mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 04:29:01 +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>
784 lines
22 KiB
TypeScript
784 lines
22 KiB
TypeScript
import { Router, type Request, type Response } from "express";
|
|
import { type Db } from "@paperclipai/db";
|
|
import {
|
|
parseDurationMs,
|
|
type BoardEventType,
|
|
type BoardEventView,
|
|
type DeploymentMode,
|
|
} from "@paperclipai/shared";
|
|
import { badRequest, forbidden, notFound, unauthorized } from "../errors.js";
|
|
import { authorizationDeniedDetails, authorizationService } from "../services/authorization.js";
|
|
import { heartbeatService } from "../services/heartbeat.js";
|
|
import {
|
|
assertCanonicalIssueAccess,
|
|
assertIssueChannelScopeAccess,
|
|
resolveHeadlessActor,
|
|
resolveHeadlessIssueReadCondition,
|
|
resolveIssueByIdOrIdentifier,
|
|
subscribeCompanyBoardEvents,
|
|
type HeadlessActorContext,
|
|
} from "../services/headless-common.js";
|
|
import {
|
|
claimTask,
|
|
completeTaskClaim,
|
|
failTaskClaim,
|
|
releaseTaskClaim,
|
|
renewTaskClaim,
|
|
} from "../services/headless-task-queue.js";
|
|
import {
|
|
assignTask,
|
|
cancelTask,
|
|
handoffTask,
|
|
reopenTask,
|
|
} from "../services/headless-task-workflows.js";
|
|
import {
|
|
listTaskDependencies,
|
|
mutateTaskDependencies,
|
|
} from "../services/headless-task-dependencies.js";
|
|
import {
|
|
dispatchManagedChannelPoolBestEffort,
|
|
dispatchManagedChannelPoolsForCompletedIssueBestEffort,
|
|
} from "../services/headless-channel-admin.js";
|
|
import {
|
|
approveOnIssue,
|
|
cancelSchedule,
|
|
confirmOnIssue,
|
|
createSchedule,
|
|
filterBoardEventsBatchForSubscriber,
|
|
getCurrentCompanyMaxEventSeq,
|
|
listSchedules,
|
|
parseBoardEventFilters,
|
|
queryBoardEventsAfter,
|
|
rejectOnIssue,
|
|
askOnIssue,
|
|
waitForBoardEvent,
|
|
type BoardEventFilterInput,
|
|
} from "../services/headless-events-schedules-interactions.js";
|
|
|
|
function toCommaSplitStrings(value: unknown): string[] {
|
|
if (typeof value === "string") {
|
|
return value
|
|
.split(",")
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value
|
|
.flatMap((v) => (typeof v === "string" ? v.split(",") : []))
|
|
.map((s) => s.trim())
|
|
.filter(Boolean);
|
|
}
|
|
return [];
|
|
}
|
|
|
|
function toStringList(value: unknown): string[] {
|
|
if (typeof value === "string") {
|
|
const trimmed = value.trim();
|
|
return trimmed ? [trimmed] : [];
|
|
}
|
|
if (Array.isArray(value)) {
|
|
return value
|
|
.filter((v): v is string => typeof v === "string")
|
|
.map((v) => v.trim())
|
|
.filter(Boolean);
|
|
}
|
|
return [];
|
|
}
|
|
|
|
function parseEventQuery(
|
|
req: Request,
|
|
fallbackAfter?: string,
|
|
): BoardEventFilterInput {
|
|
const channel =
|
|
typeof req.query.channel === "string" ? req.query.channel : undefined;
|
|
const issueId =
|
|
typeof req.query.issueId === "string" ? req.query.issueId : undefined;
|
|
const eventList = toCommaSplitStrings(req.query.event) as BoardEventType[];
|
|
const labelList = toStringList(req.query.label);
|
|
const mentions =
|
|
typeof req.query.mentions === "string" ? req.query.mentions : undefined;
|
|
const schema =
|
|
typeof req.query.schema === "string" ? req.query.schema : undefined;
|
|
const after =
|
|
typeof req.query.after === "string" && req.query.after.trim() !== ""
|
|
? req.query.after.trim()
|
|
: fallbackAfter?.trim() || undefined;
|
|
|
|
return {
|
|
...(channel ? { channel } : {}),
|
|
...(issueId ? { issueId } : {}),
|
|
...(eventList.length > 0 ? { event: eventList } : {}),
|
|
...(labelList.length > 0 ? { label: labelList } : {}),
|
|
...(mentions ? { mentions } : {}),
|
|
...(schema ? { schema } : {}),
|
|
...(after ? { after } : {}),
|
|
};
|
|
}
|
|
|
|
function parseOptionalTimeoutMs(req: Request): number | undefined {
|
|
if (typeof req.query.timeoutMs === "string" && req.query.timeoutMs.trim() !== "") {
|
|
const num = Number(req.query.timeoutMs);
|
|
if (!Number.isFinite(num) || num < 0) {
|
|
throw badRequest("Invalid timeoutMs query parameter");
|
|
}
|
|
return Math.floor(num);
|
|
}
|
|
if (typeof req.query.timeout === "string" && req.query.timeout.trim() !== "") {
|
|
try {
|
|
return parseDurationMs(req.query.timeout);
|
|
} catch (err) {
|
|
throw badRequest(
|
|
err instanceof Error ? err.message : "Invalid timeout query parameter",
|
|
);
|
|
}
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
async function resolveIssueAndActor(
|
|
db: Db,
|
|
req: Request,
|
|
idOrIdentifier: string,
|
|
deploymentMode: DeploymentMode | undefined,
|
|
requiredAction: string,
|
|
canonicalAction: "issue:read" | "issue:comment" | "issue:mutate" = "issue:mutate",
|
|
): Promise<{ issue: Awaited<ReturnType<typeof resolveIssueByIdOrIdentifier>>; actor: HeadlessActorContext }> {
|
|
if (!req.actor || req.actor.type === "none") {
|
|
throw unauthorized("Authentication required");
|
|
}
|
|
|
|
const expectedCompanyId =
|
|
req.actor.type === "agent" ? req.actor.companyId ?? undefined : undefined;
|
|
const issue = await resolveIssueByIdOrIdentifier(
|
|
db,
|
|
idOrIdentifier,
|
|
expectedCompanyId,
|
|
);
|
|
|
|
if (
|
|
req.actor.type === "board" &&
|
|
req.actor.source !== "local_implicit" &&
|
|
!req.actor.isInstanceAdmin &&
|
|
!(req.actor.companyIds ?? []).includes(issue.companyId)
|
|
) {
|
|
throw notFound(`Issue '${idOrIdentifier}' not found`);
|
|
}
|
|
|
|
const actor = await resolveHeadlessActor(db, req, issue.companyId, {
|
|
deploymentMode,
|
|
requiredAction,
|
|
});
|
|
|
|
await assertCanonicalIssueAccess(db, req, issue, canonicalAction);
|
|
await assertIssueChannelScopeAccess(db, issue, actor);
|
|
|
|
return { issue, actor };
|
|
}
|
|
|
|
function formatSseFrame(ev: BoardEventView): string {
|
|
return `id: ${ev.cursor}\nevent: ${ev.type}\ndata: ${JSON.stringify(ev)}\n\n`;
|
|
}
|
|
|
|
export function headlessQueuesEventsRoutes(
|
|
db: Db,
|
|
opts?: {
|
|
deploymentMode?: DeploymentMode;
|
|
heartbeat?: ReturnType<typeof heartbeatService>;
|
|
},
|
|
) {
|
|
const router = Router();
|
|
const deploymentMode = opts?.deploymentMode;
|
|
const heartbeat = opts?.heartbeat ?? heartbeatService(db);
|
|
|
|
async function assertCanAssignTask(
|
|
txOrDb: Db | Parameters<Parameters<Db["transaction"]>[0]>[0],
|
|
req: Request,
|
|
issue: Awaited<ReturnType<typeof resolveIssueByIdOrIdentifier>>,
|
|
targetAssigneeAgentId?: string | null,
|
|
) {
|
|
const effectiveAssigneeAgentId =
|
|
targetAssigneeAgentId !== undefined ? targetAssigneeAgentId : issue.assigneeAgentId;
|
|
const effectiveAssigneeUserId =
|
|
targetAssigneeAgentId !== undefined ? null : issue.assigneeUserId;
|
|
const decision = await authorizationService(txOrDb as unknown as Db).decide({
|
|
actor: req.actor,
|
|
action: "tasks:assign",
|
|
resource: {
|
|
type: "issue",
|
|
companyId: issue.companyId,
|
|
issueId: issue.id,
|
|
projectId: issue.projectId,
|
|
parentIssueId: issue.parentId,
|
|
assigneeAgentId: effectiveAssigneeAgentId,
|
|
assigneeUserId: effectiveAssigneeUserId,
|
|
},
|
|
scope: {
|
|
issueId: issue.id,
|
|
projectId: issue.projectId,
|
|
parentIssueId: issue.parentId,
|
|
assigneeAgentId: effectiveAssigneeAgentId,
|
|
assigneeUserId: effectiveAssigneeUserId,
|
|
},
|
|
});
|
|
if (!decision.allowed) {
|
|
throw forbidden(decision.explanation, authorizationDeniedDetails(decision));
|
|
}
|
|
}
|
|
|
|
const buildWakeHandler = () => async (wake: {
|
|
companyId: string;
|
|
issueId: string;
|
|
assigneeAgentId: string;
|
|
interactionId: string;
|
|
interactionKind: string;
|
|
interactionStatus: string;
|
|
sourceCommentId: string | null;
|
|
actor: HeadlessActorContext;
|
|
}) => {
|
|
await heartbeat.wakeup(wake.assigneeAgentId, {
|
|
source: "automation",
|
|
triggerDetail: "system",
|
|
reason: "issue_commented",
|
|
payload: {
|
|
issueId: wake.issueId,
|
|
interactionId: wake.interactionId,
|
|
interactionKind: wake.interactionKind,
|
|
interactionStatus: wake.interactionStatus,
|
|
sourceCommentId: wake.sourceCommentId,
|
|
mutation: "interaction",
|
|
},
|
|
idempotencyKey: `interaction:${wake.interactionId}:${wake.interactionStatus}`,
|
|
requestedByActorType: wake.actor.principalType === "agent" ? "agent" : "user",
|
|
requestedByActorId:
|
|
wake.actor.principalType === "agent"
|
|
? wake.actor.agentId ?? "unknown-agent"
|
|
: wake.actor.userId ?? "board",
|
|
contextSnapshot: {
|
|
issueId: wake.issueId,
|
|
taskId: wake.issueId,
|
|
interactionId: wake.interactionId,
|
|
interactionKind: wake.interactionKind,
|
|
interactionStatus: wake.interactionStatus,
|
|
wakeReason: "issue_commented",
|
|
},
|
|
});
|
|
};
|
|
|
|
router.post("/companies/:companyId/tasks/claim", async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
const actor = await resolveHeadlessActor(db, req, companyId, {
|
|
deploymentMode,
|
|
requiredAction: "tasks.claim",
|
|
});
|
|
|
|
const ac = new AbortController();
|
|
const onClose = () => {
|
|
if (!res.writableFinished) {
|
|
ac.abort();
|
|
}
|
|
};
|
|
res.on("close", onClose);
|
|
|
|
try {
|
|
const readCondition = await resolveHeadlessIssueReadCondition(db, req);
|
|
const claimed = await claimTask(db, companyId, actor, req.body, ac.signal, {
|
|
readCondition,
|
|
});
|
|
if (res.writableFinished || ac.signal.aborted) return;
|
|
if (!claimed) {
|
|
res.status(204).end();
|
|
return;
|
|
}
|
|
res.json(claimed);
|
|
} finally {
|
|
res.off("close", onClose);
|
|
}
|
|
});
|
|
|
|
router.post("/issues/:id/claim/renew", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.claim_renew",
|
|
);
|
|
const result = await renewTaskClaim(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/claim/release", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.claim_release",
|
|
);
|
|
const result = await releaseTaskClaim(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
if (issue.channelId) {
|
|
await dispatchManagedChannelPoolBestEffort(db, issue.companyId, issue.channelId, {
|
|
heartbeat,
|
|
actor,
|
|
});
|
|
}
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/claim/complete", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.complete",
|
|
);
|
|
const result = await completeTaskClaim(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
await dispatchManagedChannelPoolsForCompletedIssueBestEffort(
|
|
db,
|
|
issue.companyId,
|
|
result.id,
|
|
result.channelId,
|
|
{ heartbeat, actor },
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/claim/fail", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.fail",
|
|
);
|
|
const result = await failTaskClaim(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/assign", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.assign",
|
|
);
|
|
const result = await assignTask(db, issue.id, actor, req.body, {
|
|
heartbeat,
|
|
authorizeTargetAssignee: (tx, targetAgentId) =>
|
|
assertCanAssignTask(tx, req, issue, targetAgentId),
|
|
});
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/handoff", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.handoff",
|
|
);
|
|
const result = await handoffTask(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
{
|
|
heartbeat,
|
|
authorizeTargetAssignee: (tx, targetAgentId) =>
|
|
assertCanAssignTask(tx, req, issue, targetAgentId),
|
|
},
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/cancel", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.cancel",
|
|
);
|
|
const result = await cancelTask(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
if (result.channelId) {
|
|
await dispatchManagedChannelPoolBestEffort(db, issue.companyId, result.channelId, {
|
|
heartbeat,
|
|
actor,
|
|
});
|
|
}
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/reopen", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.reopen",
|
|
);
|
|
if (issue.status === "done" || issue.status === "cancelled") {
|
|
await assertCanAssignTask(db, req, issue);
|
|
}
|
|
const result = await reopenTask(db, issue.id, actor, req.body, {
|
|
heartbeat,
|
|
});
|
|
res.json(result);
|
|
});
|
|
|
|
router.get("/issues/:id/dependencies", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"read",
|
|
"issue:read",
|
|
);
|
|
const result = await listTaskDependencies(db, issue.id, actor);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/dependencies", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"tasks.dependencies",
|
|
);
|
|
const result = await mutateTaskDependencies(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/ask", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"interactions.create",
|
|
);
|
|
const result = await askOnIssue(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/confirm", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"interactions.create",
|
|
);
|
|
const result = await confirmOnIssue(
|
|
db,
|
|
issue.id,
|
|
actor,
|
|
req.body,
|
|
req.header("x-paperclip-claim-token") ?? undefined,
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/approve", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"interactions.resolve",
|
|
);
|
|
const result = await approveOnIssue(db, issue.id, actor, req.body, {
|
|
onWakeAssignee: buildWakeHandler(),
|
|
});
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/issues/:id/reject", async (req, res) => {
|
|
const { issue, actor } = await resolveIssueAndActor(
|
|
db,
|
|
req,
|
|
req.params.id as string,
|
|
deploymentMode,
|
|
"interactions.resolve",
|
|
);
|
|
const result = await rejectOnIssue(db, issue.id, actor, req.body, {
|
|
onWakeAssignee: buildWakeHandler(),
|
|
});
|
|
res.json(result);
|
|
});
|
|
|
|
router.post("/companies/:companyId/schedules", async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
const actor = await resolveHeadlessActor(db, req, companyId, {
|
|
deploymentMode,
|
|
requiredAction: "schedules.create",
|
|
});
|
|
const schedule = await createSchedule(db, companyId, actor, req.body, {
|
|
authActor: req.actor,
|
|
});
|
|
res.status(201).json(schedule);
|
|
});
|
|
|
|
router.get("/companies/:companyId/schedules", async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
const actor = await resolveHeadlessActor(db, req, companyId, {
|
|
deploymentMode,
|
|
requiredAction: "schedules.read",
|
|
});
|
|
const target =
|
|
typeof req.query.target === "string" ? req.query.target : undefined;
|
|
const items = await listSchedules(db, companyId, actor, { target }, {
|
|
authActor: req.actor,
|
|
});
|
|
res.json({ items });
|
|
});
|
|
|
|
router.delete("/companies/:companyId/schedules/:id", async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
const actor = await resolveHeadlessActor(db, req, companyId, {
|
|
deploymentMode,
|
|
requiredAction: "schedules.cancel",
|
|
});
|
|
const result = await cancelSchedule(
|
|
db,
|
|
companyId,
|
|
actor,
|
|
req.params.id as string,
|
|
{ authActor: req.actor },
|
|
);
|
|
res.json(result);
|
|
});
|
|
|
|
router.get("/companies/:companyId/events/wait", async (req, res) => {
|
|
const companyId = req.params.companyId as string;
|
|
const actor = await resolveHeadlessActor(db, req, companyId, {
|
|
deploymentMode,
|
|
requiredAction: "events.read",
|
|
});
|
|
const filters = parseEventQuery(req);
|
|
const timeoutMs = parseOptionalTimeoutMs(req);
|
|
|
|
const ac = new AbortController();
|
|
const onClose = () => {
|
|
if (!res.writableFinished) {
|
|
ac.abort();
|
|
}
|
|
};
|
|
res.on("close", onClose);
|
|
|
|
try {
|
|
let resolvedCursor: string | undefined;
|
|
const event = await waitForBoardEvent(db, companyId, actor, filters, {
|
|
timeoutMs,
|
|
signal: ac.signal,
|
|
authActor: req.actor,
|
|
onResolvedCursor: (cursor) => {
|
|
resolvedCursor = cursor;
|
|
},
|
|
});
|
|
if (res.writableFinished || ac.signal.aborted) return;
|
|
if (!event) {
|
|
if (resolvedCursor) {
|
|
res.setHeader("X-Paperclip-Cursor", resolvedCursor);
|
|
}
|
|
res.status(204).end();
|
|
return;
|
|
}
|
|
res.json(event);
|
|
} finally {
|
|
res.off("close", onClose);
|
|
}
|
|
});
|
|
|
|
router.get("/companies/:companyId/events/stream", async (req, res: Response) => {
|
|
const companyId = req.params.companyId as string;
|
|
const actor = await resolveHeadlessActor(db, req, companyId, {
|
|
deploymentMode,
|
|
requiredAction: "events.read",
|
|
});
|
|
const filters = parseEventQuery(
|
|
req,
|
|
req.header("last-event-id") ?? undefined,
|
|
);
|
|
const parsedFilters = parseBoardEventFilters(filters);
|
|
|
|
res.status(200);
|
|
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
|
|
res.setHeader("Cache-Control", "no-cache, no-transform");
|
|
res.setHeader("Connection", "keep-alive");
|
|
res.setHeader("X-Accel-Buffering", "no");
|
|
res.flushHeaders?.();
|
|
res.write(": connected\n\n");
|
|
|
|
let closed = false;
|
|
let replaying = true;
|
|
let lastSentSeq = parsedFilters.afterSeq;
|
|
const buffered: BoardEventView[] = [];
|
|
const pendingLiveEvents: BoardEventView[] = [];
|
|
let drainingLive = false;
|
|
const drainLiveEvents = async () => {
|
|
if (drainingLive || closed) return;
|
|
drainingLive = true;
|
|
try {
|
|
while (!closed && pendingLiveEvents.length > 0) {
|
|
const rawBatch = pendingLiveEvents.splice(0, 256);
|
|
const unseenBatch = rawBatch.filter((ev) => ev.seq > lastSentSeq);
|
|
if (unseenBatch.length === 0) continue;
|
|
|
|
const matched = await filterBoardEventsBatchForSubscriber(
|
|
db,
|
|
companyId,
|
|
actor,
|
|
unseenBatch,
|
|
parsedFilters,
|
|
req.actor,
|
|
undefined,
|
|
pendingLiveEvents,
|
|
);
|
|
if (closed) break;
|
|
|
|
const frames: string[] = [];
|
|
for (const ev of matched) {
|
|
if (ev.seq <= lastSentSeq) continue;
|
|
lastSentSeq = ev.seq;
|
|
frames.push(formatSseFrame(ev));
|
|
}
|
|
if (frames.length > 0 && !closed) {
|
|
res.write(frames.join(""));
|
|
}
|
|
}
|
|
} catch (err) {
|
|
void err;
|
|
} finally {
|
|
drainingLive = false;
|
|
if (!closed && pendingLiveEvents.length > 0) {
|
|
void drainLiveEvents();
|
|
}
|
|
}
|
|
};
|
|
|
|
const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => {
|
|
if (closed) return;
|
|
if (replaying) {
|
|
buffered.push(ev);
|
|
return;
|
|
}
|
|
pendingLiveEvents.push(ev);
|
|
void drainLiveEvents();
|
|
});
|
|
|
|
const keepaliveTimer = setInterval(() => {
|
|
if (!closed) {
|
|
res.write(": keepalive\n\n");
|
|
}
|
|
}, 25_000);
|
|
keepaliveTimer.unref?.();
|
|
|
|
const cleanup = () => {
|
|
if (closed) return;
|
|
closed = true;
|
|
clearInterval(keepaliveTimer);
|
|
unsubscribe();
|
|
res.off("close", cleanup);
|
|
};
|
|
|
|
res.on("close", cleanup);
|
|
|
|
try {
|
|
if (parsedFilters.hasExplicitAfter) {
|
|
const replayPageSize = 500;
|
|
let replayCursorSeq = parsedFilters.afterSeq;
|
|
while (!closed) {
|
|
const missed = await queryBoardEventsAfter(
|
|
db,
|
|
companyId,
|
|
actor,
|
|
{
|
|
...parsedFilters,
|
|
afterSeq: replayCursorSeq,
|
|
},
|
|
{ limit: replayPageSize, authActor: req.actor },
|
|
);
|
|
for (const ev of missed) {
|
|
if (closed) break;
|
|
replayCursorSeq = Math.max(replayCursorSeq, ev.seq);
|
|
if (ev.seq > lastSentSeq) {
|
|
lastSentSeq = ev.seq;
|
|
res.write(formatSseFrame(ev));
|
|
}
|
|
}
|
|
if (missed.length < replayPageSize) break;
|
|
}
|
|
} else {
|
|
const maxSeq = await getCurrentCompanyMaxEventSeq(db, companyId);
|
|
parsedFilters.afterSeq = maxSeq;
|
|
lastSentSeq = maxSeq;
|
|
}
|
|
if (!closed && buffered.length > 0) {
|
|
buffered.sort((a, b) => a.seq - b.seq);
|
|
pendingLiveEvents.push(...buffered);
|
|
}
|
|
replaying = false;
|
|
|
|
if (!closed && pendingLiveEvents.length > 0) {
|
|
await drainLiveEvents();
|
|
}
|
|
} catch {
|
|
cleanup();
|
|
if (!res.writableEnded) {
|
|
res.end();
|
|
}
|
|
}
|
|
});
|
|
|
|
return router;
|
|
}
|