Files
PaperClipAI/server/src/services/headless-common.ts
T
DottaandPaperclip debfa75a7a perf(server): coalesce concurrent channel posts and replies with debounced activity (#23448)
## Thinking Path

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

## Linked Issues or Issue Description

Refs #23426

**What existing behavior does this improve?**

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

**Subsystem affected**

- `server/ — REST API & orchestration services`

**Current behavior**

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

**Proposed behavior**

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

**Reason and benefit**

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

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

**Breaking changes**

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

**Additional context**

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

## What Changed

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

## Verification

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

## Risks

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

## Model Used

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

## Checklist

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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-12-02 06:13:26 -06:00

1260 lines
38 KiB
TypeScript

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