perf(server): speed up headless channel posts, replies, and SSE bursts (#23426)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Headless channels, threads, and SSE streams let agents and tools
exchange high-rate status updates and structured messages
> - A local headless benchmark on `origin/master` (`828b8c2a2a`) showed
channel posts at 226 req/s (`c=1`) and 342–346 req/s (`c=32`), with
database tuple scans growing linearly with company issue count and live
SSE streams falling behind under burst
> - CPU, heap, and PostgreSQL profiling traced the bottlenecks to an
unindexed `O(N)` `MAX(issue_number)` scan per post, redundant SQL
round-trips and uncached transactional `instance_settings` reads inside
the company row lock, upfront `FOR UPDATE` locks on normal replies,
serial per-event SSE database checks, and routing through 64 unrelated
Express sub-routers
> - This pull request adds an online-compatible `issues(company_id,
issue_number)` index so `MAX(issue_number)` floor checks run as `O(log
N)` index-only probes inside the `companies` counter update, eliminates
redundant channel/view/savepoint queries, locks parent issues on replies
only when `clientRequestId` or `after` is supplied, mounts headless
routers early, and extracts a unified bounded SSE/replay filter pipeline
with creation-time `kvLabels`/`tagLabels` snapshots and pre-change label
history lookup
> - The benefit is 2.09x to 2.67x higher channel post throughput (473
req/s at `c=1`, 885–924 req/s at `c=32`), 1.75x higher reply throughput
(1,221 req/s at `c=32`), 55.5% less heap allocation, `O(log N)`
index-only counter floor checks as issue count grows, and 100% real-time
SSE delivery under burst

## Linked Issues or Issue Description

**What existing behavior does this improve?**

`POST /api/companies/:companyId/channels/posts`, `POST
/api/companies/:companyId/issues/batch`, `POST
/api/issues/:id/comments`, and `GET
/api/companies/:companyId/events/stream` throughput, tail latency, heap
allocation, and database scalability.

**Subsystem affected**

- `packages/db/ — Drizzle schema & migrations`
- `server/ — REST API & orchestration services`

**Current behavior**

On `origin/master` (`828b8c2a2a`, Node `v26.4.0`, `darwin-arm64`, local
`embedded-postgres` with 2 live SSE subscribers):
- `createChannelPost` and `createBatchIssuesPlan` run `SELECT
coalesce(max(issue_number), 0) FROM issues WHERE company_id = $1` on
every call without an index on `(company_id, issue_number)`, scanning
every issue row in the company (`2,029` tuples/request at ~2,400
issues).
- `ensureChannel` ignores the channel row already fetched by
`assertChannelPathWritePreconditions`, runs `INSERT ... ON CONFLICT DO
NOTHING`, and selects the channel a second time.
- `createChannelPost` holds the `companies` row lock while calling
`logActivity(tx, ...)` (which skips the `instance_settings` read-through
cache on `PgTransaction` handles and opens a nested `SAVEPOINT` +
`SELECT pg_current_xact_id()`), running two round-trips in
`appendBoardEvent`, and re-querying four tables in
`loadHeadlessIssueView`.
- `POST /api/issues/:id/comments` selects all 89 `issues` columns via an
unindexed `upper(identifier)` scan when given an identifier and
unconditionally acquires `SELECT ... FOR UPDATE` on `issues` even when
neither `idempotencyKey`/`clientRequestId` nor `after` is supplied.
- `GET /api/companies/:companyId/events/stream` evaluates live events
one at a time with serial `channels` and `issues` queries per event per
subscriber and misses creation-time `labels`/`tagLabels` snapshots
during `?label=` filtering, delivering only ~302–373 of 1,000 events
during a 1,000-message burst.
- `headlessChannelsSchemasRoutes` and `headlessQueuesEventsRoutes` sit
behind 64 unrelated `api.use(...)` Express sub-routers (`15%` CPU in
`path-to-regexp` and `router`).

**Proposed behavior**

- Add an online-compatible `CREATE INDEX CONCURRENTLY IF NOT EXISTS
"issues_company_issue_number_idx" ON "issues" USING btree ("company_id",
"issue_number")` migration (`0513_closed_wither.sql`) and compute
`greatest(companies.issue_counter, coalesce((select
max(issues.issue_number) from issues where issues.company_id = $1), 0))
+ count` directly in `UPDATE companies`, preserving exact monotonic
counter floors (including lone backdated imports) via an `O(log N)`
index-only backward probe in a single round-trip.
- Return the existing channel directly in `ensureChannel` when
`allowUpdateExisting` is false, serialize newly created
`HeadlessIssueView` objects in memory, sort tag labels canonically
before `ON CONFLICT DO NOTHING` upserts, and combine
`pg_advisory_xact_lock` + `INSERT INTO board_events` into one SQL
statement.
- Pre-create `createActivityDetailsRedactor(db)` before transactions so
the 2-second `instance_settings` cache applies, prime
`pg_current_xact_id()` on existing `RETURNING` clauses, and skip nested
`db.transaction` savepoints in `persistActivity` when `db` is already a
`PgTransaction` while preserving `databaseWorkContext` attribution.
- Probe `eq(issues.identifier, normalizedUpper)` first so identifier
lookups use `issues_identifier_idx`, project only the 11 required
columns in issue route interceptors, narrow `--as` profile collision
checks to non-terminated company agents with JS `.trim()` +
`deriveAgentUrlKey` parity, and acquire `FOR UPDATE` on comment creation
only when `clientRequestId` or `after` is present.
- Extract `server/src/services/headless-board-event-stream.ts` and stamp
commit-time `kvLabels` and `tagLabels` snapshots onto issue-scoped event
payloads inside `appendBoardEvent`, so `queryBoardEventsAfter`,
`waitForBoardEvent`, and `filterBoardEventsBatchForSubscriber` share a
single stateless `eventMatchesFiltersAndAccess` verdict pipeline without
cross-batch label caches.
- Mount `headlessChannelsSchemasRoutes` and `headlessQueuesEventsRoutes`
right after `headlessIdentityRoutes` with `headlessHeartbeat` wired in
`server/src/app.ts`.

**Measured performance impact**

- `POST /channels/posts` (`c=1`): `226.4` -> `473.1 req/s` (`2.09x`),
p50 `4.27ms` -> `2.05ms`, p99 `6.98ms` -> `3.15ms`
- `POST /channels/posts` (`c=32`, single channel): `346.4` -> `885.5
req/s` (`2.56x`), p50 `91.8ms` -> `35.4ms`
- `POST /channels/posts` (`c=32`, 16 channels + 2 live SSE clients):
`342.4` -> `924.6 req/s` (`2.70x`), p50 `93.3ms` -> `33.2ms`, live SSE
events delivered during run `302` -> `1,000 / 1,000`
- `POST /issues/:id/comments` (`c=32`): `696.2` -> `1,221.6 req/s`
(`1.75x`), p50 `44.9ms` -> `25.3ms`
- Profiled 1,500 mixed messages (`c=32`): heap allocated `2,369 MB` ->
`1,054 MB` (`-55.5%`).

**Breaking changes**

None. All request/response schemas, status codes, idempotency conflict
rules, `after` stale-cursor checks, gapless `board_events.seq` commit
ordering, and private channel/issue revocation rules remain unchanged.

## What Changed

- Added `issues_company_issue_number_idx` in
`packages/db/src/schema/issues.ts`,
`packages/db/src/migrations/0513_closed_wither.sql` (`CREATE INDEX
CONCURRENTLY IF NOT EXISTS`), and `MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`
in `packages/db/src/client.ts`.
- Updated `server/src/services/headless-common.ts`,
`server/src/services/headless-channels.ts`, and
`server/src/services/headless-labels-batch.ts` to compute exact indexed
`MAX(issue_number)` counter floors inside `UPDATE companies`, return
existing channels early in `ensureChannel`, prime transaction XIDs, sort
tag label names before upsert, serialize newly created
`HeadlessIssueView` responses in memory, include `kvLabels` and
`tagLabels` snapshots on creation/ready board events, and combine
`pg_advisory_xact_lock` + `INSERT INTO board_events` into a single
round-trip.
- Updated `server/src/services/activity-log.ts` to accept an optional
pre-built `ActivityDetailsRedactor` and skip nested `db.transaction`
savepoints when `persistActivity` runs on an existing `PgTransaction`
while preserving `databaseWorkContext` attribution.
- Updated `server/src/routes/headless-channels-schemas.ts` to use
`resolveIssueCommentTarget`, pre-create the activity redactor on `db`,
prime transaction XIDs on comment inserts, and lock the parent issue
`FOR UPDATE` only when `clientRequestId` or `after` is supplied.
- Extracted `server/src/services/headless-board-event-stream.ts`
(re-exported from
`server/src/services/headless-events-schedules-interactions.ts`) and
updated `server/src/services/headless-common.ts`,
`server/src/routes/headless-queues-events.ts`, and `server/src/app.ts`
to stamp commit-time `kvLabels` and `tagLabels` snapshots in
`appendBoardEvent`, unify single-event, replay, and batched SSE
filtering without cross-batch label caches, and mount headless routers
early with `headlessHeartbeat`.
- Added regression tests in
`server/src/__tests__/headless-channels-schemas-batch.test.ts` (drifted
`issueCounter` + lone backdated `#95` floor, concurrent tag upserts, and
tab/CJK `--as` profile parity) and
`server/src/__tests__/headless-queues-leases-events.test.ts` (live SSE
burst ordering, cold-cache `?label=urgent` `exists` tag +
`labels.changed` interleaving + unlabeled `comment.posted`, and
immediate private-channel revocation).

## Verification

- `pnpm --filter @paperclipai/db run check:migrations && pnpm --filter
@paperclipai/db exec vitest run src/migration-snapshot-drift.test.ts`
(passed, 0 blocked migrations)
- `cd server && node scripts/typecheck-layers.mjs` (0 errors across all
7 layers)
- `pnpm --filter @paperclipai/server exec vitest run
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` (5 files, 41/41
tests passed)

## Risks

- Low risk. Migration `0513_closed_wither.sql` uses `CREATE INDEX
CONCURRENTLY IF NOT EXISTS` and is registered in
`MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS`, so online rollouts do not block
reads or writes on `issues`. Live SSE micro-batching re-evaluates
channel and issue visibility fresh on every drained batch without
cross-batch permission caching, preserving immediate membership
revocation.

## 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 01:47:17 +00:00
1 parent c59a56883c
commit c47452699a
17 files changed
+3903 -921

No files matched your search

@@ -1,5 +1,6 @@
import os from "node:os";
import { randomUUID } from "node:crypto";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { eq } from "drizzle-orm";
import {
activityLog,
@@ -9,14 +10,19 @@ import {
createDb,
heartbeatRuns,
issues,
subscribeDatabaseWork,
type Db,
} from "@paperclipai/db";
import {
createActivityDetailsRedactor,
logActivity,
persistActivity,
resolveResponsibleUserIdForActivity,
type ActivityPublication,
type LogActivityInput,
} from "../services/activity-log.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
import { instanceSettingsService } from "../services/instance-settings.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
@@ -243,4 +249,84 @@ describeEmbeddedPostgres("logActivity responsible-user stamping", () => {
expect(row?.responsibleUserId).toBe("key-user");
});
it("reuses a supplied redactor and skips nested savepoints when persistActivity runs inside a PgTransaction", async () => {
const companyId = randomUUID();
const issueId = randomUUID();
const currentUsername = os.userInfo().username;
await db.insert(companies).values({
id: companyId,
name: "TxActivityCo",
issuePrefix: `A${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
defaultResponsibleUserId: "tx-owner",
requireBoardApprovalForNewAgents: false,
});
await db.insert(issues).values({
id: issueId,
companyId,
title: "Transactional activity issue",
status: "todo",
scope: "board",
responsibleUserId: "tx-owner",
});
await instanceSettingsService(db).updateGeneral({
censorUsernameInLogs: true,
});
try {
const redactor = await createActivityDetailsRedactor(db);
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");
await persistActivity(
tx as unknown as Db,
{
companyId,
actorType: "user",
actorId: "tx-owner",
action: "issue.comment_added",
entityType: "issue",
entityId: issueId,
issueId,
responsibleUserIdOverride: "tx-owner",
details: {
workspacePath: `/Users/${currentUsername}/project`,
},
},
undefined,
{ redactor },
);
expect(nestedTxSpy).not.toHaveBeenCalled();
});
} finally {
unsubscribe();
}
expect(settledHints).toContain(`task:${issueId}`);
const [stored] = await db
.select({ details: activityLog.details })
.from(activityLog)
.where(eq(activityLog.entityId, issueId));
const workspacePath = String(
(stored?.details as Record<string, unknown> | null)?.workspacePath ?? "",
);
expect(workspacePath).not.toContain(currentUsername);
} finally {
await instanceSettingsService(db).updateGeneral({
censorUsernameInLogs: false,
});
}
});
});
@@ -18,6 +18,7 @@ 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 { issueService } from "../services/issues.js";
import {
getEmbeddedPostgresTestSupport,
@@ -1327,4 +1328,168 @@ describeEmbeddedPostgres("headless channels, schemas, CAS labels, and batch DAG"
},
]);
});
it("10. self-heals drifted company issueCounter on channel post and batch create without O(N) pre-scans", 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 [companyRow] = await db
.select({ issuePrefix: companies.issuePrefix })
.from(companies)
.where(eq(companies.id, companyId));
const prefix = companyRow!.issuePrefix;
await db.insert(issues).values({
companyId,
title: "Imported legacy #50 without #1..49",
status: "backlog",
scope: "board",
issueNumber: 50,
identifier: `${prefix}-50`,
createdByUserId: ownerUserId,
});
await db
.update(companies)
.set({ issueCounter: 0 })
.where(eq(companies.id, companyId));
const postRes = await request(app)
.post(`/api/companies/${companyId}/channels/posts`)
.set("x-test-user-id", ownerUserId)
.set("x-paperclip-actor-profile", "perf-bot")
.send({
channel: "eng/perf",
text: "Post after non-colliding drifted counter",
labels: { env: "prod" },
tagLabels: ["fast-path"],
})
.expect(201);
expect(postRes.body.identifier).toBe(`${prefix}-51`);
expect(postRes.body.channel).toBe("eng/perf");
expect(postRes.body.kvLabels).toEqual({ env: "prod" });
expect(postRes.body.tagLabels).toEqual(["fast-path"]);
expect(postRes.body.actorProfile).toBe("perf-bot");
await db.insert(issues).values({
companyId,
title: "Lone backdated imported #95 without #52..94",
status: "backlog",
scope: "board",
issueNumber: 95,
identifier: `${prefix}-95`,
createdByUserId: ownerUserId,
createdAt: new Date("2000-01-01T00:00:00.000Z"),
updatedAt: new Date("2000-01-01T00:00:00.000Z"),
});
const batchRes = await request(app)
.post(`/api/companies/${companyId}/issues/batch`)
.set("x-test-user-id", ownerUserId)
.send({
channel: "eng/perf",
tasks: [
{ key: "t1", title: "Batch task 1" },
{ key: "t2", title: "Batch task 2", needs: ["t1"] },
],
})
.expect(201);
expect(batchRes.body.tasks.map((t: { identifier: string }) => t.identifier)).toEqual([
`${prefix}-96`,
`${prefix}-97`,
]);
const [concurrentPost, concurrentBatch] = await Promise.all([
request(app)
.post(`/api/companies/${companyId}/channels/posts`)
.set("x-test-user-id", ownerUserId)
.send({
channel: "eng/perf",
text: "Concurrent tagged post",
tagLabels: ["shared-concurrent-z", "shared-concurrent-a"],
}),
request(app)
.post(`/api/companies/${companyId}/issues/batch`)
.set("x-test-user-id", ownerUserId)
.send({
channel: "eng/perf",
tasks: [
{
key: "ct1",
title: "Concurrent tagged batch task",
tagLabels: ["shared-concurrent-a", "shared-concurrent-z"],
},
],
}),
]);
expect(concurrentPost.status).toBe(201);
expect(concurrentBatch.status).toBe(201);
expect(concurrentPost.body.tagLabels.sort()).toEqual([
"shared-concurrent-a",
"shared-concurrent-z",
]);
await db.insert(agents).values([
{
companyId,
name: "\t雪\t",
role: "engineer",
status: "idle",
},
{
companyId,
name: "\tguardian-bot\t",
role: "engineer",
status: "idle",
},
]);
const tabReservedRes = await request(app)
.post(`/api/companies/${companyId}/channels/posts`)
.set("x-test-user-id", ownerUserId)
.set("x-paperclip-actor-profile", "guardian-bot")
.send({ channel: "eng/perf", text: "Should collide with tab-padded agent" });
expect(tabReservedRes.status).toBe(409);
expect(tabReservedRes.body.code).toBe("profile_matches_registered_agent");
await expect(
resolveHeadlessActor(
db,
{
actor: {
type: "board",
userId: ownerUserId,
source: "session",
companyIds: [companyId],
isInstanceAdmin: false,
},
header: (name: string) =>
name.toLowerCase() === "x-paperclip-actor-profile" ? "雪" : undefined,
} as any,
companyId,
{ deploymentMode: "authenticated", requiredAction: "post" },
),
).rejects.toMatchObject({
status: 409,
});
});
});
@@ -15,6 +15,7 @@ import {
agents,
authUsers,
boardEvents,
channelAccessMembers,
channels,
companies,
companyMemberships,
@@ -28,6 +29,7 @@ import {
issueThreadInteractions,
issueTreeHolds,
issueWorkProducts,
labels,
projectAccessMembers,
projects,
reconcileDatabaseWork,
@@ -45,6 +47,7 @@ import {
import { parseSseEventStream } from "@paperclipai/shared/sdk/sse";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js";
import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js";
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
@@ -55,6 +58,7 @@ import {
import { createScheduledBoardPostsWorker } from "../services/headless-events-schedules-interactions.js";
import { createClaimLeaseExpiryWorker } from "../services/headless-task-queue.js";
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
import { issueService } from "../services/issues.js";
import { recoveryService } from "../services/recovery/service.js";
import {
getEmbeddedPostgresTestSupport,
@@ -93,6 +97,7 @@ function createTestServer(db: Db) {
}
next();
});
app.use("/api", headlessChannelsSchemasRoutes(db));
app.use("/api", headlessQueuesEventsRoutes(db));
app.use(errorHandler);
return createServer(app);
@@ -1562,4 +1567,524 @@ describeEmbeddedPostgres("headless queues, fenced leases, events & interactions"
const wokenClaim = (await wokenClaimRes.json()) as TaskClaimView;
expect(wokenClaim.issue.id).toBe(poolDep.id);
});
it("11. drains live SSE bursts in strict seq order with payload.labels filtering and immediate private-channel revocation", async () => {
const { company, channel: openCh, agent } = await seedCompanyAndChannel("sse-burst");
const [privCh] = await db
.insert(channels)
.values({
companyId: company.id,
path: "sec/live",
visibility: "private",
createdByUserId: "owner-user",
})
.returning();
await db.insert(channelAccessMembers).values({
companyId: company.id,
channelId: privCh!.id,
subjectType: "agent",
subjectId: agent.id,
});
const openIssue = await seedTask(company.id, company.issuePrefix, {
title: "Open burst thread",
channelId: openCh.id,
});
const [privIssue] = await db
.insert(issues)
.values({
companyId: company.id,
channelId: privCh!.id,
visibility: "private",
title: "Private burst thread",
status: "backlog",
scope: "channel",
issueNumber: ++issueSeq + 5000,
identifier: `${company.issuePrefix}-${issueSeq + 5000}`,
createdByUserId: "owner-user",
})
.returning();
await db
.update(issues)
.set({ privacyRootIssueId: privIssue!.id })
.where(eq(issues.id, privIssue!.id));
const ac = new AbortController();
const res = await fetch(
`${baseUrl}/api/companies/${company.id}/events/stream?label=env%3Dprod`,
{
headers: {
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
signal: ac.signal,
},
);
expect(res.status).toBe(200);
expect(res.body).not.toBeNull();
const received: BoardEventView[] = [];
const readerDone = (async () => {
for await (const ev of parseSseEventStream(res.body!, ac.signal)) {
received.push(ev);
}
})().catch(() => {});
try {
await new Promise((r) => setTimeout(r, 50));
const expectedSeqs: number[] = [];
for (let i = 0; i < 25; i += 1) {
const matchEv = await appendBoardEvent(db, {
companyId: company.id,
type: "thread.posted",
channelId: openCh.id,
channelPath: openCh.path,
issueId: openIssue.id,
identifier: openIssue.identifier,
actor: {
principalType: "user",
userId: "owner-user",
agentId: null,
agentName: null,
actorProfile: "burst-bot",
},
payload: { title: `Burst #${i}`, labels: { env: "prod", idx: String(i) } },
});
expectedSeqs.push(matchEv.seq);
publishCommittedBoardEvent(matchEv);
if (i < 10) {
const skipEv = await appendBoardEvent(db, {
companyId: company.id,
type: "thread.posted",
channelId: openCh.id,
channelPath: openCh.path,
issueId: openIssue.id,
identifier: openIssue.identifier,
actor: {
principalType: "user",
userId: "owner-user",
agentId: null,
agentName: null,
actorProfile: "burst-bot",
},
payload: { title: `Skip #${i}`, labels: { env: "staging" } },
});
publishCommittedBoardEvent(skipEv);
}
}
const allowedPrivEv = await appendBoardEvent(db, {
companyId: company.id,
type: "thread.posted",
channelId: privCh!.id,
channelPath: privCh!.path,
issueId: privIssue!.id,
identifier: privIssue!.identifier,
actor: {
principalType: "user",
userId: "owner-user",
agentId: null,
agentName: null,
actorProfile: "owner",
},
payload: { title: "Before revocation", labels: { env: "prod" } },
});
expectedSeqs.push(allowedPrivEv.seq);
publishCommittedBoardEvent(allowedPrivEv);
await vi.waitFor(() => {
expect(received.map((e) => e.seq)).toEqual(expectedSeqs);
});
await db
.delete(channelAccessMembers)
.where(
and(
eq(channelAccessMembers.channelId, privCh!.id),
eq(channelAccessMembers.subjectId, agent.id),
),
);
const revokedPrivEv = await appendBoardEvent(db, {
companyId: company.id,
type: "thread.posted",
channelId: privCh!.id,
channelPath: privCh!.path,
issueId: privIssue!.id,
identifier: privIssue!.identifier,
actor: {
principalType: "user",
userId: "owner-user",
agentId: null,
agentName: null,
actorProfile: "owner",
},
payload: { title: "After revocation", labels: { env: "prod" } },
});
publishCommittedBoardEvent(revokedPrivEv);
const sentinelEv = await appendBoardEvent(db, {
companyId: company.id,
type: "thread.posted",
channelId: openCh.id,
channelPath: openCh.path,
issueId: openIssue.id,
identifier: openIssue.identifier,
actor: {
principalType: "user",
userId: "owner-user",
agentId: null,
agentName: null,
actorProfile: "burst-bot",
},
payload: { title: "Sentinel after revocation", labels: { env: "prod" } },
});
expectedSeqs.push(sentinelEv.seq);
publishCommittedBoardEvent(sentinelEv);
await vi.waitFor(() => {
expect(received.map((e) => e.seq)).toEqual(expectedSeqs);
});
} finally {
ac.abort();
await readerDone;
}
const [urgentLabelRow] = await db
.insert(labels)
.values({
companyId: company.id,
name: "urgent",
color: "#ef4444",
})
.returning();
const [maxBeforeRealBurst] = await db
.select({ maxSeq: sql<number>`coalesce(max(${boardEvents.seq}), 0)::int` })
.from(boardEvents)
.where(eq(boardEvents.companyId, company.id));
const afterBeforeRealBurst = `evt_${maxBeforeRealBurst?.maxSeq ?? 0}`;
const claimOnlyAc = new AbortController();
const claimOnlyRes = await fetch(
`${baseUrl}/api/companies/${company.id}/events/stream?event=task.claimed&label=urgent`,
{
headers: {
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
signal: claimOnlyAc.signal,
},
);
expect(claimOnlyRes.status).toBe(200);
const claimOnlyReceived: BoardEventView[] = [];
const claimOnlyDone = (async () => {
for await (const ev of parseSseEventStream(claimOnlyRes.body!, claimOnlyAc.signal)) {
claimOnlyReceived.push(ev);
}
})().catch(() => {});
const existsAc = new AbortController();
const existsRes = await fetch(
`${baseUrl}/api/companies/${company.id}/events/stream?label=urgent`,
{
headers: {
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
signal: existsAc.signal,
},
);
expect(existsRes.status).toBe(200);
const existsReceived: BoardEventView[] = [];
const existsReaderDone = (async () => {
for await (const ev of parseSseEventStream(existsRes.body!, existsAc.signal)) {
existsReceived.push(ev);
}
})().catch(() => {});
try {
await new Promise((r) => setTimeout(r, 50));
const untaggedCreateRes = await fetch(
`${baseUrl}/api/companies/${company.id}/channels/posts`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
channel: "burst/open/real-1",
status: "todo",
title: "Initially untagged task",
}),
},
);
expect(untaggedCreateRes.status).toBe(201);
const untaggedTask = (await untaggedCreateRes.json()) as HeadlessIssueView;
await issueService(db).update(untaggedTask.id, {
labelIds: [urgentLabelRow!.id],
});
const untaggedClaimRes = await fetch(
`${baseUrl}/api/companies/${company.id}/tasks/claim`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
body: JSON.stringify({ channel: "burst/open/real-1" }),
},
);
expect(untaggedClaimRes.status).toBe(200);
const untaggedClaim = (await untaggedClaimRes.json()) as TaskClaimView;
expect(untaggedClaim.issue.id).toBe(untaggedTask.id);
await vi.waitFor(() => {
expect(
claimOnlyReceived.map((e) => `${e.issueId}:${e.type}`),
).toContain(`${untaggedTask.id}:task.claimed`);
expect(
existsReceived.map((e) => `${e.issueId}:${e.type}`),
).toContain(`${untaggedTask.id}:task.claimed`);
});
expect(
claimOnlyReceived.find((e) => e.issueId === untaggedTask.id)?.payload.tagLabels,
).toEqual(["urgent"]);
await issueService(db).update(untaggedTask.id, { labelIds: [] });
const untaggedReleaseRes = await fetch(
`${baseUrl}/api/issues/${untaggedTask.id}/claim/release`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-paperclip-claim-token": untaggedClaim.claimToken,
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
body: JSON.stringify({ claimEpoch: untaggedClaim.claimEpoch }),
},
);
expect(untaggedReleaseRes.status).toBe(200);
const taggedCreateRes = await fetch(
`${baseUrl}/api/companies/${company.id}/channels/posts`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
channel: "burst/open/real-2",
status: "todo",
title: "Tagged lifecycle task",
tagLabels: ["urgent"],
}),
},
);
expect(taggedCreateRes.status).toBe(201);
const taggedTask = (await taggedCreateRes.json()) as HeadlessIssueView;
const taggedClaimRes = await fetch(
`${baseUrl}/api/companies/${company.id}/tasks/claim`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
body: JSON.stringify({ channel: "burst/open/real-2" }),
},
);
expect(taggedClaimRes.status).toBe(200);
const taggedClaim = (await taggedClaimRes.json()) as TaskClaimView;
expect(taggedClaim.issue.id).toBe(taggedTask.id);
const taggedCommentRes = await fetch(
`${baseUrl}/api/issues/${taggedTask.id}/comments`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ body: "Unlabeled comment while issue has urgent tag" }),
},
);
expect(taggedCommentRes.status).toBe(201);
await vi.waitFor(() => {
expect(
existsReceived.map((e) => `${e.issueId}:${e.type}`),
).toContain(`${taggedTask.id}:comment.posted`);
});
expect(
existsReceived.find(
(e) => e.issueId === taggedTask.id && e.type === "task.claimed",
)?.payload.tagLabels,
).toEqual(["urgent"]);
expect(
existsReceived.find(
(e) => e.issueId === taggedTask.id && e.type === "comment.posted",
)?.payload.tagLabels,
).toEqual(["urgent"]);
await issueService(db).update(taggedTask.id, { labelIds: [] });
const taggedReleaseRes = await fetch(
`${baseUrl}/api/issues/${taggedTask.id}/claim/release`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-paperclip-claim-token": taggedClaim.claimToken,
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
body: JSON.stringify({ claimEpoch: taggedClaim.claimEpoch }),
},
);
expect(taggedReleaseRes.status).toBe(200);
const kvCreateRes = await fetch(
`${baseUrl}/api/companies/${company.id}/channels/posts`,
{
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
channel: "burst/open/real-3",
status: "todo",
title: "KV urgent lifecycle task",
labels: { urgent: "1" },
}),
},
);
expect(kvCreateRes.status).toBe(201);
const kvTask = (await kvCreateRes.json()) as HeadlessIssueView;
const kvClaimRes = await fetch(
`${baseUrl}/api/companies/${company.id}/tasks/claim`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
body: JSON.stringify({ channel: "burst/open/real-3" }),
},
);
expect(kvClaimRes.status).toBe(200);
const kvClaim = (await kvClaimRes.json()) as TaskClaimView;
expect(kvClaim.issue.id).toBe(kvTask.id);
const [legacyPreDeployRow] = await db
.insert(boardEvents)
.values({
companyId: company.id,
eventType: "task.lease_renewed",
channelId: openCh.id,
channelPath: "burst/open/real-3",
issueId: kvTask.id,
identifier: kvTask.identifier,
actorType: "agent",
actorId: agent.id,
actorName: agent.name,
payload: { leaseExpiresAt: "2099-01-01T00:00:00.000Z" },
})
.returning();
const kvUnsetRes = await fetch(
`${baseUrl}/api/issues/${kvTask.id}/kv-labels`,
{
method: "PATCH",
headers: { "content-type": "application/json" },
body: JSON.stringify({ unset: ["urgent"] }),
},
);
expect(kvUnsetRes.status).toBe(200);
const kvReleaseRes = await fetch(
`${baseUrl}/api/issues/${kvTask.id}/claim/release`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-paperclip-claim-token": kvClaim.claimToken,
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
body: JSON.stringify({ claimEpoch: kvClaim.claimEpoch }),
},
);
expect(kvReleaseRes.status).toBe(200);
const expectedLivePairs = [
`${untaggedTask.id}:task.claimed`,
`${taggedTask.id}:task.created`,
`${taggedTask.id}:task.ready`,
`${taggedTask.id}:task.claimed`,
`${taggedTask.id}:comment.posted`,
`${kvTask.id}:task.created`,
`${kvTask.id}:task.ready`,
`${kvTask.id}:task.claimed`,
];
await vi.waitFor(() => {
expect(existsReceived.map((e) => `${e.issueId}:${e.type}`)).toEqual(
expectedLivePairs,
);
});
const expectedReplayPairs = [
...expectedLivePairs,
`${kvTask.id}:task.lease_renewed`,
];
expect(legacyPreDeployRow).toBeDefined();
const replayAc = new AbortController();
const replayRes = await fetch(
`${baseUrl}/api/companies/${company.id}/events/stream?after=${encodeURIComponent(afterBeforeRealBurst)}&label=urgent`,
{
headers: {
"x-test-actor-type": "agent",
"x-test-agent-id": agent.id,
"x-test-company-id": company.id,
},
signal: replayAc.signal,
},
);
expect(replayRes.status).toBe(200);
const replayReceived: BoardEventView[] = [];
const replayDone = (async () => {
for await (const ev of parseSseEventStream(replayRes.body!, replayAc.signal)) {
replayReceived.push(ev);
}
})().catch(() => {});
try {
await vi.waitFor(() => {
expect(replayReceived.map((e) => `${e.issueId}:${e.type}`)).toEqual(
expectedReplayPairs,
);
});
} finally {
replayAc.abort();
await replayDone;
}
} finally {
claimOnlyAc.abort();
existsAc.abort();
await Promise.all([claimOnlyDone, existsReaderDone]);
}
});
});
+9 -5
View File
@@ -785,7 +785,16 @@ export async function createApp(
api.use("/cloud", cloudRoutes());
api.use(cloudInferenceRoutes(db, cloudTrialInferenceController));
api.use(onboardingTelemetryRoutes());
const headlessHeartbeat = heartbeatService(db, { pluginWorkerManager: workerManager });
api.use(headlessIdentityRoutes(db, { deploymentMode: opts.deploymentMode }));
api.use(headlessChannelsSchemasRoutes(db, {
deploymentMode: opts.deploymentMode,
heartbeat: headlessHeartbeat,
}));
api.use(headlessQueuesEventsRoutes(db, {
deploymentMode: opts.deploymentMode,
heartbeat: headlessHeartbeat,
}));
api.use("/companies", companyRoutes(db, opts.storageService));
api.use(llmRoutes(db));
api.use(folderRoutes(db));
@@ -1012,11 +1021,6 @@ export async function createApp(
// Issue routes are intentionally mounted after the gateway is constructed because
// issue approval endpoints delegate to it. The intervening routers use distinct
// route prefixes, so this dependency does not change issue-route precedence.
api.use(headlessChannelsSchemasRoutes(db, { deploymentMode: opts.deploymentMode }));
api.use(headlessQueuesEventsRoutes(db, {
deploymentMode: opts.deploymentMode,
heartbeat: heartbeatService(db, { pluginWorkerManager: workerManager }),
}));
api.use(issueRoutes(db, opts.storageService, {
chatRunRetries: chatChannels,
pluginWorkerManager: workerManager,
+46 -17
View File
@@ -22,6 +22,7 @@ import {
issueRelations,
issues,
issueThreadInteractions,
primeDatabaseWorkTransactionId,
projects,
} from "@paperclipai/db";
import {
@@ -56,6 +57,7 @@ import {
updateChannel,
} from "../services/headless-channel-admin.js";
import {
createActivityDetailsRedactor,
logActivity,
publishActivity,
type ActivityPublication,
@@ -92,6 +94,7 @@ import {
resolveHeadlessActor,
resolveHeadlessIssueReadCondition,
resolveIssueByIdOrIdentifier,
resolveIssueCommentTarget,
resolveProjectReference,
serializeCommentView,
} from "../services/headless-common.js";
@@ -562,9 +565,9 @@ export function headlessChannelsSchemasRoutes(
const hasProfileHeader = Boolean(req.header("x-paperclip-actor-profile"));
const isExplicitHeadless = hasHeadlessBody || hasProfileHeader;
let targetIssue: typeof issues.$inferSelect;
let targetIssue: Awaited<ReturnType<typeof resolveIssueCommentTarget>>;
try {
targetIssue = await resolveIssueByIdOrIdentifier(
targetIssue = await resolveIssueCommentTarget(
db,
req.params.id as string,
);
@@ -633,11 +636,14 @@ export function headlessChannelsSchemasRoutes(
data: schemaInput.data as Record<string, unknown>,
});
}
const validatedBlocks = await validateSchemaBlocks(
db,
targetIssue.companyId,
combinedBlocks,
);
const validatedBlocks =
combinedBlocks.length > 0
? await validateSchemaBlocks(
db,
targetIssue.companyId,
combinedBlocks,
)
: [];
let bodyText =
typeof b.body === "string" && b.body.length > 0
@@ -671,15 +677,20 @@ export function headlessChannelsSchemasRoutes(
const authorUserId = actor.agentId ? null : (actor.userId ?? "local-board");
const identifier = targetIssue.identifier ?? targetIssue.id;
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) => {
await tx
.select({ id: issues.id })
.from(issues)
.where(eq(issues.id, targetIssue.id))
.for("update");
if (needsSerializedThreadCheck) {
await tx
.select({ id: issues.id })
.from(issues)
.where(eq(issues.id, targetIssue.id))
.for("update");
}
if (clientRequestId) {
const [existing] = await tx
@@ -754,7 +765,24 @@ export function headlessChannelsSchemasRoutes(
createdAt: now,
updatedAt: now,
})
.returning();
.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`,
});
if (inserted?.xid) {
primeDatabaseWorkTransactionId(tx, inserted.xid);
}
await tx
.update(issues)
@@ -790,6 +818,7 @@ export function headlessChannelsSchemasRoutes(
},
},
publications,
{ redactor: activityRedactor },
);
committedEvent = await appendBoardEvent(tx, {
@@ -853,9 +882,9 @@ export function headlessChannelsSchemasRoutes(
return;
}
let targetIssue: typeof issues.$inferSelect;
let targetIssue: Awaited<ReturnType<typeof resolveIssueCommentTarget>>;
try {
targetIssue = await resolveIssueByIdOrIdentifier(
targetIssue = await resolveIssueCommentTarget(
db,
req.params.id as string,
);
@@ -1524,9 +1553,9 @@ export function headlessChannelsSchemasRoutes(
const isBrowserRequest =
Boolean(req.header("referer")) || Boolean(req.header("sec-fetch-mode"));
let targetIssue: typeof issues.$inferSelect;
let targetIssue: Awaited<ReturnType<typeof resolveIssueCommentTarget>>;
try {
targetIssue = await resolveIssueByIdOrIdentifier(
targetIssue = await resolveIssueCommentTarget(
db,
req.params.id as string,
);
+47 -37
View File
@@ -44,7 +44,7 @@ import {
cancelSchedule,
confirmOnIssue,
createSchedule,
eventMatchesFiltersAndAccess,
filterBoardEventsBatchForSubscriber,
getCurrentCompanyMaxEventSeq,
listSchedules,
parseBoardEventFilters,
@@ -662,48 +662,57 @@ export function headlessQueuesEventsRoutes(
let replaying = true;
let lastSentSeq = parsedFilters.afterSeq;
const buffered: BoardEventView[] = [];
const issueLabelCache = new Map<
string,
{ kvLabels: Record<string, string>; tagLabels: string[] }
>();
const pendingLiveEvents: BoardEventView[] = [];
let drainingLive = false;
const drainLiveEvents = async () => {
if (drainingLive || closed) return;
drainingLive = true;
try {
while (!closed && pendingLiveEvents.length > 0) {
const rawBatch = pendingLiveEvents.splice(0, 256);
const unseenBatch = rawBatch.filter((ev) => ev.seq > lastSentSeq);
if (unseenBatch.length === 0) continue;
// Serialize live filter checks and writes so SSE frames preserve order.
let writeChain = Promise.resolve();
const matched = await filterBoardEventsBatchForSubscriber(
db,
companyId,
actor,
unseenBatch,
parsedFilters,
req.actor,
undefined,
pendingLiveEvents,
);
if (closed) break;
const deliverEvent = async (ev: BoardEventView) => {
if (ev.type === "labels.changed" && ev.issueId) {
issueLabelCache.delete(ev.issueId);
const frames: string[] = [];
for (const ev of matched) {
if (ev.seq <= lastSentSeq) continue;
lastSentSeq = ev.seq;
frames.push(formatSseFrame(ev));
}
if (frames.length > 0 && !closed) {
res.write(frames.join(""));
}
}
} catch (err) {
void err;
} finally {
drainingLive = false;
if (!closed && pendingLiveEvents.length > 0) {
void drainLiveEvents();
}
}
if (closed || ev.seq <= lastSentSeq) return;
// Evaluate channel access fresh on live events so revoked channel membership applies immediately.
const matches = await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsedFilters,
undefined,
issueLabelCache,
undefined,
req.actor,
);
if (closed || !matches || ev.seq <= lastSentSeq) return;
lastSentSeq = ev.seq;
res.write(formatSseFrame(ev));
};
const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => {
if (closed) return;
if (ev.type === "labels.changed" && ev.issueId) {
issueLabelCache.delete(ev.issueId);
}
if (replaying) {
buffered.push(ev);
return;
}
writeChain = writeChain
.then(() => deliverEvent(ev))
.catch(() => {});
pendingLiveEvents.push(ev);
void drainLiveEvents();
});
const keepaliveTimer = setInterval(() => {
@@ -753,13 +762,14 @@ export function headlessQueuesEventsRoutes(
parsedFilters.afterSeq = maxSeq;
lastSentSeq = maxSeq;
}
replaying = false;
if (!closed && buffered.length > 0) {
buffered.sort((a, b) => a.seq - b.seq);
for (const ev of buffered) {
await deliverEvent(ev);
}
pendingLiveEvents.push(...buffered);
}
replaying = false;
if (!closed && pendingLiveEvents.length > 0) {
await drainLiveEvents();
}
} catch {
cleanup();
+38 -11
View File
@@ -5,7 +5,8 @@ import { beginRunPhase } from "./execution-preparation-timing.js";
import type { ActivityPublication } from "../types/activity-publication.js";
export type { ActivityPublication } from "../types/activity-publication.js";
import { randomUUID } from "node:crypto";
import { and, eq } from "drizzle-orm";
import { and, eq, is } from "drizzle-orm";
import { PgTransaction } from "drizzle-orm/pg-core";
import type { Db } from "@paperclipai/db";
import { activityLog, agentApiKeys, companies, heartbeatRuns, issues } from "@paperclipai/db";
import { isUuidLike, PLUGIN_EVENT_TYPES, type PluginEventType } from "@paperclipai/shared";
@@ -74,7 +75,15 @@ export interface LogActivityInput {
}
export async function createActivityDetailsRedactor(db: Db) {
export type ActivityDetailsRedactor = (
details: Record<string, unknown> | null,
) => Record<string, unknown> | null;
export interface PersistActivityOptions {
redactor?: ActivityDetailsRedactor;
}
export async function createActivityDetailsRedactor(db: Db): Promise<ActivityDetailsRedactor> {
const currentUserRedactionOptions = {
enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs,
};
@@ -171,8 +180,22 @@ export function publishActivity(publication: ActivityPublication) {
} finally { finish(); }
}
export async function persistActivity(db: Db, input: LogActivityInput, receipt?: { id: string }) {
const redactedDetails = await redactActivityDetails(db, input.authorization ? { ...input.details, permissionDecision: input.authorization, ...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}) } : input.details ?? null);
export async function persistActivity(
db: Db,
input: LogActivityInput,
receipt?: { id: string },
options?: PersistActivityOptions,
) {
const rawDetails = input.authorization
? {
...input.details,
permissionDecision: input.authorization,
...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}),
}
: (input.details ?? null);
const redactedDetails = options?.redactor
? options.redactor(rawDetails)
: await redactActivityDetails(db, rawDetails);
const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input);
const insert = (runner: Db) => runner.insert(activityLog).values({
...(receipt ? { id: receipt.id } : {}),
@@ -187,13 +210,16 @@ export async function persistActivity(db: Db, input: LogActivityInput, receipt?:
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"
? await db.transaction(async tx => {
await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`);
if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status)))
await notifyActiveRunSilence(tx, { companyId: input.companyId, runId: input.runId });
return insert(tx as unknown as Db);
})
? (is(db, PgTransaction)
? await insertIssueActivity(db)
: await db.transaction(async tx => insertIssueActivity(tx as unknown as Db)))
: await insert(db);
const payload = {
@@ -242,8 +268,9 @@ export async function logActivity(
db: Db,
input: LogActivityInput,
postCommitPublications?: ActivityPublication[],
options?: PersistActivityOptions,
) {
const { activity, publication } = await persistActivity(db, input);
const { activity, publication } = await persistActivity(db, input, undefined, options);
if (postCommitPublications) {
postCommitPublications.push(publication);
} else {
@@ -0,0 +1,848 @@
import { and, asc, eq, gt, inArray } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
boardEvents,
channels,
issueLabels,
issues,
labels,
} from "@paperclipai/db";
import {
boardEventTypeSchema,
formatEventCursor,
isUuidLike,
matchesLabelFilter,
normalizeChannelPath,
normalizeIssueIdentifier,
parseEventCursor,
parseLabelFilterExpr,
parseSchemaRef,
type BoardEventType,
type BoardEventView,
type LabelFilterExpr,
type SchemaBlock,
} from "@paperclipai/shared";
import { badRequest } from "../errors.js";
import { issueReadSqlCondition, type AuthorizationActor } from "./authorization.js";
import {
buildAuthActorFromHeadless,
canAccessChannel,
enforceHeadlessScopes,
findInaccessibleChannelIds,
getLatestCompanyEventCursor,
subscribeCompanyBoardEvents,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
export type IssueLabelSnapshot = {
kvLabels: Record<string, string>;
tagLabels: string[];
};
export type IssueLabelCache = Map<string, IssueLabelSnapshot>;
export interface BoardEventFilterInput {
channel?: string;
issueId?: string;
event?: BoardEventType[];
label?: string[];
mentions?: string;
schema?: string;
after?: string;
}
export interface ParsedBoardEventFilters {
afterSeq: number;
hasExplicitAfter: boolean;
channelNorm: { path: string; isSubtreePrefix: boolean } | null;
issueUuid: string | null;
issueIdentifierUpper: string | null;
eventTypes: Set<BoardEventType> | null;
labelExprs: LabelFilterExpr[];
mentionsName: string | null;
schemaFilter: { name: string; version: null | number } | null;
}
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function isChannelAllowedByScopes(
actor: HeadlessActorContext,
channelPath: string,
): boolean {
try {
enforceHeadlessScopes(actor, { channelPath });
return true;
} catch {
return false;
}
}
function isStringRecord(val: unknown): val is Record<string, string> {
return Boolean(val) && typeof val === "object" && !Array.isArray(val);
}
function extractIssuePayloadKvLabels(
ev: BoardEventView,
): Record<string, string> | null {
if (ev.type === "labels.changed" && isStringRecord(ev.payload.current)) {
return ev.payload.current;
}
if (isStringRecord(ev.payload.kvLabels)) return ev.payload.kvLabels;
if (isStringRecord(ev.payload.current)) return ev.payload.current;
if (
(ev.type === "thread.posted" ||
ev.type === "task.created" ||
ev.type === "task.ready") &&
isStringRecord(ev.payload.labels)
) {
return ev.payload.labels;
}
return null;
}
function extractPayloadTagLabels(
payload: Record<string, unknown>,
): string[] | undefined {
return Array.isArray(payload.tagLabels)
? payload.tagLabels.filter((x): x is string => typeof x === "string")
: undefined;
}
export function parseBoardEventFilters(
filters: BoardEventFilterInput,
): ParsedBoardEventFilters {
let afterSeq = 0;
let hasExplicitAfter = false;
if (filters.after !== undefined && filters.after.trim() !== "") {
const parsed = parseEventCursor(filters.after);
if (parsed === null) {
throw badRequest(
`Invalid cursor "${filters.after}": expected evt_<non-negative-integer>`,
);
}
afterSeq = parsed;
hasExplicitAfter = true;
}
let channelNorm: { path: string; isSubtreePrefix: boolean } | null = null;
if (filters.channel && filters.channel.trim() !== "") {
try {
channelNorm = normalizeChannelPath(filters.channel, {
allowSubtreePrefix: true,
});
} catch (err) {
throw badRequest(err instanceof Error ? err.message : "Invalid channel");
}
}
let issueUuid: string | null = null;
let issueIdentifierUpper: string | null = null;
if (filters.issueId && filters.issueId.trim() !== "") {
const trimmed = filters.issueId.trim();
if (isUuidLike(trimmed)) {
issueUuid = trimmed.toLowerCase();
} else {
issueIdentifierUpper = (
normalizeIssueIdentifier(trimmed) ?? trimmed
).toUpperCase();
}
}
let eventTypes: Set<BoardEventType> | null = null;
if (filters.event && filters.event.length > 0) {
eventTypes = new Set();
for (const raw of filters.event) {
const parsed = boardEventTypeSchema.safeParse(raw);
if (!parsed.success) {
throw badRequest(`Invalid board event type "${raw}"`);
}
eventTypes.add(parsed.data);
}
}
const labelExprs: LabelFilterExpr[] = [];
if (filters.label && filters.label.length > 0) {
for (const raw of filters.label) {
try {
labelExprs.push(parseLabelFilterExpr(raw));
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : "Invalid label filter",
);
}
}
}
let mentionsName: string | null = null;
if (filters.mentions && filters.mentions.trim() !== "") {
mentionsName = filters.mentions.trim().replace(/^@/, "").toLowerCase();
}
let schemaFilter: { name: string; version: number | null } | null = null;
if (filters.schema && filters.schema.trim() !== "") {
const rawSchema = filters.schema.trim();
if (rawSchema.includes("@")) {
try {
const parsed = parseSchemaRef(rawSchema);
schemaFilter = { name: parsed.name, version: parsed.version };
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : "Invalid schema filter",
);
}
} else {
schemaFilter = { name: rawSchema, version: null };
}
}
return {
afterSeq,
hasExplicitAfter,
channelNorm,
issueUuid,
issueIdentifierUpper,
eventTypes,
labelExprs,
mentionsName,
schemaFilter,
};
}
export async function getCurrentCompanyMaxEventSeq(
dbOrTx: DbOrTx,
companyId: string,
): Promise<number> {
const cursor = await getLatestCompanyEventCursor(dbOrTx, companyId);
return parseEventCursor(cursor) ?? 0;
}
function serializeBoardEventRow(
row: typeof boardEvents.$inferSelect,
): BoardEventView {
const seq = Number(row.seq);
return {
cursor: formatEventCursor(seq),
seq,
type: row.eventType,
companyId: row.companyId,
channel: row.channelPath ?? null,
issueId: row.issueId ?? null,
identifier: row.identifier ?? null,
actor: {
type: row.actorType,
id: row.actorId ?? null,
name: row.actorName ?? null,
profile: row.actorProfile ?? null,
},
payload: (row.payload ?? {}) as Record<string, unknown>,
createdAt: row.createdAt.toISOString(),
};
}
function matchesNonDbEventFilters(
ev: BoardEventView,
parsed: ParsedBoardEventFilters,
): boolean {
if (ev.seq <= parsed.afterSeq) return false;
if (parsed.eventTypes && !parsed.eventTypes.has(ev.type)) {
return false;
}
if (parsed.channelNorm) {
if (!ev.channel) return false;
if (parsed.channelNorm.isSubtreePrefix) {
if (
ev.channel !== parsed.channelNorm.path &&
!ev.channel.startsWith(`${parsed.channelNorm.path}/`)
) {
return false;
}
} else if (ev.channel !== parsed.channelNorm.path) {
return false;
}
}
if (parsed.issueUuid) {
if (!ev.issueId || ev.issueId.toLowerCase() !== parsed.issueUuid) {
return false;
}
} else if (parsed.issueIdentifierUpper) {
if (
!ev.identifier ||
ev.identifier.toUpperCase() !== parsed.issueIdentifierUpper
) {
return false;
}
}
if (parsed.mentionsName) {
const mentionRegex = new RegExp(
`(^|\\s)@${escapeRegExp(parsed.mentionsName)}(\\b|$)`,
"i",
);
const candidateTexts = [
ev.payload.text,
ev.payload.body,
ev.payload.title,
ev.payload.message,
ev.payload.description,
].filter((v): v is string => typeof v === "string");
if (!candidateTexts.some((txt) => mentionRegex.test(txt))) {
return false;
}
}
if (parsed.schemaFilter) {
const blocks = Array.isArray(ev.payload.blocks)
? (ev.payload.blocks as Array<Partial<SchemaBlock>>)
: [];
const matched = blocks.some(
(b) =>
b &&
b.schema === parsed.schemaFilter!.name &&
(parsed.schemaFilter!.version === null ||
b.version === parsed.schemaFilter!.version),
);
if (!matched) {
return false;
}
}
return true;
}
function canBypassEventChannelPrivacy(
companyId: string,
actor: HeadlessActorContext,
): boolean {
return (
actor.companyId === companyId &&
(actor.isInstanceAdmin || actor.principalType === "local_trusted")
);
}
async function canActorAccessEventChannel(
db: Db,
companyId: string,
actor: HeadlessActorContext,
channelPath: string | null,
cache?: Map<string, boolean>,
): Promise<boolean> {
if (!channelPath) return true;
if (!isChannelAllowedByScopes(actor, channelPath)) return false;
if (canBypassEventChannelPrivacy(companyId, actor)) {
return true;
}
const cached = cache?.get(channelPath);
if (cached !== undefined) return cached;
const [ch] = await db
.select({
id: channels.id,
companyId: channels.companyId,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, channelPath)))
.limit(1);
const allowed = ch ? await canAccessChannel(db, ch, actor) : true;
cache?.set(channelPath, allowed);
return allowed;
}
function findHistoricalKvLabelsBeforeLaterChange(
events: BoardEventView[],
fromIndex: number,
issueId: string,
lookaheadEvents?: BoardEventView[],
): Record<string, string> | undefined {
for (let j = fromIndex + 1; j < events.length; j += 1) {
const later = events[j]!;
if (
later.type === "labels.changed" &&
later.issueId === issueId &&
isStringRecord(later.payload.previous)
) {
return later.payload.previous;
}
}
if (lookaheadEvents) {
for (let j = 0; j < lookaheadEvents.length; j += 1) {
const later = lookaheadEvents[j]!;
if (
later.type === "labels.changed" &&
later.issueId === issueId &&
isStringRecord(later.payload.previous)
) {
return later.payload.previous;
}
}
}
return undefined;
}
async function loadCurrentIssueLabelSnapshot(
db: Db,
issueId: string,
): Promise<IssueLabelSnapshot> {
const [issueRow] = await db
.select({ kvLabels: issues.kvLabels })
.from(issues)
.where(eq(issues.id, issueId))
.limit(1);
const tagRows = await db
.select({ name: labels.name })
.from(issueLabels)
.innerJoin(labels, eq(issueLabels.labelId, labels.id))
.where(eq(issueLabels.issueId, issueId));
return {
kvLabels: (issueRow?.kvLabels ?? {}) as Record<string, string>,
tagLabels: tagRows.map((t) => t.name),
};
}
async function eventMatchesLabelFilters(
db: Db,
ev: BoardEventView,
labelExprs: LabelFilterExpr[],
batchFallbackCache?: IssueLabelCache,
historicalKvLabelsOverride?: Record<string, string>,
): Promise<boolean> {
if (ev.type === "labels.changed" && ev.issueId) {
batchFallbackCache?.delete(ev.issueId);
}
if (labelExprs.length === 0) return true;
let kvLabels =
extractIssuePayloadKvLabels(ev) ?? historicalKvLabelsOverride ?? null;
let tagLabels = extractPayloadTagLabels(ev.payload);
const unresolvedExistsExpr = labelExprs.some(
(expr) =>
expr.kind === "exists" &&
(kvLabels === null ||
!Object.prototype.hasOwnProperty.call(kvLabels, expr.key)),
);
const needsTagLookup = tagLabels === undefined && unresolvedExistsExpr;
if ((kvLabels === null || needsTagLookup) && ev.issueId) {
let fallback = batchFallbackCache?.get(ev.issueId);
if (!fallback) {
fallback = await loadCurrentIssueLabelSnapshot(db, ev.issueId);
if (historicalKvLabelsOverride === undefined) {
batchFallbackCache?.set(ev.issueId, fallback);
}
}
if (kvLabels === null) {
kvLabels = fallback.kvLabels;
}
if (tagLabels === undefined) {
tagLabels = fallback.tagLabels;
}
}
const effectiveKv = kvLabels ?? {};
return labelExprs.every((expr) =>
matchesLabelFilter(effectiveKv, tagLabels, expr),
);
}
export async function eventMatchesFiltersAndAccess(
db: Db,
companyId: string,
actor: HeadlessActorContext,
ev: BoardEventView,
parsed: ParsedBoardEventFilters,
channelCache?: Map<string, boolean>,
batchFallbackCache?: IssueLabelCache,
readableIssueIds?: Set<string>,
authActor?: AuthorizationActor,
historicalKvLabelsOverride?: Record<string, string>,
): Promise<boolean> {
if (!matchesNonDbEventFilters(ev, parsed)) {
if (ev.type === "labels.changed" && ev.issueId) {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
if (!(await canActorAccessEventChannel(db, companyId, actor, ev.channel, channelCache))) {
if (ev.type === "labels.changed" && ev.issueId) {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
if (ev.issueId) {
if (readableIssueIds) {
if (!readableIssueIds.has(ev.issueId)) {
if (ev.type === "labels.changed") {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
} else {
const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor);
const readCondition = await issueReadSqlCondition(db, effectiveAuthActor);
const [readable] = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
eq(issues.id, ev.issueId),
readCondition,
),
)
.limit(1);
if (!readable) {
if (ev.type === "labels.changed") {
batchFallbackCache?.delete(ev.issueId);
}
return false;
}
}
}
return eventMatchesLabelFilters(
db,
ev,
parsed.labelExprs,
batchFallbackCache,
historicalKvLabelsOverride,
);
}
async function prepareBatchAccessMaps(
db: Db,
companyId: string,
actor: HeadlessActorContext,
events: BoardEventView[],
parsed: ParsedBoardEventFilters,
effectiveAuthActor: AuthorizationActor,
channelCache?: Map<string, boolean>,
): Promise<{
batchChannelAccess: Map<string, boolean>;
readableIssueIds: Set<string>;
}> {
const batchChannelAccess = channelCache ?? new Map<string, boolean>();
const scopeEligible = events.filter(
(ev) =>
matchesNonDbEventFilters(ev, parsed) &&
(!ev.channel || isChannelAllowedByScopes(actor, ev.channel)),
);
if (scopeEligible.length === 0) {
return { batchChannelAccess, readableIssueIds: new Set() };
}
if (canBypassEventChannelPrivacy(companyId, actor)) {
for (const ev of scopeEligible) {
if (ev.channel) batchChannelAccess.set(ev.channel, true);
}
} else {
const uncheckedPaths = Array.from(
new Set(
scopeEligible
.map((ev) => ev.channel)
.filter(
(ch): ch is string => Boolean(ch) && !batchChannelAccess.has(ch!),
),
),
);
if (uncheckedPaths.length > 0) {
const chRows = await db
.select({
id: channels.id,
companyId: channels.companyId,
path: channels.path,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(
and(
eq(channels.companyId, companyId),
inArray(channels.path, uncheckedPaths),
),
);
const inaccessibleIds = new Set(
await findInaccessibleChannelIds(db, companyId, actor, chRows),
);
for (const ch of chRows) {
batchChannelAccess.set(ch.path, !inaccessibleIds.has(ch.id));
}
for (const path of uncheckedPaths) {
if (!batchChannelAccess.has(path)) {
batchChannelAccess.set(path, true);
}
}
}
}
const distinctIssueIds = Array.from(
new Set(
scopeEligible
.filter((ev) => (ev.channel ? batchChannelAccess.get(ev.channel) !== false : true))
.map((ev) => ev.issueId)
.filter((id): id is string => Boolean(id)),
),
);
const readableIssueIds = new Set<string>();
if (distinctIssueIds.length > 0) {
const readCondition = await issueReadSqlCondition(db, effectiveAuthActor);
const readableRows = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.id, distinctIssueIds),
readCondition,
),
);
for (const r of readableRows) {
readableIssueIds.add(r.id);
}
}
return { batchChannelAccess, readableIssueIds };
}
export async function filterBoardEventsBatchForSubscriber(
db: Db,
companyId: string,
actor: HeadlessActorContext,
events: BoardEventView[],
parsed: ParsedBoardEventFilters,
authActor?: AuthorizationActor,
channelCache?: Map<string, boolean>,
lookaheadEvents?: BoardEventView[],
): Promise<BoardEventView[]> {
if (events.length === 0) return [];
const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor);
const { batchChannelAccess, readableIssueIds } = await prepareBatchAccessMaps(
db,
companyId,
actor,
events,
parsed,
effectiveAuthActor,
channelCache,
);
const batchFallbackCache: IssueLabelCache = new Map();
const matched: BoardEventView[] = [];
for (let i = 0; i < events.length; i += 1) {
const ev = events[i]!;
const historicalKv =
parsed.labelExprs.length > 0 &&
ev.issueId &&
extractIssuePayloadKvLabels(ev) === null
? findHistoricalKvLabelsBeforeLaterChange(
events,
i,
ev.issueId,
lookaheadEvents,
)
: undefined;
const ok = await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
batchChannelAccess,
batchFallbackCache,
readableIssueIds,
effectiveAuthActor,
historicalKv,
);
if (ok) {
matched.push(ev);
}
}
return matched;
}
export async function queryBoardEventsAfter(
db: Db,
companyId: string,
actor: HeadlessActorContext,
filtersOrParsed: BoardEventFilterInput | ParsedBoardEventFilters,
opts: { limit?: number; authActor?: AuthorizationActor } = {},
): Promise<BoardEventView[]> {
enforceHeadlessScopes(actor, { action: "events.read" });
const parsed =
"afterSeq" in filtersOrParsed
? filtersOrParsed
: parseBoardEventFilters(filtersOrParsed);
const limit = Math.min(Math.max(1, opts.limit ?? 100), 500);
const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor);
const channelCache = new Map<string, boolean>();
const results: BoardEventView[] = [];
let cursorSeq = parsed.afterSeq;
const batchSize = 200;
while (results.length < limit) {
const conditions = [
eq(boardEvents.companyId, companyId),
gt(boardEvents.seq, cursorSeq),
];
if (parsed.eventTypes && parsed.eventTypes.size > 0) {
const sqlEventTypes: BoardEventType[] =
parsed.labelExprs.length > 0 && !parsed.eventTypes.has("labels.changed")
? [...parsed.eventTypes, "labels.changed"]
: Array.from(parsed.eventTypes);
conditions.push(inArray(boardEvents.eventType, sqlEventTypes));
}
if (parsed.issueUuid) {
conditions.push(eq(boardEvents.issueId, parsed.issueUuid));
}
const rows = await db
.select()
.from(boardEvents)
.where(and(...conditions))
.orderBy(asc(boardEvents.seq))
.limit(batchSize);
if (rows.length === 0) break;
const batchEvents = rows.map(serializeBoardEventRow);
cursorSeq = Math.max(cursorSeq, batchEvents[batchEvents.length - 1]!.seq);
const matchedBatch = await filterBoardEventsBatchForSubscriber(
db,
companyId,
actor,
batchEvents,
parsed,
effectiveAuthActor,
channelCache,
);
for (const ev of matchedBatch) {
results.push(ev);
if (results.length >= limit) break;
}
if (rows.length < batchSize) break;
}
return results;
}
export async function waitForBoardEvent(
db: Db,
companyId: string,
actor: HeadlessActorContext,
filters: BoardEventFilterInput,
opts: {
timeoutMs?: number;
signal?: AbortSignal;
authActor?: AuthorizationActor;
onResolvedCursor?: (cursor: string) => void;
} = {},
): Promise<BoardEventView | null> {
enforceHeadlessScopes(actor, { action: "events.read" });
const parsed = parseBoardEventFilters(filters);
const timeoutMs = Math.min(Math.max(0, opts.timeoutMs ?? 30_000), 120_000);
const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor);
const channelCache = new Map<string, boolean>();
const buffered: BoardEventView[] = [];
let checkingInitial = true;
let resolveWaiter: ((ev: BoardEventView | null) => void) | null = null;
const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => {
if (checkingInitial) {
buffered.push(ev);
return;
}
if (ev.seq <= parsed.afterSeq) return;
void eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
undefined,
undefined,
effectiveAuthActor,
)
.then((ok) => {
if (ok && resolveWaiter) {
const resolveFn = resolveWaiter;
resolveWaiter = null;
resolveFn(ev);
}
})
.catch(() => {});
});
try {
if (parsed.hasExplicitAfter) {
opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq));
const existing = await queryBoardEventsAfter(db, companyId, actor, parsed, {
limit: 1,
authActor: effectiveAuthActor,
});
if (existing.length > 0) {
return existing[0]!;
}
} else {
parsed.afterSeq = await getCurrentCompanyMaxEventSeq(db, companyId);
opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq));
}
while (buffered.length > 0) {
const ev = buffered.shift()!;
if (
await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
undefined,
undefined,
effectiveAuthActor,
)
) {
return ev;
}
}
if (timeoutMs <= 0 || opts.signal?.aborted) {
return null;
}
return await new Promise<BoardEventView | null>((resolve) => {
let settled = false;
const finish = (result: BoardEventView | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
opts.signal?.removeEventListener("abort", onAbort);
resolveWaiter = null;
resolve(result);
};
const onAbort = () => finish(null);
resolveWaiter = finish;
checkingInitial = false;
const timer = setTimeout(() => finish(null), timeoutMs);
opts.signal?.addEventListener("abort", onAbort, { once: true });
});
} finally {
unsubscribe();
}
}
+178 -126
View File
@@ -26,6 +26,7 @@ import {
issueLabels,
issues,
labels,
primeDatabaseWorkTransactionId,
projects,
} from "@paperclipai/db";
import {
@@ -58,6 +59,7 @@ import {
} from "@paperclipai/shared";
import { badRequest, conflict, forbidden, notFound } from "../errors.js";
import {
createActivityDetailsRedactor,
logActivity,
publishActivity,
type ActivityPublication,
@@ -67,6 +69,7 @@ import {
appendBoardEvent,
assertChannelAccess,
assertProjectReadAccess,
buildNextIssueCounterSql,
buildSqlIssueLabelFilterCondition,
canAccessChannel,
channelDescendantsCondition,
@@ -79,6 +82,7 @@ import {
resolveIssueByIdOrIdentifier,
resolveProjectReference,
serializeCommentView,
serializeCreatedHeadlessIssueView,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
@@ -223,16 +227,15 @@ export async function resolveAssigneeAgent(
return null;
}
export async function attachTagLabels(
export async function ensureCompanyTagLabels(
tx: DbOrTx,
companyId: string,
issueId: string,
tagNames: string[],
): Promise<void> {
): Promise<Array<{ id: string; name: string }>> {
const uniqueNames = Array.from(
new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)),
);
if (uniqueNames.length === 0) return;
).sort();
if (uniqueNames.length === 0) return [];
await tx
.insert(labels)
@@ -247,12 +250,20 @@ export async function attachTagLabels(
target: [labels.companyId, labels.name],
});
const labelRows = await tx
.select({ id: labels.id })
return tx
.select({ id: labels.id, name: labels.name })
.from(labels)
.where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames)));
}
if (labelRows.length === 0) return;
export async function attachTagLabels(
tx: DbOrTx,
companyId: string,
issueId: string,
tagNames: string[],
): Promise<string[]> {
const labelRows = await ensureCompanyTagLabels(tx, companyId, tagNames);
if (labelRows.length === 0) return [];
await tx
.insert(issueLabels)
@@ -266,6 +277,8 @@ export async function attachTagLabels(
.onConflictDoNothing({
target: [issueLabels.issueId, issueLabels.labelId],
});
return labelRows.map((l) => l.name);
}
async function addChannelCreatorMembership(
@@ -380,7 +393,7 @@ export async function ensureChannel(
input: EnsureChannelInput | CreateChannelInput,
opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {},
): Promise<typeof channels.$inferSelect> {
const { normalizedPath, hasPrivateAncestor } =
const { normalizedPath, existingChannel, hasPrivateAncestor } =
await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path);
const normalized = { path: normalizedPath };
@@ -427,14 +440,12 @@ export async function ensureChannel(
visibility = "private";
}
const [preExisting] = await dbOrTx
.select({ id: channels.id })
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (existingChannel && !opts.allowUpdateExisting) {
return existingChannel;
}
let inserted: typeof channels.$inferSelect | undefined;
if (!preExisting) {
let existing = existingChannel;
if (!existing) {
if (validatedQueueConfig?.managedPool) {
await assertCanConfigureManagedPool(
dbOrTx,
@@ -450,7 +461,7 @@ export async function ensureChannel(
}
const now = new Date();
const [createdRow] = await dbOrTx
const [inserted] = await dbOrTx
.insert(channels)
.values({
companyId,
@@ -470,55 +481,55 @@ export async function ensureChannel(
target: [channels.companyId, channels.path],
})
.returning();
inserted = createdRow;
}
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,
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,
);
opts.publications,
);
}
return inserted;
}
return inserted;
}
const [existing] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
const [raced] = await dbOrTx
.select()
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path)))
.limit(1);
if (!existing) {
throw notFound(`Channel '${normalized.path}' not found`);
}
if (!raced || raced.archivedAt !== null) {
throw notFound(`Channel '${normalized.path}' not found`);
}
if (existing.visibility === "private") {
await assertChannelAccess(dbOrTx, existing, actor);
}
if (raced.visibility === "private") {
await assertChannelAccess(dbOrTx, raced, actor);
}
if (!opts.allowUpdateExisting) {
return existing;
if (!opts.allowUpdateExisting) {
return raced;
}
existing = raced;
}
const updates: Partial<typeof channels.$inferInsert> = {};
@@ -912,7 +923,10 @@ export async function createChannelPost(
data: input.schema.data,
});
}
const validatedBlocks = await validateSchemaBlocks(db, companyId, combinedBlocks);
const validatedBlocks =
combinedBlocks.length > 0
? await validateSchemaBlocks(db, companyId, combinedBlocks)
: [];
const resolvedResultSchemaRef = input.resultSchema
? await assertSchemaExists(db, companyId, input.resultSchema)
@@ -1011,6 +1025,7 @@ export async function createChannelPost(
}
}
const activityRedactor = await createActivityDetailsRedactor(db);
const publications: ActivityPublication[] = [];
const committedEvents: BoardEventView[] = [];
@@ -1020,7 +1035,11 @@ export async function createChannelPost(
sql`select pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${"post:" + originId}))`,
);
const [existingInTx] = await tx
.select()
.select({
id: issues.id,
channelId: issues.channelId,
originFingerprint: issues.originFingerprint,
})
.from(issues)
.where(
and(
@@ -1056,9 +1075,15 @@ export async function createChannelPost(
}
}
const channel = await ensureChannel(tx, companyId, actor, {
path: normalizedChannel.path,
});
const channel = await ensureChannel(
tx,
companyId,
actor,
{
path: normalizedChannel.path,
},
{ publications },
);
const now = new Date();
let projectId: string | null = channel.defaultProjectId ?? null;
@@ -1076,28 +1101,6 @@ export async function createChannelPost(
for: input.for,
});
const [maxRow] = await tx
.select({
maxNum: sql<number>`coalesce(max(${issues.issueNumber}), 0)`,
})
.from(issues)
.where(eq(issues.companyId, companyId));
const currentMax = Number(maxRow?.maxNum ?? 0);
const [companyRow] = await tx
.update(companies)
.set({
issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`,
updatedAt: now,
})
.where(eq(companies.id, companyId))
.returning({
issueCounter: companies.issueCounter,
issuePrefix: companies.issuePrefix,
});
const issueNumber = companyRow!.issueCounter;
const identifier = `${companyRow!.issuePrefix}-${issueNumber}`;
const scope: IssueScope = input.board ? "board" : "channel";
const priority: IssuePriority = input.priority ?? "medium";
let issueVisibility: "open" | "private" =
@@ -1112,49 +1115,69 @@ export async function createChannelPost(
issueVisibility = "private";
}
}
const nextCounterExpr = buildNextIssueCounterSql(companyId, 1);
const [companyRow] = await tx
.update(companies)
.set({
issueCounter: nextCounterExpr,
updatedAt: now,
})
.where(eq(companies.id, companyId))
.returning({
issueCounter: companies.issueCounter,
issuePrefix: companies.issuePrefix,
xid: sql<string>`pg_current_xact_id()::text`,
});
if (companyRow?.xid) {
primeDatabaseWorkTransactionId(tx, companyRow.xid);
}
const issueNumber = companyRow!.issueCounter;
const identifier = `${companyRow!.issuePrefix}-${issueNumber}`;
const newIssueId = randomUUID();
const privacyRootIssueId = issueVisibility === "private" ? newIssueId : null;
const [inserted] = await tx
.insert(issues)
.values({
id: newIssueId,
companyId,
projectId,
channelId: channel.id,
visibility: issueVisibility,
privacyRootIssueId,
title: resolvedTitle,
description: resolvedDescription,
status: requestedStatus,
scope,
priority,
assigneeAgentId,
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
responsibleUserId: actor.responsibleUserId,
kvLabels: mergedKvLabels,
schemaBlocks: validatedBlocks,
resultSchemaRef: resolvedResultSchemaRef,
issueNumber,
identifier,
originKind: "manual",
originId,
originFingerprint: requestHash ?? "default",
createdAt: now,
updatedAt: now,
})
.returning();
await tx.insert(issues).values({
id: newIssueId,
companyId,
projectId,
channelId: channel.id,
visibility: issueVisibility,
privacyRootIssueId,
title: resolvedTitle,
description: resolvedDescription,
status: requestedStatus,
scope,
priority,
assigneeAgentId,
createdByAgentId: actor.agentId,
createdByUserId: actor.agentId ? null : actor.userId,
createdByProfile: actor.actorProfile,
responsibleUserId: actor.responsibleUserId,
kvLabels: mergedKvLabels,
schemaBlocks: validatedBlocks,
resultSchemaRef: resolvedResultSchemaRef,
issueNumber,
identifier,
originKind: "manual",
originId,
originFingerprint: requestHash ?? "default",
createdAt: now,
updatedAt: now,
});
await tx
.update(channels)
.set({ lastActivityAt: now, updatedAt: now })
.where(eq(channels.id, channel.id));
if (input.tagLabels && input.tagLabels.length > 0) {
await attachTagLabels(tx, companyId, inserted!.id, input.tagLabels);
}
const attachedTagNames =
input.tagLabels && input.tagLabels.length > 0
? await attachTagLabels(tx, companyId, newIssueId, input.tagLabels)
: [];
await logActivity(
tx as unknown as Db,
@@ -1166,12 +1189,12 @@ export async function createChannelPost(
? actor.agentId!
: (actor.userId ?? "local-board"),
agentId: actor.agentId,
issueId: inserted!.id,
issueId: newIssueId,
responsibleUserIdOverride: actor.responsibleUserId,
action:
requestedStatus === "todo" ? "issue.created" : "channel.post_created",
entityType: "issue",
entityId: inserted!.id,
entityId: newIssueId,
details: {
identifier,
channel: channel.path,
@@ -1180,6 +1203,7 @@ export async function createChannelPost(
},
},
publications,
{ redactor: activityRedactor },
);
const isReadyTask = requestedStatus === "todo" && assigneeAgentId === null;
@@ -1188,7 +1212,7 @@ export async function createChannelPost(
type: requestedStatus === "todo" ? "task.created" : "thread.posted",
channelId: channel.id,
channelPath: channel.path,
issueId: inserted!.id,
issueId: newIssueId,
identifier,
actor,
payload: {
@@ -1196,6 +1220,8 @@ export async function createChannelPost(
...(resolvedDescription ? { description: resolvedDescription.slice(0, 4000) } : {}),
blocks: validatedBlocks,
labels: mergedKvLabels,
kvLabels: mergedKvLabels,
tagLabels: attachedTagNames,
...(isReadyTask ? { ready: true } : {}),
},
});
@@ -1208,16 +1234,42 @@ export async function createChannelPost(
type: "task.ready",
channelId: channel.id,
channelPath: channel.path,
issueId: inserted!.id,
issueId: newIssueId,
identifier,
actor,
payload: {},
payload: {
kvLabels: mergedKvLabels,
tagLabels: attachedTagNames,
},
});
committedEvents.push(readyEvent);
lastCursor = readyEvent.cursor;
}
const view = await loadHeadlessIssueView(tx, inserted!.id, lastCursor);
const view = serializeCreatedHeadlessIssueView({
id: newIssueId,
companyId,
identifier,
title: resolvedTitle,
description: resolvedDescription,
status: requestedStatus,
scope,
priority,
channelId: channel.id,
channel: channel.path,
projectId,
assigneeAgentId,
assigneeUserId: null,
actorProfile: actor.actorProfile,
kvLabels: mergedKvLabels,
tagLabels: attachedTagNames,
blocks: validatedBlocks,
resultSchemaRef: resolvedResultSchemaRef,
blockedByIssueIds: [],
cursor: lastCursor,
createdAt: now,
updatedAt: now,
});
return { issue: view, created: true };
});
+287 -78
View File
@@ -439,7 +439,6 @@ export async function resolveHeadlessActor(
);
}
// Check whether an active registered agent with this name or derived urlKey already exists.
const profileLower = effectiveProfile.toLowerCase();
const companyAgents = await db
.select({
@@ -907,35 +906,48 @@ export async function resolveProjectReference(
return resolvedId;
}
export async function resolveIssueByIdOrIdentifier(
dbOrTx: DbOrTx,
export function buildNextIssueCounterSql(
companyId: string,
count: number,
): SQL {
return sql`greatest(${companies.issueCounter}, coalesce((select max(${issues.issueNumber}) from ${issues} where ${issues.companyId} = ${companyId}), 0)) + ${count}`;
}
async function queryIssueByIdOrIdentifier<T>(
idOrIdentifier: string,
expectedCompanyId?: string,
) {
expectedCompanyId: string | undefined,
runQuery: (whereClause: SQL | undefined) => Promise<T[]>,
): Promise<T> {
const trimmed = idOrIdentifier.trim();
let row;
let row: T | undefined;
if (isUuidLike(trimmed)) {
[row] = await dbOrTx
.select()
.from(issues)
.where(
expectedCompanyId
? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId))
: eq(issues.id, trimmed),
);
[row] = await runQuery(
expectedCompanyId
? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId))
: eq(issues.id, trimmed),
);
} else {
const normalized = normalizeIssueIdentifier(trimmed) ?? trimmed.toUpperCase();
[row] = await dbOrTx
.select()
.from(issues)
.where(
const normalizedUpper = (
normalizeIssueIdentifier(trimmed) ?? trimmed
).toUpperCase();
[row] = await runQuery(
expectedCompanyId
? and(
eq(issues.identifier, normalizedUpper),
eq(issues.companyId, expectedCompanyId),
)
: eq(issues.identifier, normalizedUpper),
);
if (!row) {
[row] = await runQuery(
expectedCompanyId
? and(
sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`,
sql`upper(${issues.identifier}) = ${normalizedUpper}`,
eq(issues.companyId, expectedCompanyId),
)
: sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`,
: sql`upper(${issues.identifier}) = ${normalizedUpper}`,
);
}
}
if (!row) {
throw notFound(`Issue '${idOrIdentifier}' not found`);
@@ -943,6 +955,53 @@ export async function resolveIssueByIdOrIdentifier(
return row;
}
export async function resolveIssueByIdOrIdentifier(
dbOrTx: DbOrTx,
idOrIdentifier: string,
expectedCompanyId?: string,
) {
return queryIssueByIdOrIdentifier(
idOrIdentifier,
expectedCompanyId,
(whereClause) => dbOrTx.select().from(issues).where(whereClause).limit(1),
);
}
const issueCommentTargetSelection = {
id: issues.id,
identifier: issues.identifier,
companyId: issues.companyId,
channelId: issues.channelId,
projectId: issues.projectId,
parentId: issues.parentId,
assigneeAgentId: issues.assigneeAgentId,
assigneeUserId: issues.assigneeUserId,
status: issues.status,
scope: issues.scope,
conversationAgentId: issues.conversationAgentId,
};
export async function resolveIssueCommentTarget(
dbOrTx: DbOrTx,
idOrIdentifier: string,
expectedCompanyId?: string,
) {
return queryIssueByIdOrIdentifier(
idOrIdentifier,
expectedCompanyId,
(whereClause) =>
dbOrTx
.select(issueCommentTargetSelection)
.from(issues)
.where(whereClause)
.limit(1),
);
}
function isPlainObjectRecord(val: unknown): val is Record<string, unknown> {
return Boolean(val) && typeof val === "object" && !Array.isArray(val);
}
export async function appendBoardEvent(
dbOrTx: DbOrTx,
input: {
@@ -982,36 +1041,89 @@ export async function appendBoardEvent(
? 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;
await dbOrTx.execute(
sql`SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId}))`,
);
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);
const [inserted] = await dbOrTx
.insert(boardEvents)
.values({
companyId: input.companyId,
eventType: input.type,
channelId: input.channelId ?? null,
channelPath: input.channelPath ?? null,
issueId: input.issueId ?? null,
identifier: input.identifier ?? null,
actorType,
actorId,
actorName,
actorProfile,
payload: input.payload ?? {},
})
.returning();
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: input.issueId ?? null,
issueId: issueIdVal,
identifier: input.identifier ?? null,
actor: {
type: actorType,
@@ -1019,8 +1131,8 @@ export async function appendBoardEvent(
name: actorName,
profile: actorProfile,
},
payload: (inserted!.payload ?? {}) as Record<string, unknown>,
createdAt: inserted!.createdAt.toISOString(),
payload: persistedPayload,
createdAt: createdAtIso,
};
}
@@ -1108,52 +1220,149 @@ export async function loadHeadlessIssueViews(
return issueRows.map((row) => {
const channelPath = row.channelId ? channelMap.get(row.channelId) ?? null : null;
const isPassivePost =
row.scope === "channel" &&
row.status === "backlog" &&
!row.assigneeAgentId &&
!row.assigneeUserId;
const issueSeq = seqMap.get(row.id);
const cursor =
explicitCursor ??
(issueSeq !== undefined ? formatEventCursor(issueSeq) : fallbackCursor);
return {
id: row.id,
companyId: row.companyId,
identifier: row.identifier ?? row.id,
title: row.title,
description: row.description ?? null,
status: row.status as IssueStatus,
scope: row.scope as IssueScope,
priority: row.priority as IssuePriority,
channelId: row.channelId ?? null,
channel: channelPath,
projectId: row.projectId ?? null,
assigneeAgentId: row.assigneeAgentId ?? null,
assigneeUserId: row.assigneeUserId ?? null,
actorProfile: row.createdByProfile ?? null,
kvLabels: (row.kvLabels ?? {}) as Record<string, string>,
return mapHeadlessIssueRowToView(row, {
channelPath,
tagLabels: tagMap.get(row.id) ?? [],
blocks: (row.schemaBlocks ?? []) as SchemaBlock[],
resultSchemaRef: row.resultSchemaRef ?? null,
blockedByIssueIds: blockerMap.get(row.id) ?? [],
isPassivePost,
claimEpoch: Number(row.claimEpoch ?? 0),
claimHolderProfile: row.claimHolderProfile ?? null,
claimHolderAgentId: row.claimHolderAgentId ?? null,
claimHolderUserId: row.claimHolderUserId ?? null,
claimLeaseExpiresAt: row.claimLeaseExpiresAt
? row.claimLeaseExpiresAt.toISOString()
: null,
claimAttemptCount: row.claimAttemptCount ?? 0,
cursor,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
});
});
}
function mapHeadlessIssueRowToView(
row: {
id: string;
companyId: string;
identifier: string | null;
title: string;
description: string | null;
status: string;
scope: string;
priority: string;
channelId: string | null;
projectId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
createdByProfile: string | null;
kvLabels: Record<string, string> | null;
schemaBlocks: SchemaBlock[] | null;
resultSchemaRef: string | null;
claimEpoch?: number | null;
claimHolderProfile?: string | null;
claimHolderAgentId?: string | null;
claimHolderUserId?: string | null;
claimLeaseExpiresAt?: Date | null;
claimAttemptCount?: number | null;
createdAt: Date;
updatedAt: Date;
},
extra: {
channelPath: string | null;
tagLabels: string[];
blockedByIssueIds: string[];
cursor: string;
},
): HeadlessIssueView {
const isPassivePost =
row.scope === "channel" &&
row.status === "backlog" &&
!row.assigneeAgentId &&
!row.assigneeUserId;
return {
id: row.id,
companyId: row.companyId,
identifier: row.identifier ?? row.id,
title: row.title,
description: row.description ?? null,
status: row.status as IssueStatus,
scope: row.scope as IssueScope,
priority: row.priority as IssuePriority,
channelId: row.channelId ?? null,
channel: extra.channelPath,
projectId: row.projectId ?? null,
assigneeAgentId: row.assigneeAgentId ?? null,
assigneeUserId: row.assigneeUserId ?? null,
actorProfile: row.createdByProfile ?? null,
kvLabels: (row.kvLabels ?? {}) as Record<string, string>,
tagLabels: extra.tagLabels,
blocks: (row.schemaBlocks ?? []) as SchemaBlock[],
resultSchemaRef: row.resultSchemaRef ?? null,
blockedByIssueIds: extra.blockedByIssueIds,
isPassivePost,
claimEpoch: Number(row.claimEpoch ?? 0),
claimHolderProfile: row.claimHolderProfile ?? null,
claimHolderAgentId: row.claimHolderAgentId ?? null,
claimHolderUserId: row.claimHolderUserId ?? null,
claimLeaseExpiresAt: row.claimLeaseExpiresAt
? row.claimLeaseExpiresAt.toISOString()
: null,
claimAttemptCount: row.claimAttemptCount ?? 0,
cursor: extra.cursor,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
};
}
export function serializeCreatedHeadlessIssueView(input: {
id: string;
companyId: string;
identifier: string;
title: string;
description: string | null;
status: IssueStatus;
scope: IssueScope;
priority: IssuePriority;
channelId: string | null;
channel: string | null;
projectId: string | null;
assigneeAgentId: string | null;
assigneeUserId: string | null;
actorProfile: string | null;
kvLabels: Record<string, string>;
tagLabels: string[];
blocks: SchemaBlock[];
resultSchemaRef: string | null;
blockedByIssueIds: string[];
cursor: string;
createdAt: Date;
updatedAt: Date;
}): HeadlessIssueView {
return mapHeadlessIssueRowToView(
{
id: input.id,
companyId: input.companyId,
identifier: input.identifier,
title: input.title,
description: input.description,
status: input.status,
scope: input.scope,
priority: input.priority,
channelId: input.channelId,
projectId: input.projectId,
assigneeAgentId: input.assigneeAgentId,
assigneeUserId: input.assigneeUserId,
createdByProfile: input.actorProfile,
kvLabels: input.kvLabels,
schemaBlocks: input.blocks,
resultSchemaRef: input.resultSchemaRef,
createdAt: input.createdAt,
updatedAt: input.updatedAt,
},
{
channelPath: input.channel,
tagLabels: input.tagLabels,
blockedByIssueIds: input.blockedByIssueIds,
cursor: input.cursor,
},
);
}
export async function loadHeadlessIssueView(
dbOrTx: DbOrTx,
issueId: string,
@@ -1,46 +1,34 @@
import { randomUUID } from "node:crypto";
import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm";
import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm";
import { z } from "zod";
import type { Db } from "@paperclipai/db";
import {
activityLog,
agents,
boardEvents,
channels,
companies,
issueComments,
issueLabels,
issues,
issueThreadInteractions,
labels,
projects,
scheduledBoardPosts,
} from "@paperclipai/db";
import {
boardEventTypeSchema,
deriveAgentUrlKey,
formatEventCursor,
isUuidLike,
matchesLabelFilter,
normalizeChannelPath,
normalizeIssueIdentifier,
OneLineAskSchema,
OneLineConfirmSchema,
parseDurationMs,
parseEventCursor,
parseLabelFilterExpr,
parseSchemaRef,
ResolveInteractionInputSchema,
SchedulePostSchema,
splitMessageIntoTitleAndDescription,
type AskUserQuestionsPayload,
type AskUserQuestionsResult,
type BoardEventType,
type BoardEventView,
type InteractionView,
type IssueThreadInteractionPayload,
type IssueThreadInteractionResult,
type LabelFilterExpr,
type RequestConfirmationPayload,
type RequestConfirmationResult,
type SchemaBlock,
@@ -66,11 +54,22 @@ import {
getLatestCompanyEventCursor,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
subscribeCompanyBoardEvents,
type DbOrTx,
type HeadlessActorContext,
} from "./headless-common.js";
import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js";
export {
eventMatchesFiltersAndAccess,
filterBoardEventsBatchForSubscriber,
getCurrentCompanyMaxEventSeq,
parseBoardEventFilters,
queryBoardEventsAfter,
waitForBoardEvent,
type BoardEventFilterInput,
type IssueLabelCache,
type IssueLabelSnapshot,
type ParsedBoardEventFilters,
} from "./headless-board-event-stream.js";
const ISSUE_REF_RE = /^[A-Z][A-Z0-9]*-\d+$/i;
@@ -81,32 +80,6 @@ function isIssueReferenceTarget(target: string): boolean {
export { ResolveInteractionInputSchema };
export interface BoardEventFilterInput {
channel?: string;
issueId?: string;
event?: BoardEventType[];
label?: string[];
mentions?: string;
schema?: string;
after?: string;
}
export interface ParsedBoardEventFilters {
afterSeq: number;
hasExplicitAfter: boolean;
channelNorm: { path: string; isSubtreePrefix: boolean } | null;
issueUuid: string | null;
issueIdentifierUpper: string | null;
eventTypes: Set<BoardEventType> | null;
labelExprs: LabelFilterExpr[];
mentionsName: string | null;
schemaFilter: { name: string; version: number | null } | null;
}
function escapeRegExp(input: string): string {
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function isChannelAllowedByScopes(
actor: HeadlessActorContext,
channelPath: string,
@@ -1119,565 +1092,6 @@ export async function rejectOnIssue(
return resolveInteractionOnIssue(db, issueId, actor, rawInput, "reject", opts);
}
export function parseBoardEventFilters(
filters: BoardEventFilterInput,
): ParsedBoardEventFilters {
let afterSeq = 0;
let hasExplicitAfter = false;
if (filters.after !== undefined && filters.after.trim() !== "") {
const parsed = parseEventCursor(filters.after);
if (parsed === null) {
throw badRequest(
`Invalid cursor "${filters.after}": expected evt_<non-negative-integer>`,
);
}
afterSeq = parsed;
hasExplicitAfter = true;
}
let channelNorm: { path: string; isSubtreePrefix: boolean } | null = null;
if (filters.channel && filters.channel.trim() !== "") {
try {
channelNorm = normalizeChannelPath(filters.channel, {
allowSubtreePrefix: true,
});
} catch (err) {
throw badRequest(err instanceof Error ? err.message : "Invalid channel");
}
}
let issueUuid: string | null = null;
let issueIdentifierUpper: string | null = null;
if (filters.issueId && filters.issueId.trim() !== "") {
const trimmed = filters.issueId.trim();
if (isUuidLike(trimmed)) {
issueUuid = trimmed.toLowerCase();
} else {
issueIdentifierUpper = (
normalizeIssueIdentifier(trimmed) ?? trimmed
).toUpperCase();
}
}
let eventTypes: Set<BoardEventType> | null = null;
if (filters.event && filters.event.length > 0) {
eventTypes = new Set();
for (const raw of filters.event) {
const parsed = boardEventTypeSchema.safeParse(raw);
if (!parsed.success) {
throw badRequest(`Invalid board event type "${raw}"`);
}
eventTypes.add(parsed.data);
}
}
const labelExprs: LabelFilterExpr[] = [];
if (filters.label && filters.label.length > 0) {
for (const raw of filters.label) {
try {
labelExprs.push(parseLabelFilterExpr(raw));
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : "Invalid label filter",
);
}
}
}
let mentionsName: string | null = null;
if (filters.mentions && filters.mentions.trim() !== "") {
mentionsName = filters.mentions.trim().replace(/^@/, "").toLowerCase();
}
let schemaFilter: { name: string; version: number | null } | null = null;
if (filters.schema && filters.schema.trim() !== "") {
const rawSchema = filters.schema.trim();
if (rawSchema.includes("@")) {
try {
const parsed = parseSchemaRef(rawSchema);
schemaFilter = { name: parsed.name, version: parsed.version };
} catch (err) {
throw badRequest(
err instanceof Error ? err.message : "Invalid schema filter",
);
}
} else {
schemaFilter = { name: rawSchema, version: null };
}
}
return {
afterSeq,
hasExplicitAfter,
channelNorm,
issueUuid,
issueIdentifierUpper,
eventTypes,
labelExprs,
mentionsName,
schemaFilter,
};
}
export async function getCurrentCompanyMaxEventSeq(
dbOrTx: DbOrTx,
companyId: string,
): Promise<number> {
const cursor = await getLatestCompanyEventCursor(dbOrTx, companyId);
return parseEventCursor(cursor) ?? 0;
}
function serializeBoardEventRow(
row: typeof boardEvents.$inferSelect,
): BoardEventView {
const seq = Number(row.seq);
return {
cursor: formatEventCursor(seq),
seq,
type: row.eventType,
companyId: row.companyId,
channel: row.channelPath ?? null,
issueId: row.issueId ?? null,
identifier: row.identifier ?? null,
actor: {
type: row.actorType,
id: row.actorId ?? null,
name: row.actorName ?? null,
profile: row.actorProfile ?? null,
},
payload: (row.payload ?? {}) as Record<string, unknown>,
createdAt: row.createdAt.toISOString(),
};
}
function matchesNonDbEventFilters(
ev: BoardEventView,
parsed: ParsedBoardEventFilters,
): boolean {
if (ev.seq <= parsed.afterSeq) return false;
if (parsed.eventTypes && !parsed.eventTypes.has(ev.type)) {
return false;
}
if (parsed.channelNorm) {
if (!ev.channel) return false;
if (parsed.channelNorm.isSubtreePrefix) {
if (
ev.channel !== parsed.channelNorm.path &&
!ev.channel.startsWith(`${parsed.channelNorm.path}/`)
) {
return false;
}
} else if (ev.channel !== parsed.channelNorm.path) {
return false;
}
}
if (parsed.issueUuid) {
if (!ev.issueId || ev.issueId.toLowerCase() !== parsed.issueUuid) {
return false;
}
} else if (parsed.issueIdentifierUpper) {
if (
!ev.identifier ||
ev.identifier.toUpperCase() !== parsed.issueIdentifierUpper
) {
return false;
}
}
if (parsed.mentionsName) {
const mentionRegex = new RegExp(
`(^|\\s)@${escapeRegExp(parsed.mentionsName)}(\\b|$)`,
"i",
);
const candidateTexts = [
ev.payload.text,
ev.payload.body,
ev.payload.title,
ev.payload.message,
ev.payload.description,
].filter((v): v is string => typeof v === "string");
if (!candidateTexts.some((txt) => mentionRegex.test(txt))) {
return false;
}
}
if (parsed.schemaFilter) {
const blocks = Array.isArray(ev.payload.blocks)
? (ev.payload.blocks as Array<Partial<SchemaBlock>>)
: [];
const matched = blocks.some(
(b) =>
b &&
b.schema === parsed.schemaFilter!.name &&
(parsed.schemaFilter!.version === null ||
b.version === parsed.schemaFilter!.version),
);
if (!matched) {
return false;
}
}
return true;
}
async function canActorAccessEventChannel(
db: Db,
companyId: string,
actor: HeadlessActorContext,
channelPath: string | null,
cache?: Map<string, boolean>,
): Promise<boolean> {
if (!channelPath) return true;
if (!isChannelAllowedByScopes(actor, channelPath)) return false;
const cached = cache?.get(channelPath);
if (cached !== undefined) return cached;
const [ch] = await db
.select({
id: channels.id,
companyId: channels.companyId,
visibility: channels.visibility,
createdByUserId: channels.createdByUserId,
createdByAgentId: channels.createdByAgentId,
})
.from(channels)
.where(and(eq(channels.companyId, companyId), eq(channels.path, channelPath)))
.limit(1);
const allowed = ch ? await canAccessChannel(db, ch, actor) : true;
cache?.set(channelPath, allowed);
return allowed;
}
async function eventMatchesLabelFilters(
db: Db,
ev: BoardEventView,
labelExprs: LabelFilterExpr[],
issueLabelCache: Map<
string,
{ kvLabels: Record<string, string>; tagLabels: string[] }
>,
): Promise<boolean> {
if (ev.type === "labels.changed" && ev.issueId) {
issueLabelCache.delete(ev.issueId);
}
if (labelExprs.length === 0) return true;
let kvLabels =
ev.payload.kvLabels &&
typeof ev.payload.kvLabels === "object" &&
!Array.isArray(ev.payload.kvLabels)
? (ev.payload.kvLabels as Record<string, string>)
: ev.payload.current &&
typeof ev.payload.current === "object" &&
!Array.isArray(ev.payload.current)
? (ev.payload.current as Record<string, string>)
: null;
let tagLabels = Array.isArray(ev.payload.tagLabels)
? (ev.payload.tagLabels.filter((x): x is string => typeof x === "string"))
: undefined;
if (
!ev.payload.kvLabels &&
!(
ev.payload.current &&
typeof ev.payload.current === "object" &&
!Array.isArray(ev.payload.current)
) &&
ev.issueId
) {
// Re-check issue labels if not carried on payload
let cached = issueLabelCache.get(ev.issueId);
if (!cached) {
const [issueRow] = await db
.select({ kvLabels: issues.kvLabels })
.from(issues)
.where(eq(issues.id, ev.issueId))
.limit(1);
const tagRows = await db
.select({ name: labels.name })
.from(issueLabels)
.innerJoin(labels, eq(issueLabels.labelId, labels.id))
.where(eq(issueLabels.issueId, ev.issueId));
cached = {
kvLabels: (issueRow?.kvLabels ?? {}) as Record<string, string>,
tagLabels: tagRows.map((t) => t.name),
};
issueLabelCache.set(ev.issueId, cached);
}
kvLabels = cached.kvLabels;
tagLabels = cached.tagLabels;
}
const effectiveKv = kvLabels ?? {};
return labelExprs.every((expr) =>
matchesLabelFilter(effectiveKv, tagLabels, expr),
);
}
export async function eventMatchesFiltersAndAccess(
db: Db,
companyId: string,
actor: HeadlessActorContext,
ev: BoardEventView,
parsed: ParsedBoardEventFilters,
channelCache?: Map<string, boolean>,
issueLabelCache = new Map<
string,
{ kvLabels: Record<string, string>; tagLabels: string[] }
>(),
readableIssueIds?: Set<string>,
authActor?: AuthorizationActor,
): Promise<boolean> {
if (ev.type === "labels.changed" && ev.issueId) {
issueLabelCache.delete(ev.issueId);
}
if (!matchesNonDbEventFilters(ev, parsed)) return false;
if (!(await canActorAccessEventChannel(db, companyId, actor, ev.channel, channelCache))) {
return false;
}
if (ev.issueId) {
if (readableIssueIds) {
if (!readableIssueIds.has(ev.issueId)) {
return false;
}
} else {
const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor);
const readCondition = await issueReadSqlCondition(db, effectiveAuthActor);
const [readable] = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
eq(issues.id, ev.issueId),
readCondition,
),
)
.limit(1);
if (!readable) {
return false;
}
}
}
if (!(await eventMatchesLabelFilters(db, ev, parsed.labelExprs, issueLabelCache))) {
return false;
}
return true;
}
export async function queryBoardEventsAfter(
db: Db,
companyId: string,
actor: HeadlessActorContext,
filtersOrParsed: BoardEventFilterInput | ParsedBoardEventFilters,
opts: { limit?: number; authActor?: AuthorizationActor } = {},
): Promise<BoardEventView[]> {
enforceHeadlessScopes(actor, { action: "events.read" });
const parsed =
"afterSeq" in filtersOrParsed
? filtersOrParsed
: parseBoardEventFilters(filtersOrParsed);
const limit = Math.min(Math.max(1, opts.limit ?? 100), 500);
const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor);
const channelCache = new Map<string, boolean>();
const issueLabelCache = new Map<
string,
{ kvLabels: Record<string, string>; tagLabels: string[] }
>();
const results: BoardEventView[] = [];
let cursorSeq = parsed.afterSeq;
const batchSize = 200;
while (results.length < limit) {
const conditions = [
eq(boardEvents.companyId, companyId),
gt(boardEvents.seq, cursorSeq),
];
if (parsed.eventTypes && parsed.eventTypes.size > 0) {
conditions.push(inArray(boardEvents.eventType, Array.from(parsed.eventTypes)));
}
if (parsed.issueUuid) {
conditions.push(eq(boardEvents.issueId, parsed.issueUuid));
}
const rows = await db
.select()
.from(boardEvents)
.where(and(...conditions))
.orderBy(asc(boardEvents.seq))
.limit(batchSize);
if (rows.length === 0) break;
const batchIssueIds = Array.from(
new Set(rows.map((r) => r.issueId).filter((id): id is string => Boolean(id))),
);
const readableIssueIds = new Set<string>();
if (batchIssueIds.length > 0) {
const readCondition = await issueReadSqlCondition(db, effectiveAuthActor);
const readableRows = await db
.select({ id: issues.id })
.from(issues)
.where(
and(
eq(issues.companyId, companyId),
inArray(issues.id, batchIssueIds),
readCondition,
),
);
for (const r of readableRows) {
readableIssueIds.add(r.id);
}
}
for (const row of rows) {
const ev = serializeBoardEventRow(row);
cursorSeq = Math.max(cursorSeq, ev.seq);
if (
await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
issueLabelCache,
readableIssueIds,
effectiveAuthActor,
)
) {
results.push(ev);
if (results.length >= limit) break;
}
}
if (rows.length < batchSize) break;
}
return results;
}
export async function waitForBoardEvent(
db: Db,
companyId: string,
actor: HeadlessActorContext,
filters: BoardEventFilterInput,
opts: {
timeoutMs?: number;
signal?: AbortSignal;
authActor?: AuthorizationActor;
onResolvedCursor?: (cursor: string) => void;
} = {},
): Promise<BoardEventView | null> {
enforceHeadlessScopes(actor, { action: "events.read" });
const parsed = parseBoardEventFilters(filters);
const timeoutMs = Math.min(Math.max(0, opts.timeoutMs ?? 30_000), 120_000);
const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor);
const channelCache = new Map<string, boolean>();
const issueLabelCache = new Map<
string,
{ kvLabels: Record<string, string>; tagLabels: string[] }
>();
const buffered: BoardEventView[] = [];
let checkingInitial = true;
let resolveWaiter: ((ev: BoardEventView | null) => void) | null = null;
const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => {
if (checkingInitial) {
buffered.push(ev);
return;
}
if (ev.seq <= parsed.afterSeq) return;
void eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
issueLabelCache,
undefined,
effectiveAuthActor,
)
.then((ok) => {
if (ok && resolveWaiter) {
const resolveFn = resolveWaiter;
resolveWaiter = null;
resolveFn(ev);
}
})
.catch(() => {});
});
try {
if (parsed.hasExplicitAfter) {
opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq));
const existing = await queryBoardEventsAfter(db, companyId, actor, parsed, {
limit: 1,
authActor: effectiveAuthActor,
});
if (existing.length > 0) {
return existing[0]!;
}
} else {
parsed.afterSeq = await getCurrentCompanyMaxEventSeq(db, companyId);
opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq));
}
// Drain any events buffered during the initial query while keeping
// checkingInitial=true so newly arriving events keep buffering until we
// synchronously install resolveWaiter below (zero missed-event window).
while (buffered.length > 0) {
const ev = buffered.shift()!;
if (
await eventMatchesFiltersAndAccess(
db,
companyId,
actor,
ev,
parsed,
channelCache,
issueLabelCache,
undefined,
effectiveAuthActor,
)
) {
return ev;
}
}
if (timeoutMs <= 0 || opts.signal?.aborted) {
return null;
}
return await new Promise<BoardEventView | null>((resolve) => {
let settled = false;
const finish = (result: BoardEventView | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
opts.signal?.removeEventListener("abort", onAbort);
resolveWaiter = null;
resolve(result);
};
const onAbort = () => finish(null);
resolveWaiter = finish;
checkingInitial = false;
const timer = setTimeout(() => finish(null), timeoutMs);
opts.signal?.addEventListener("abort", onAbort, { once: true });
});
} finally {
unsubscribe();
}
}
export async function createSchedule(
db: Db,
companyId: string,
@@ -2294,6 +1708,7 @@ export function createScheduledBoardPostsWorker(
title,
body: row.message,
kvLabels: row.kvLabels ?? {},
tagLabels: [],
blocks: row.schemaBlocks ?? [],
scheduleId: row.id,
},
@@ -2313,6 +1728,7 @@ export function createScheduledBoardPostsWorker(
title,
body: row.message,
kvLabels: row.kvLabels ?? {},
tagLabels: [],
blocks: row.schemaBlocks ?? [],
scheduleId: row.id,
},
@@ -2329,6 +1745,7 @@ export function createScheduledBoardPostsWorker(
actor: scheduleActor,
payload: {
kvLabels: row.kvLabels ?? {},
tagLabels: [],
scheduleId: row.id,
},
}),
+55 -43
View File
@@ -7,6 +7,7 @@ import {
issueBatchIdempotencyKeys,
issueRelations,
issues,
primeDatabaseWorkTransactionId,
projects,
} from "@paperclipai/db";
import {
@@ -20,6 +21,7 @@ import {
} from "@paperclipai/shared";
import { badRequest, conflict, unprocessable } from "../errors.js";
import {
createActivityDetailsRedactor,
logActivity,
publishActivity,
type ActivityPublication,
@@ -33,8 +35,8 @@ import {
appendBoardEvent,
assertIssueChannelScopeAccess,
assertProjectReadAccess,
buildNextIssueCounterSql,
enforceHeadlessScopes,
loadHeadlessIssueView,
loadHeadlessIssueViews,
publishCommittedBoardEvent,
resolveIssueByIdOrIdentifier,
@@ -241,6 +243,7 @@ export async function createBatchIssuesPlan(
});
const requestHash = hashCanonicalRequest(rawInput);
const activityRedactor = await createActivityDetailsRedactor(db);
const publications: ActivityPublication[] = [];
const committedEvents: BoardEventView[] = [];
@@ -344,44 +347,6 @@ export async function createBatchIssuesPlan(
});
}
// Atomically allocate issue numbers for the batch
const now = new Date();
const [maxRow] = await tx
.select({
maxNum: sql<number>`coalesce(max(${issues.issueNumber}), 0)`,
})
.from(issues)
.where(eq(issues.companyId, companyId));
const currentMax = Number(maxRow?.maxNum ?? 0);
const [companyRow] = await tx
.update(companies)
.set({
issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + ${plan.tasks.length}`,
updatedAt: now,
})
.where(eq(companies.id, companyId))
.returning({
issueCounter: companies.issueCounter,
issuePrefix: companies.issuePrefix,
});
const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1;
const createdByKey = new Map<string, typeof issues.$inferSelect>();
const createdRows: Array<typeof issues.$inferSelect> = [];
const pendingEvents: Array<{
issueId: string;
identifier: string;
key: string | null;
type: "task.created" | "task.ready";
payload: Record<string, unknown>;
isTaskCreated?: boolean;
}> = [];
const cursorByIssueId = new Map<string, string>();
const keyByIssueId = new Map<string, string | null>();
// Pre-fetch private project visibility for all referenced projects
const referencedProjectIds = Array.from(
new Set(
resolvedTaskConfigs
@@ -405,6 +370,44 @@ export async function createBatchIssuesPlan(
}
}
const now = new Date();
const nextBatchCounterExpr = buildNextIssueCounterSql(
companyId,
plan.tasks.length,
);
const [companyRow] = await tx
.update(companies)
.set({
issueCounter: nextBatchCounterExpr,
updatedAt: now,
})
.where(eq(companies.id, companyId))
.returning({
issueCounter: companies.issueCounter,
issuePrefix: companies.issuePrefix,
xid: sql<string>`pg_current_xact_id()::text`,
});
if (companyRow?.xid) {
primeDatabaseWorkTransactionId(tx, companyRow.xid);
}
const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1;
const createdByKey = new Map<string, typeof issues.$inferSelect>();
const createdRows: Array<typeof issues.$inferSelect> = [];
const pendingEvents: Array<{
issueId: string;
identifier: string;
key: string | null;
type: "task.created" | "task.ready";
payload: Record<string, unknown>;
isTaskCreated?: boolean;
}> = [];
const cursorByIssueId = new Map<string, string>();
const keyByIssueId = new Map<string, string | null>();
for (let i = 0; i < plan.tasks.length; i += 1) {
const task = plan.tasks[i]!;
const cfg = resolvedTaskConfigs[i]!;
@@ -462,9 +465,10 @@ export async function createBatchIssuesPlan(
createdByKey.set(task.key, inserted!);
}
if (task.tagLabels.length > 0) {
await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels);
}
const attachedTagNames =
task.tagLabels.length > 0
? await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels)
: [];
const blockerIds: string[] = [];
let hasOpenBlocker = false;
@@ -530,6 +534,7 @@ export async function createBatchIssuesPlan(
},
},
publications,
{ redactor: activityRedactor },
);
pendingEvents.push({
@@ -542,6 +547,9 @@ export async function createBatchIssuesPlan(
key: task.key,
title: task.title,
...(description ? { description: description.slice(0, 4000) } : {}),
labels: task.labels,
kvLabels: task.labels,
tagLabels: attachedTagNames,
blockedByIssueIds: blockerIds,
},
});
@@ -552,7 +560,11 @@ export async function createBatchIssuesPlan(
identifier,
key: task.key ?? null,
type: "task.ready",
payload: { key: task.key },
payload: {
key: task.key,
kvLabels: task.labels,
tagLabels: attachedTagNames,
},
});
}
}