mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 11:47:42 +01:00
## 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>
1418 lines
43 KiB
TypeScript
1418 lines
43 KiB
TypeScript
import { EventEmitter } from "node:events";
|
|
import type { Request } from "express";
|
|
import { and, desc, eq, inArray, ne, or, sql, type SQL } from "drizzle-orm";
|
|
import type { Db } from "@paperclipai/db";
|
|
import {
|
|
agents,
|
|
boardApiKeys,
|
|
boardEvents,
|
|
channelAccessMembers,
|
|
channels,
|
|
companies,
|
|
issueLabels,
|
|
issues,
|
|
labels,
|
|
projects,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
clientScopesSchema,
|
|
deriveAgentUrlKey,
|
|
deriveProjectUrlKey,
|
|
formatEventCursor,
|
|
isUuidLike,
|
|
normalizeChannelPath,
|
|
normalizeIssueIdentifier,
|
|
type AgentApiKeyScope,
|
|
type AgentIdentityPolicy,
|
|
type BoardEventType,
|
|
type BoardEventView,
|
|
type ClientScopes,
|
|
type CommentView,
|
|
type DeploymentMode,
|
|
type HeadlessIssueView,
|
|
type IssuePriority,
|
|
type IssueScope,
|
|
type IssueStatus,
|
|
type LabelFilterExpr,
|
|
type SchemaBlock,
|
|
} from "@paperclipai/shared";
|
|
import { badRequest, conflict, forbidden, notFound, unauthorized } from "../errors.js";
|
|
import {
|
|
authorizationService,
|
|
issueReadSqlCondition,
|
|
type AuthorizationActor,
|
|
} from "./authorization.js";
|
|
import { publishLiveEvent } from "./live-events.js";
|
|
import { listIssueDependencyReadinessMap } from "./issues.js";
|
|
|
|
export type DbOrTx = Db | Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
|
|
const boardEventEmitter = new EventEmitter();
|
|
boardEventEmitter.setMaxListeners(0);
|
|
|
|
export function subscribeCompanyBoardEvents(
|
|
companyId: string,
|
|
listener: (event: BoardEventView) => void,
|
|
): () => void {
|
|
boardEventEmitter.on(companyId, listener);
|
|
return () => boardEventEmitter.off(companyId, listener);
|
|
}
|
|
|
|
export function publishCommittedBoardEvent(event: BoardEventView): void {
|
|
boardEventEmitter.emit(event.companyId, event);
|
|
publishLiveEvent({
|
|
companyId: event.companyId,
|
|
type: "activity.logged",
|
|
payload: {
|
|
boardEventSeq: event.seq,
|
|
boardEventCursor: event.cursor,
|
|
boardEventType: event.type,
|
|
channel: event.channel,
|
|
issueId: event.issueId,
|
|
identifier: event.identifier,
|
|
},
|
|
});
|
|
}
|
|
|
|
export 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,
|
|
};
|
|
|
|
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: {
|
|
companyId: string;
|
|
type: BoardEventType;
|
|
channelId?: string | null;
|
|
channelPath?: string | null;
|
|
issueId?: string | null;
|
|
identifier?: string | null;
|
|
actor: Pick<
|
|
HeadlessActorContext,
|
|
"principalType" | "userId" | "agentId" | "agentName" | "actorProfile"
|
|
> | {
|
|
principalType: "system";
|
|
userId?: null;
|
|
agentId?: null;
|
|
agentName?: null;
|
|
actorProfile?: string | null;
|
|
};
|
|
payload?: Record<string, unknown>;
|
|
},
|
|
): Promise<BoardEventView> {
|
|
const actorType: "user" | "agent" | "system" =
|
|
input.actor.principalType === "agent"
|
|
? "agent"
|
|
: input.actor.principalType === "system"
|
|
? "system"
|
|
: "user";
|
|
const actorId =
|
|
input.actor.principalType === "agent"
|
|
? input.actor.agentId ?? null
|
|
: input.actor.principalType === "system"
|
|
? "system"
|
|
: input.actor.userId ?? null;
|
|
const actorName =
|
|
input.actor.principalType === "agent"
|
|
? input.actor.agentName ?? null
|
|
: null;
|
|
const actorProfile = input.actor.actorProfile ?? null;
|
|
const payloadObj = input.payload ?? {};
|
|
const payloadJson = JSON.stringify(payloadObj);
|
|
const issueIdVal = input.issueId ?? null;
|
|
|
|
const hasExplicitIssueKv =
|
|
isPlainObjectRecord(payloadObj.kvLabels) ||
|
|
(input.type === "labels.changed" && isPlainObjectRecord(payloadObj.current)) ||
|
|
((input.type === "thread.posted" ||
|
|
input.type === "task.created" ||
|
|
input.type === "task.ready") &&
|
|
isPlainObjectRecord(payloadObj.labels));
|
|
const hasExplicitTagLabels = Array.isArray(payloadObj.tagLabels);
|
|
|
|
let payloadExpr: SQL = sql`${payloadJson}::jsonb`;
|
|
if (issueIdVal && (!hasExplicitIssueKv || !hasExplicitTagLabels)) {
|
|
const kvSelectSql = sql`coalesce((select ${issues.kvLabels} from ${issues} where ${issues.id} = ${issueIdVal}::uuid and ${issues.companyId} = ${input.companyId}::uuid), '{}'::jsonb)`;
|
|
const tagSelectSql = sql`coalesce((select jsonb_agg(${labels.name} order by ${labels.name}) from ${issueLabels} inner join ${labels} on ${labels.id} = ${issueLabels.labelId} where ${issueLabels.issueId} = ${issueIdVal}::uuid and ${issueLabels.companyId} = ${input.companyId}::uuid), '[]'::jsonb)`;
|
|
if (!hasExplicitIssueKv && !hasExplicitTagLabels) {
|
|
payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}, 'tagLabels', ${tagSelectSql}))`;
|
|
} else if (!hasExplicitIssueKv) {
|
|
payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}))`;
|
|
} else {
|
|
payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('tagLabels', ${tagSelectSql}))`;
|
|
}
|
|
}
|
|
|
|
const [inserted] = await dbOrTx.execute<{
|
|
seq: string | number;
|
|
created_at: Date | string;
|
|
payload: Record<string, unknown> | string;
|
|
}>(sql`
|
|
INSERT INTO ${boardEvents} (
|
|
${sql.raw(boardEvents.companyId.name)},
|
|
${sql.raw(boardEvents.eventType.name)},
|
|
${sql.raw(boardEvents.channelId.name)},
|
|
${sql.raw(boardEvents.channelPath.name)},
|
|
${sql.raw(boardEvents.issueId.name)},
|
|
${sql.raw(boardEvents.identifier.name)},
|
|
${sql.raw(boardEvents.actorType.name)},
|
|
${sql.raw(boardEvents.actorId.name)},
|
|
${sql.raw(boardEvents.actorName.name)},
|
|
${sql.raw(boardEvents.actorProfile.name)},
|
|
${sql.raw(boardEvents.payload.name)}
|
|
)
|
|
SELECT
|
|
${input.companyId}::uuid,
|
|
${input.type},
|
|
${input.channelId ?? null}::uuid,
|
|
${input.channelPath ?? null},
|
|
${issueIdVal}::uuid,
|
|
${input.identifier ?? null},
|
|
${actorType},
|
|
${actorId},
|
|
${actorName},
|
|
${actorProfile},
|
|
${payloadExpr}
|
|
FROM (
|
|
SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId}))
|
|
) AS _lock
|
|
RETURNING
|
|
${sql.raw(boardEvents.seq.name)},
|
|
${sql.raw(boardEvents.createdAt.name)},
|
|
${sql.raw(boardEvents.payload.name)}
|
|
`);
|
|
|
|
const seq = Number(inserted!.seq);
|
|
const createdAtIso =
|
|
inserted!.created_at instanceof Date
|
|
? inserted!.created_at.toISOString()
|
|
: new Date(inserted!.created_at).toISOString();
|
|
const persistedPayload: Record<string, unknown> =
|
|
typeof inserted!.payload === "string"
|
|
? (JSON.parse(inserted!.payload) as Record<string, unknown>)
|
|
: isPlainObjectRecord(inserted!.payload)
|
|
? inserted!.payload
|
|
: payloadObj;
|
|
return {
|
|
cursor: formatEventCursor(seq),
|
|
seq,
|
|
type: input.type,
|
|
companyId: input.companyId,
|
|
channel: input.channelPath ?? null,
|
|
issueId: issueIdVal,
|
|
identifier: input.identifier ?? null,
|
|
actor: {
|
|
type: actorType,
|
|
id: actorId,
|
|
name: actorName,
|
|
profile: actorProfile,
|
|
},
|
|
payload: persistedPayload,
|
|
createdAt: createdAtIso,
|
|
};
|
|
}
|
|
|
|
export async function getLatestCompanyEventCursor(
|
|
dbOrTx: DbOrTx,
|
|
companyId: string,
|
|
): Promise<string> {
|
|
const [latest] = await dbOrTx
|
|
.select({ seq: boardEvents.seq })
|
|
.from(boardEvents)
|
|
.where(eq(boardEvents.companyId, companyId))
|
|
.orderBy(desc(boardEvents.seq))
|
|
.limit(1);
|
|
return formatEventCursor(latest ? Number(latest.seq) : 0);
|
|
}
|
|
|
|
export async function loadHeadlessIssueViews(
|
|
dbOrTx: DbOrTx,
|
|
issueRows: Array<typeof issues.$inferSelect>,
|
|
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(),
|
|
};
|
|
}
|