mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-16 03:31:44 +01:00
perf(server): read the issue detail with fewer database statements (#21713)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The board UI loads the task page through `GET /api/issues/:id`, and
the server runs all requests on one Node main thread
> - A CPU profile of the server shows that the cost is per database
statement: SQL building, parameter encoding, result parsing and one
socket write each
> - The issue detail read sent 73 statements for a task with two
ancestors, one blocker and a project mention
> - Several of those statements read the issue row again, only to get
values that the route already loaded
> - This pull request passes the loaded issue to those reads, walks the
ancestor chain in one query, and skips reads whose result the response
does not use
> - The benefit is 9 fewer statements on each task page load (73 to 64),
plus one fewer statement for each extra ancestor level, with a
byte-identical response
## Linked Issues or Issue Description
**What existing behavior does this improve?**
`GET /api/issues/:id` reads the same issue row several times in one
request, and walks the ancestor chain with one statement for each level.
**Subsystem affected**
Server: issue routes and the issue, issue reference and project
services.
**Current behavior**
The route loads the issue, then `getRelationSummaries`,
`getCurrentScheduledRetry`, `findMentionedProjectIds`,
`listIssueReferenceSummary` and `getAncestors` each read the issue row
again. `getAncestors` sends one statement for each ancestor. The inbox
archive fields read two activity aggregates even when the issue has no
archive row. The project embed reads the workspace provider catalog, but
the compact embed does not return it. The test fixture request sends 73
statements.
**Proposed behavior**
The route passes the values it already has. The ancestor walk is one
recursive query. The activity aggregates run only when an archive row
exists. The project embed skips the provider catalog. The same fixture
request sends 64 statements, and the JSON response is the same.
**Reason and benefit**
Fewer statements per request means less CPU on the main thread for every
open task page.
**Breaking changes**
None. Other callers of the changed service functions keep the old
behavior, because the new arguments are optional.
## What Changed
- `issueService.getRelationSummaries` and `getCurrentScheduledRetry`
accept an optional known `companyId` and then skip the issue read.
- `issueService.findMentionedProjectIds` accepts the loaded issue
(`companyId`, `title`, `description`).
- `issueService.getAncestors` accepts the known `parentId` and walks the
chain in one recursive query. It keeps the order (nearest first), the
limit of 50, and the stop at a cycle or at a task that is its own
parent.
- `issueService.getActiveInboxArchiveFields` reads the archive row first
and reads the activity aggregates only when an archive row exists.
- `issueReferenceService.listIssueReferenceSummary` accepts an optional
known `companyId`.
- `issueThreadInteractionService.listForIssue` accepts the loaded issue
(`status`, `companyId`, `executionWorkspaceId`). `GET
/api/issues/:id/interactions`, which the board polls, passes it (11 to
10 statements).
- `projectService.getById` accepts `{ workspaceProvider: false }`. The
issue detail route uses it, because `compactIssueProject` never returns
`workspaceProvider`.
- Test helpers: `createStatementCensus` (statements per request, grouped
by statement shape with the server callers), and a board route fixture
with the real session actor middleware. `meterDatabaseStatements` can
record a call stack for each statement.
- New tests: `issue-detail-statements.test.ts` (statement budget,
byte-identical normalized JSON against a fixture file, access rules,
membership removal on the next request, ancestor walk with a cycle) plus
an interactions poll test, and `board-route-statement-census.test.ts`
(census of the polled and page-load board routes).
## Verification
- Red: before the change, the fixture request sent 73 statements, and
the budget test failed (`expected 73 to be less than or equal to 64`).
- Green: after the change, the request sends 64 statements. The
normalized JSON is byte-identical to the fixture file that I wrote
before the change.
- Access: another company's user gets 404, a missing issue gets 404, an
anonymous request gets 404, a hidden issue stays readable for a member,
and a removed membership gets 404 on the very next request.
- `pnpm exec vitest run` on `issue-detail-statements`,
`board-route-statement-census`, `issues-goal-context-routes`,
`issues-service`, `issue-references-service`, `inbox-archive-routes`,
`heartbeat-task-context`, `project-workspace-provider.integration`,
`workspace-provider-failure`, `issue-telemetry-routes`,
`issue-thread-interaction-routes`, `issue-document-restore-routes`,
`heartbeat-referenced-projects`, `project-environments`: 14 files, 414
tests pass.
- `pnpm --filter @paperclipai/server typecheck` passes.
- Interactions: the polled route sends 10 statements instead of 11, with
a response equal to the service result without the known issue.
- Census: `PAPERCLIP_STATEMENT_CENSUS=/tmp/census.txt pnpm exec vitest
run src/__tests__/board-route-statement-census.test.ts` writes
statements per request and the top statement shapes for each board
route.
## Risks
- Low risk. The new arguments are optional, so other callers keep the
old reads.
- When the route passes a known `companyId`, a concurrent delete of the
issue no longer gives a 404 from these sub-reads. The route already
loaded and authorized the issue in the same request, so the response is
the same in practice.
- The JSON fixture file fails when someone changes the issue detail
response. Regenerate it with `PAPERCLIP_WRITE_ISSUE_DETAIL_GOLDEN=1` and
review the diff.
> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude
Code with tool use (shell, file edits, test runs).
## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f4f4902707
commit
30c4d2f4a1
13 files changed
+721
-72
No files matched your search
@@ -0,0 +1,29 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import request from "supertest";
|
||||
import { expect, it } from "vitest";
|
||||
import { boardCensusRoutes, boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js";
|
||||
|
||||
describeEmbeddedPostgres("board route statement census", () => {
|
||||
const ctx = useEmbeddedPostgres("board-route-census-");
|
||||
|
||||
it("answers every polled and page-load board route and reports statements per request", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seedBoardRouteFixture(ctx.db, "Census");
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const report: string[] = [];
|
||||
for (const [label, path] of boardCensusRoutes(fixture)) {
|
||||
const warm = await request(app).get(path);
|
||||
expect(warm.status, `${label}: ${JSON.stringify(warm.body)}`).toBe(200);
|
||||
const measured = await census.measure(() => request(app).get(path).expect(200), { stacks: true });
|
||||
expect(measured.statements, label).toBeGreaterThan(0);
|
||||
report.push(formatStatementCensus(label, measured, Number(process.env.PAPERCLIP_STATEMENT_CENSUS_TOP ?? 5)));
|
||||
}
|
||||
if (process.env.PAPERCLIP_STATEMENT_CENSUS) writeFileSync(process.env.PAPERCLIP_STATEMENT_CENSUS, `${report.join("\n\n")}\n`);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
{
|
||||
"id": "<id:0>",
|
||||
"companyId": "<id:1>",
|
||||
"conversationAgentId": null,
|
||||
"conversationUserId": null,
|
||||
"conversationState": null,
|
||||
"conversationSessionGeneration": 0,
|
||||
"conversationBoundaryCommentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"projectWorkspaceId": null,
|
||||
"goalId": null,
|
||||
"parentId": "<id:3>",
|
||||
"visibility": "open",
|
||||
"privacyRootIssueId": null,
|
||||
"privacyParentIssueId": null,
|
||||
"title": "Detail task",
|
||||
"titleNeedsGeneration": false,
|
||||
"description": "Uses [@Detail project](project://<id:2>)",
|
||||
"status": "in_progress",
|
||||
"statusVersion": 0,
|
||||
"lastStatusDecisionId": null,
|
||||
"workMode": "standard",
|
||||
"harnessKind": null,
|
||||
"priority": "high",
|
||||
"reviewPolicy": null,
|
||||
"assigneeAgentId": "<id:4>",
|
||||
"assigneeUserId": null,
|
||||
"checkoutRunId": null,
|
||||
"executionRunId": null,
|
||||
"executionAgentNameKey": null,
|
||||
"executionLockedAt": null,
|
||||
"createdByAgentId": null,
|
||||
"createdByUserId": "<user>",
|
||||
"responsibleUserId": null,
|
||||
"issueNumber": null,
|
||||
"identifier": null,
|
||||
"originKind": "manual",
|
||||
"originId": null,
|
||||
"originRunId": null,
|
||||
"originIssueId": null,
|
||||
"originIdentityContextId": null,
|
||||
"continuationIdentityContextId": null,
|
||||
"originFingerprint": "default",
|
||||
"requestDepth": 0,
|
||||
"billingCode": null,
|
||||
"assigneeAdapterOverrides": null,
|
||||
"executionPolicy": null,
|
||||
"executionState": null,
|
||||
"monitorNextCheckAt": null,
|
||||
"monitorWakeRequestedAt": null,
|
||||
"monitorLastTriggeredAt": null,
|
||||
"monitorAttemptCount": 0,
|
||||
"monitorNotes": null,
|
||||
"monitorScheduledBy": null,
|
||||
"executionWorkspaceId": null,
|
||||
"workspaceBindingRevision": 0,
|
||||
"workspaceSelection": null,
|
||||
"workspacePendingSelection": null,
|
||||
"executionWorkspacePreference": null,
|
||||
"executionWorkspaceSettings": null,
|
||||
"sourceTrust": null,
|
||||
"unblockDescriptor": null,
|
||||
"blockedTransitionAt": null,
|
||||
"blockedOwnerNotifiedAt": null,
|
||||
"startedAt": null,
|
||||
"completedAt": null,
|
||||
"cancelledAt": null,
|
||||
"hiddenAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>",
|
||||
"displayStatus": "todo",
|
||||
"externalConversationState": null,
|
||||
"labels": [],
|
||||
"labelIds": [],
|
||||
"watchdog": null,
|
||||
"ancestors": [
|
||||
{
|
||||
"id": "<id:3>",
|
||||
"identifier": null,
|
||||
"title": "Detail parent",
|
||||
"description": null,
|
||||
"status": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"projectId": null,
|
||||
"goalId": null,
|
||||
"project": null,
|
||||
"goal": null
|
||||
},
|
||||
{
|
||||
"id": "<id:6>",
|
||||
"identifier": null,
|
||||
"title": "Detail grandparent",
|
||||
"description": null,
|
||||
"status": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"goalId": null,
|
||||
"project": {
|
||||
"id": "<id:2>",
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"status": "backlog",
|
||||
"goalId": null,
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null
|
||||
},
|
||||
"goal": null
|
||||
}
|
||||
],
|
||||
"blockerAttention": {
|
||||
"state": "none",
|
||||
"reason": null,
|
||||
"unresolvedBlockerCount": 0,
|
||||
"coveredBlockerCount": 0,
|
||||
"stalledBlockerCount": 0,
|
||||
"attentionBlockerCount": 0,
|
||||
"pendingFinalizeBlockerIssueIds": [],
|
||||
"sampleBlockerIdentifier": null,
|
||||
"sampleStalledBlockerIdentifier": null,
|
||||
"blockingTreeLive": false,
|
||||
"directBlockerIssueId": null,
|
||||
"terminalBlockerIssueId": null,
|
||||
"terminalBlocker": null
|
||||
},
|
||||
"reviewAttention": {
|
||||
"state": "none",
|
||||
"paths": [],
|
||||
"reason": null
|
||||
},
|
||||
"successfulRunHandoff": null,
|
||||
"executionBlocker": null,
|
||||
"interruption": null,
|
||||
"scheduledRetry": null,
|
||||
"activeRecoveryAction": null,
|
||||
"stalledDependencies": [],
|
||||
"blockedBy": [
|
||||
{
|
||||
"id": "<id:7>",
|
||||
"identifier": null,
|
||||
"title": "Detail blocker",
|
||||
"status": "todo",
|
||||
"displayStatus": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"assigneeUserId": null,
|
||||
"scheduledRetry": null,
|
||||
"activeRecoveryAction": null
|
||||
}
|
||||
],
|
||||
"blocks": [],
|
||||
"relatedWork": {
|
||||
"outbound": [],
|
||||
"inbound": []
|
||||
},
|
||||
"referencedIssueIdentifiers": [],
|
||||
"planDocument": null,
|
||||
"documentSummaries": [],
|
||||
"legacyPlanDocument": null,
|
||||
"project": {
|
||||
"id": "<id:2>",
|
||||
"companyId": "<id:1>",
|
||||
"urlKey": "detail-project",
|
||||
"goalId": null,
|
||||
"goalIds": [],
|
||||
"goals": [],
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"visibility": "open",
|
||||
"personalOwnerUserId": null,
|
||||
"status": "backlog",
|
||||
"leadAgentId": null,
|
||||
"targetDate": null,
|
||||
"color": null,
|
||||
"icon": null,
|
||||
"env": null,
|
||||
"pauseReason": null,
|
||||
"pausedAt": null,
|
||||
"executionWorkspacePolicy": null,
|
||||
"codebase": {
|
||||
"workspaceId": null,
|
||||
"repoUrl": null,
|
||||
"repoRef": null,
|
||||
"defaultRef": null,
|
||||
"repoName": null,
|
||||
"localFolder": null,
|
||||
"managedFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"effectiveLocalFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"origin": "managed_checkout"
|
||||
},
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null,
|
||||
"managedByPlugin": null,
|
||||
"archivedAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>"
|
||||
},
|
||||
"goal": null,
|
||||
"mentionedProjects": [
|
||||
{
|
||||
"id": "<id:2>",
|
||||
"companyId": "<id:1>",
|
||||
"goalId": null,
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"visibility": "open",
|
||||
"privacyOwnerUserId": null,
|
||||
"personalOwnerUserId": null,
|
||||
"status": "backlog",
|
||||
"leadAgentId": null,
|
||||
"decisionOwnerUserId": null,
|
||||
"targetDate": null,
|
||||
"color": null,
|
||||
"icon": null,
|
||||
"env": null,
|
||||
"gitAuthorizationGrantId": null,
|
||||
"gitAuthorizedByUserId": null,
|
||||
"pauseReason": null,
|
||||
"pausedAt": null,
|
||||
"executionWorkspacePolicy": null,
|
||||
"archivedAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>",
|
||||
"urlKey": "detail-project",
|
||||
"goalIds": [],
|
||||
"goals": [],
|
||||
"codebase": {
|
||||
"workspaceId": null,
|
||||
"repoUrl": null,
|
||||
"repoRef": null,
|
||||
"defaultRef": null,
|
||||
"repoName": null,
|
||||
"localFolder": null,
|
||||
"managedFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"effectiveLocalFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"origin": "managed_checkout"
|
||||
},
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null,
|
||||
"managedByPlugin": null,
|
||||
"workspaceProvider": {
|
||||
"source": "core",
|
||||
"pluginId": null,
|
||||
"displayName": "Core / local",
|
||||
"providers": [],
|
||||
"effectivePolicy": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"currentExecutionWorkspace": null,
|
||||
"workProducts": [
|
||||
{
|
||||
"id": "<id:8>",
|
||||
"companyId": "<id:1>",
|
||||
"projectId": "<id:2>",
|
||||
"issueId": "<id:0>",
|
||||
"executionWorkspaceId": null,
|
||||
"runtimeServiceId": null,
|
||||
"type": "pull_request",
|
||||
"provider": "github",
|
||||
"externalId": null,
|
||||
"title": "Fixture PR",
|
||||
"url": "https://example.test/pr/1",
|
||||
"status": "open",
|
||||
"reviewState": "none",
|
||||
"isPrimary": false,
|
||||
"healthStatus": "unknown",
|
||||
"summary": null,
|
||||
"metadata": null,
|
||||
"sourceTrust": null,
|
||||
"createdByRunId": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>"
|
||||
}
|
||||
],
|
||||
"externalChannelBinding": null,
|
||||
"createdFrom": null
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import net from "node:net";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
|
||||
export type MeteredStatement = { sql: string; parameters: number; rows: number; ms: number; inTransaction: boolean };
|
||||
export type MeteredStatement = { sql: string; parameters: number; rows: number; ms: number; inTransaction: boolean; stack?: string };
|
||||
|
||||
type Method = (this: unknown, ...args: unknown[]) => unknown;
|
||||
|
||||
@@ -27,6 +27,7 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
const totals = { statements: 0, transactions: 0, waits: 0, rows: 0, sqlBytes: 0 };
|
||||
let inFlight = 0;
|
||||
let log: MeteredStatement[] | null = null;
|
||||
let captureStacks = false;
|
||||
const visited = new WeakSet<object>();
|
||||
const visit = (value: unknown, inTransaction: boolean) => {
|
||||
if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
|
||||
@@ -42,7 +43,13 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
if (inFlight === 0) totals.waits += 1;
|
||||
inFlight += 1;
|
||||
const pending = Reflect.apply(unsafe, this, args) as PromiseLike<{ length: number }>;
|
||||
const entry = { sql: query, parameters: Array.isArray(args[1]) ? args[1].length : 0, rows: 0, ms: 0, inTransaction };
|
||||
const entry: MeteredStatement = { sql: query, parameters: Array.isArray(args[1]) ? args[1].length : 0, rows: 0, ms: 0, inTransaction };
|
||||
if (log && captureStacks) {
|
||||
const limit = Error.stackTraceLimit;
|
||||
Error.stackTraceLimit = 60;
|
||||
entry.stack = new Error().stack;
|
||||
Error.stackTraceLimit = limit;
|
||||
}
|
||||
log?.push(entry);
|
||||
// The query starts one microtask after its first `then`, so a caller
|
||||
// can still select the result format on the returned query.
|
||||
@@ -79,7 +86,7 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
/** The totals since the client started. Subtract two readings to meter one request. */
|
||||
read: () => ({ ...totals, bytesReceived: bytesReceived() }),
|
||||
/** Records every statement until `stopLog`. */
|
||||
startLog: () => { log = []; },
|
||||
startLog: (options: { stacks?: boolean } = {}) => { log = []; captureStacks = options.stacks === true; },
|
||||
stopLog: () => {
|
||||
const recorded = log ?? [];
|
||||
log = null;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import express from "express";
|
||||
import { agents, authUsers, issueComments, issueWorkProducts, issues, projects, type Db } from "@paperclipai/db";
|
||||
import { actorMiddleware } from "../../middleware/auth.js";
|
||||
import { errorHandler } from "../../middleware/error-handler.js";
|
||||
import { activityRoutes } from "../../routes/activity.js";
|
||||
import { agentRoutes } from "../../routes/agents.js";
|
||||
import { companySkillRoutes } from "../../routes/company-skills.js";
|
||||
import { dashboardRoutes } from "../../routes/dashboard.js";
|
||||
import { issueRoutes } from "../../routes/issues.js";
|
||||
import { sidebarBadgeRoutes } from "../../routes/sidebar-badges.js";
|
||||
import { seedCompanyWithBoardAccess } from "./route-test-harness.js";
|
||||
|
||||
export function boardSessionApp(db: Db, sessionUserId: () => string | null) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(actorMiddleware(db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => {
|
||||
const userId = sessionUserId();
|
||||
return userId ? {
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Board user", email: `${userId}@example.test` },
|
||||
} : null;
|
||||
},
|
||||
}));
|
||||
app.use("/api", issueRoutes(db, {} as never));
|
||||
app.use("/api", agentRoutes(db));
|
||||
app.use("/api", activityRoutes(db));
|
||||
app.use("/api", companySkillRoutes(db));
|
||||
app.use("/api", sidebarBadgeRoutes(db));
|
||||
app.use("/api", dashboardRoutes(db));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function seedBoardRouteFixture(db: Db, name: string, commentCount = 3) {
|
||||
const company = await seedCompanyWithBoardAccess(db, name);
|
||||
const now = new Date("2026-11-01T00:00:00.000Z");
|
||||
await db.insert(authUsers).values({
|
||||
id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now,
|
||||
});
|
||||
const [agent] = await db.insert(agents).values({
|
||||
companyId: company.companyId, name: `${name} agent`, role: "engineer", adapterType: "process", status: "idle",
|
||||
}).returning();
|
||||
const [project] = await db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning();
|
||||
const [parent] = await db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} parent`, status: "todo", createdByUserId: company.userId,
|
||||
createdAt: now, updatedAt: now,
|
||||
}).returning();
|
||||
const [issue] = await db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} task`, description: "Fixture task", status: "in_progress",
|
||||
priority: "high", parentId: parent!.id, projectId: project!.id, assigneeAgentId: agent!.id,
|
||||
createdByUserId: company.userId, createdAt: now, updatedAt: now,
|
||||
}).returning();
|
||||
if (commentCount > 0) {
|
||||
await db.insert(issueComments).values(Array.from({ length: commentCount }, (_, index) => ({
|
||||
companyId: company.companyId, issueId: issue!.id, authorUserId: company.userId, authorType: "user" as const,
|
||||
body: `Comment ${index}`, createdAt: new Date(now.getTime() + (index + 1) * 1000), updatedAt: now,
|
||||
})));
|
||||
}
|
||||
await db.insert(issueWorkProducts).values({
|
||||
companyId: company.companyId, projectId: project!.id, issueId: issue!.id, type: "pull_request", provider: "github",
|
||||
title: "Fixture PR", url: "https://example.test/pr/1", status: "open", createdAt: now, updatedAt: now,
|
||||
});
|
||||
return { ...company, agent: agent!, project: project!, parent: parent!, issue: issue! };
|
||||
}
|
||||
|
||||
export type BoardRouteFixture = Awaited<ReturnType<typeof seedBoardRouteFixture>>;
|
||||
|
||||
export function boardCensusRoutes(fixture: BoardRouteFixture) {
|
||||
const { companyId, issue, parent } = fixture;
|
||||
return [
|
||||
["GET /api/issues/:id", `/api/issues/${issue.id}`],
|
||||
["GET /api/issues/:id/comments", `/api/issues/${issue.id}/comments`],
|
||||
["GET /api/issues/:id/activity", `/api/issues/${issue.id}/activity`],
|
||||
["GET /api/issues/:id/interactions", `/api/issues/${issue.id}/interactions`],
|
||||
["GET /api/issues/:id/work-products", `/api/issues/${issue.id}/work-products`],
|
||||
["GET /api/companies/:id/issues", `/api/companies/${companyId}/issues`],
|
||||
["GET /api/companies/:id/issues/summaries?ids", `/api/companies/${companyId}/issues/summaries?ids=${issue.id},${parent.id}`],
|
||||
["GET /api/companies/:id/live-runs", `/api/companies/${companyId}/live-runs`],
|
||||
["GET /api/companies/:id/skills", `/api/companies/${companyId}/skills`],
|
||||
["GET /api/companies/:id/sidebar-badges", `/api/companies/${companyId}/sidebar-badges`],
|
||||
["GET /api/companies/:id/dashboard", `/api/companies/${companyId}/dashboard`],
|
||||
["GET /api/companies/:id/agents", `/api/companies/${companyId}/agents`],
|
||||
["GET /api/companies/:id/chats", `/api/companies/${companyId}/chats`],
|
||||
] as const;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { meterDatabaseStatements, type MeteredStatement } from "./database-statement-meter.js";
|
||||
|
||||
export type StatementShape = { shape: string; count: number; callers: string[] };
|
||||
export type RequestCensus = { statements: number; transactions: number; shapes: StatementShape[]; log: MeteredStatement[] };
|
||||
|
||||
export function normalizeStatementShape(sql: string) {
|
||||
return sql
|
||||
.replace(/\s+/g, " ")
|
||||
.replace(/\$\d+(?:\s*,\s*\$\d+)*/g, "$n")
|
||||
.replace(/\(\s*\$n\s*\)(?:\s*,\s*\(\s*\$n\s*\))+/g, "($n)")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function statementCaller(stack: string | undefined, depth = 3) {
|
||||
if (!stack) return "unknown";
|
||||
const frames = stack.split("\n").slice(1).map((line) => line.trim())
|
||||
.filter((line) => line.includes("/server/src/") && !line.includes("/__tests__/"))
|
||||
.slice(0, depth)
|
||||
.map((line) => {
|
||||
const match = /at (?:async )?(?:(\S+) )?\(?.*\/server\/src\/([^:)]+):(\d+)/.exec(line);
|
||||
return match ? `${match[2]}:${match[3]}${match[1] ? ` ${match[1]}` : ""}` : line;
|
||||
});
|
||||
return frames.length > 0 ? frames.join(" < ") : "unknown";
|
||||
}
|
||||
|
||||
export function groupStatementShapes(log: MeteredStatement[]): StatementShape[] {
|
||||
const byShape = new Map<string, StatementShape>();
|
||||
for (const entry of log) {
|
||||
const shape = normalizeStatementShape(entry.sql);
|
||||
const group = byShape.get(shape) ?? { shape, count: 0, callers: [] };
|
||||
group.count += 1;
|
||||
const caller = statementCaller(entry.stack);
|
||||
if (!group.callers.includes(caller)) group.callers.push(caller);
|
||||
byShape.set(shape, group);
|
||||
}
|
||||
return [...byShape.values()].sort((left, right) => right.count - left.count);
|
||||
}
|
||||
|
||||
export function createStatementCensus(db: Db) {
|
||||
const { host, port } = (db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
const meter = meterDatabaseStatements(db, `postgres://${host[0]}:${port[0]}/census`);
|
||||
return {
|
||||
async measure(run: () => Promise<unknown>, options: { stacks?: boolean } = {}): Promise<RequestCensus> {
|
||||
const before = meter.read();
|
||||
meter.startLog(options);
|
||||
let log: MeteredStatement[];
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
log = meter.stopLog();
|
||||
}
|
||||
const after = meter.read();
|
||||
return {
|
||||
statements: after.statements - before.statements,
|
||||
transactions: after.transactions - before.transactions,
|
||||
shapes: groupStatementShapes(log),
|
||||
log,
|
||||
};
|
||||
},
|
||||
uninstall: () => meter.uninstall(),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStatementCensus(label: string, census: RequestCensus, top = 5) {
|
||||
const lines = [`${label}: ${census.statements} statements, ${census.transactions} transactions`];
|
||||
for (const shape of census.shapes.slice(0, top)) {
|
||||
lines.push(` ${String(shape.count).padStart(3)}x ${shape.shape.slice(0, 160)}`);
|
||||
for (const caller of shape.callers.slice(0, 3)) lines.push(` ${caller}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { expect, it } from "vitest";
|
||||
import { authUsers, companies, companyMemberships, issueRelations, issues } from "@paperclipai/db";
|
||||
import { boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
|
||||
const GOLDEN = new URL("./fixtures/issue-detail-response.json", import.meta.url);
|
||||
|
||||
function normalizeResponse(body: unknown, issuePrefix: string) {
|
||||
const ids = new Map<string, string>();
|
||||
const text = JSON.stringify(body, null, 2)
|
||||
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, (id) => {
|
||||
if (!ids.has(id)) ids.set(id, `<id:${ids.size}>`);
|
||||
return ids.get(id)!;
|
||||
})
|
||||
.replace(/"[^"]*\/instances\/[^/"]+\//g, "\"<home>/")
|
||||
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g, "<time>")
|
||||
.replaceAll(issuePrefix, "<prefix>")
|
||||
.replace(/user-<id:\d+>/g, "<user>");
|
||||
return `${text}\n`;
|
||||
}
|
||||
|
||||
describeEmbeddedPostgres("GET /api/issues/:id statements per request", () => {
|
||||
const ctx = useEmbeddedPostgres("issue-detail-statements-");
|
||||
|
||||
async function seed() {
|
||||
const fixture = await seedBoardRouteFixture(ctx.db, "Detail");
|
||||
const [grandparent] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Detail grandparent", status: "todo", projectId: fixture.project.id,
|
||||
createdByUserId: fixture.userId, createdAt: new Date("2026-10-30T00:00:00.000Z"), updatedAt: new Date("2026-10-30T00:00:00.000Z"),
|
||||
}).returning();
|
||||
await ctx.db.update(issues).set({ parentId: grandparent!.id }).where(eq(issues.id, fixture.parent.id));
|
||||
const [blocker] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Detail blocker", status: "todo", createdByUserId: fixture.userId,
|
||||
createdAt: new Date("2026-10-31T00:00:00.000Z"), updatedAt: new Date("2026-10-31T00:00:00.000Z"),
|
||||
}).returning();
|
||||
await ctx.db.insert(issueRelations).values({
|
||||
companyId: fixture.companyId, issueId: blocker!.id, relatedIssueId: fixture.issue.id, type: "blocks",
|
||||
});
|
||||
await ctx.db.update(issues).set({ description: `Uses [@Detail project](project://${fixture.project.id})` })
|
||||
.where(eq(issues.id, fixture.issue.id));
|
||||
const [company] = await ctx.db.select({ issuePrefix: companies.issuePrefix }).from(companies)
|
||||
.where(eq(companies.id, fixture.companyId));
|
||||
return { ...fixture, grandparent: grandparent!, blocker: blocker!, issuePrefix: company!.issuePrefix };
|
||||
}
|
||||
|
||||
it("answers the issue detail with the same JSON in fewer statements", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const path = `/api/issues/${fixture.issue.id}`;
|
||||
await request(app).get(path).expect(200);
|
||||
let response: request.Response | undefined;
|
||||
const measured = await census.measure(async () => {
|
||||
response = await request(app).get(path).expect(200);
|
||||
}, { stacks: true });
|
||||
|
||||
const normalized = normalizeResponse(response!.body, fixture.issuePrefix);
|
||||
if (process.env.PAPERCLIP_WRITE_ISSUE_DETAIL_GOLDEN) writeFileSync(GOLDEN, normalized);
|
||||
expect(normalized).toBe(readFileSync(GOLDEN, "utf8"));
|
||||
expect(response!.body.ancestors.map((ancestor: { id: string }) => ancestor.id))
|
||||
.toEqual([fixture.parent.id, fixture.grandparent.id]);
|
||||
expect(response!.body.blockedBy.map((relation: { id: string }) => relation.id)).toEqual([fixture.blocker.id]);
|
||||
expect(response!.body.mentionedProjects.map((project: { id: string }) => project.id)).toEqual([fixture.project.id]);
|
||||
expect(measured.statements, formatStatementCensus(path, measured, 80)).toBeLessThanOrEqual(64);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("keeps the access rules: another company's user, a missing issue and a hidden issue", async () => {
|
||||
const fixture = await seed();
|
||||
const outsider = await seedBoardRouteFixture(ctx.db, "Outsider");
|
||||
const [hidden] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Hidden", status: "todo", hiddenAt: new Date(),
|
||||
}).returning();
|
||||
const memberApp = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const outsiderApp = boardSessionApp(ctx.db, () => outsider.userId);
|
||||
const anonymousApp = boardSessionApp(ctx.db, () => null);
|
||||
|
||||
const statuses = {
|
||||
outsiderReadsMemberIssue: (await request(outsiderApp).get(`/api/issues/${fixture.issue.id}`)).status,
|
||||
memberReadsOtherCompanyIssue: (await request(memberApp).get(`/api/issues/${outsider.issue.id}`)).status,
|
||||
memberReadsMissingIssue: (await request(memberApp).get(`/api/issues/${randomUUID()}`)).status,
|
||||
anonymousReadsMemberIssue: (await request(anonymousApp).get(`/api/issues/${fixture.issue.id}`)).status,
|
||||
};
|
||||
expect(statuses).toEqual({
|
||||
outsiderReadsMemberIssue: 404,
|
||||
memberReadsOtherCompanyIssue: 404,
|
||||
memberReadsMissingIssue: 404,
|
||||
anonymousReadsMemberIssue: 404,
|
||||
});
|
||||
const hiddenResponse = await request(memberApp).get(`/api/issues/${hidden!.id}`);
|
||||
expect(hiddenResponse.status).toBe(200);
|
||||
expect(hiddenResponse.body.hiddenAt).not.toBeNull();
|
||||
}, 60_000);
|
||||
|
||||
it("denies the very next request after the membership is removed", async () => {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
await ctx.db.delete(authUsers).where(eq(authUsers.id, fixture.userId));
|
||||
}, 60_000);
|
||||
it("walks the ancestor chain nearest first, stops at a cycle and ignores a task that is its own parent", async () => {
|
||||
const fixture = await seed();
|
||||
const svc = issueService(ctx.db);
|
||||
await ctx.db.update(issues).set({ parentId: fixture.parent.id }).where(eq(issues.id, fixture.grandparent.id));
|
||||
const expected = [fixture.parent.id, fixture.grandparent.id];
|
||||
expect((await svc.getAncestors(fixture.issue.id)).map((ancestor) => ancestor.id)).toEqual(expected);
|
||||
expect((await svc.getAncestors(fixture.issue.id, { parentId: fixture.parent.id })).map((ancestor) => ancestor.id)).toEqual(expected);
|
||||
await ctx.db.update(issues).set({ parentId: fixture.blocker.id }).where(eq(issues.id, fixture.blocker.id));
|
||||
expect(await svc.getAncestors(fixture.blocker.id)).toEqual([]);
|
||||
}, 60_000);
|
||||
it("answers the interactions poll without reading the issue again", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const path = `/api/issues/${fixture.issue.id}/interactions`;
|
||||
await request(app).get(path).expect(200);
|
||||
let response: request.Response | undefined;
|
||||
const measured = await census.measure(async () => {
|
||||
response = await request(app).get(path).expect(200);
|
||||
});
|
||||
const expected = await issueThreadInteractionService(ctx.db).listForIssue(fixture.issue.id);
|
||||
expect(response!.body).toEqual(JSON.parse(JSON.stringify(expected)));
|
||||
expect(measured.shapes.filter((shape) => shape.shape.startsWith('select "status", "company_id", "execution_workspace_id" from "issues"'))).toEqual([]);
|
||||
expect(measured.statements, formatStatementCensus(path, measured, 20)).toBeLessThanOrEqual(10);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -872,7 +872,7 @@ describe("issue thread interaction routes", () => {
|
||||
.get("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/interactions")
|
||||
.expect(200, []);
|
||||
|
||||
expect(mockInteractionService.listForIssue).toHaveBeenCalledExactlyOnceWith(ISSUE_ID);
|
||||
expect(mockInteractionService.listForIssue).toHaveBeenCalledExactlyOnceWith(ISSUE_ID, expect.objectContaining({ id: ISSUE_ID, status }));
|
||||
expect(mockInteractionService.expireRequestConfirmationsSupersededByHistoricalComments).not.toHaveBeenCalled();
|
||||
expect(mockInteractionService.expirePendingInteractionsForTerminalIssue).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
|
||||
@@ -312,7 +312,7 @@ describe("issue goal context routes", () => {
|
||||
);
|
||||
expect(mockIssueService.findMentionedProjectIds).toHaveBeenCalledWith(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
{ includeCommentBodies: false },
|
||||
{ includeCommentBodies: false, issue: expect.objectContaining({ id: "11111111-1111-4111-8111-111111111111" }) },
|
||||
);
|
||||
expect(mockGoalService.getDefaultCompanyGoal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -8478,9 +8478,9 @@ export function issueRoutes(
|
||||
companyId: string;
|
||||
projectId: string | null;
|
||||
goalId: string | null;
|
||||
}) {
|
||||
}, options: { workspaceProvider?: boolean } = {}) {
|
||||
const projectPromise = issue.projectId
|
||||
? projectsSvc.getById(issue.projectId)
|
||||
? projectsSvc.getById(issue.projectId, options)
|
||||
: Promise.resolve(null);
|
||||
const directGoalPromise = issue.goalId
|
||||
? goalsSvc.getById(issue.goalId)
|
||||
@@ -10157,20 +10157,20 @@ export function issueRoutes(
|
||||
workProducts,
|
||||
createdFrom,
|
||||
] = await Promise.all([
|
||||
timing.time("project_goal", () => resolveIssueProjectAndGoal(issue)),
|
||||
timing.time("ancestors", () => svc.getAncestors(issue.id)),
|
||||
timing.time("mentions", () => svc.findMentionedProjectIds(issue.id, { includeCommentBodies: false })),
|
||||
timing.time("project_goal", () => resolveIssueProjectAndGoal(issue, { workspaceProvider: false })),
|
||||
timing.time("ancestors", () => svc.getAncestors(issue.id, { parentId: issue.parentId })),
|
||||
timing.time("mentions", () => svc.findMentionedProjectIds(issue.id, { includeCommentBodies: false, issue })),
|
||||
timing.time("documents", () => documentsSvc.getIssueDocumentPayload(issue)),
|
||||
timing.time("relations", () => svc.getRelationSummaries(issue.id)),
|
||||
timing.time("relations", () => svc.getRelationSummaries(issue.id, { companyId: issue.companyId })),
|
||||
timing.time("blockers", () => svc
|
||||
.listBlockerAttention(issue.companyId, [issue])
|
||||
.then((map) => map.get(issue.id) ?? null)),
|
||||
timing.time("review", () => svc
|
||||
.listReviewAttention(issue.companyId, [issue])
|
||||
.then((map) => map.get(issue.id) ?? null)),
|
||||
timing.time("references", () => issueReferencesSvc.listIssueReferenceSummary(issue.id)),
|
||||
timing.time("references", () => issueReferencesSvc.listIssueReferenceSummary(issue.id, undefined, { companyId: issue.companyId })),
|
||||
timing.time("handoff", () => listSuccessfulRunHandoffStates(db, issue.companyId, [issue.id])),
|
||||
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id)),
|
||||
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id, { companyId: issue.companyId })),
|
||||
timing.time("recovery", () => recoveryActionsSvc.getActiveForIssue(issue.companyId, issue.id)),
|
||||
inboxArchiveFieldsPromise,
|
||||
timing.time("channel", () => getExternalChannelBindingSummary(db, issue.companyId, issue.id)),
|
||||
@@ -18402,7 +18402,7 @@ export function issueRoutes(
|
||||
if (!issue) return;
|
||||
if (!(await assertIssueReadAllowed(req, res, issue))) return;
|
||||
const interactions =
|
||||
await issueThreadInteractionService(db).listForIssue(id);
|
||||
await issueThreadInteractionService(db).listForIssue(issue.id, issue);
|
||||
if (req.actor.type === "agent" && req.actor.agentId && req.actor.runId) {
|
||||
await recordDeclinedInteractionRead(db, { companyId: issue.companyId, agentId: req.actor.agentId, runId: req.actor.runId,
|
||||
issue, interactions: interactions as Parameters<typeof recordDeclinedInteractionRead>[1]["interactions"] })
|
||||
|
||||
@@ -343,8 +343,12 @@ export function issueReferenceService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
async function listIssueReferenceSummary(issueId: string, dbOrTx: any = db): Promise<IssueRelatedWorkSummary> {
|
||||
const issue = await issueById(issueId, dbOrTx);
|
||||
async function listIssueReferenceSummary(
|
||||
issueId: string,
|
||||
dbOrTx: any = db,
|
||||
known?: { companyId: string },
|
||||
): Promise<IssueRelatedWorkSummary> {
|
||||
const issue = known ? { id: issueId, companyId: known.companyId } : await issueById(issueId, dbOrTx);
|
||||
if (!issue) throw notFound("Issue not found");
|
||||
|
||||
const [outboundRows, inboundRows] = await Promise.all([
|
||||
|
||||
@@ -3429,7 +3429,10 @@ export function issueThreadInteractionService(
|
||||
woken,
|
||||
};
|
||||
},
|
||||
listForIssue: async (issueId: string) => {
|
||||
listForIssue: async (
|
||||
issueId: string,
|
||||
known?: { status: string; companyId: string; executionWorkspaceId: string | null },
|
||||
) => {
|
||||
const [rows, issue] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
@@ -3439,7 +3442,7 @@ export function issueThreadInteractionService(
|
||||
asc(issueThreadInteractions.createdAt),
|
||||
asc(issueThreadInteractions.id),
|
||||
),
|
||||
db
|
||||
known ? { status: known.status, companyId: known.companyId, executionWorkspaceId: known.executionWorkspaceId } : db
|
||||
.select({
|
||||
status: issues.status,
|
||||
companyId: issues.companyId,
|
||||
|
||||
@@ -9124,10 +9124,9 @@ export function issueService(db: Db) {
|
||||
issue: Pick<IssueRow, "id" | "companyId" | "updatedAt">,
|
||||
userId: string,
|
||||
) => {
|
||||
const [[activity], [archive]] = await Promise.all([
|
||||
lastActivityStatsForIssues(db, issue.companyId, [issue.id]),
|
||||
inboxArchiveRowsForIssues(db, issue.companyId, userId, [issue.id]),
|
||||
]);
|
||||
const [archive] = await inboxArchiveRowsForIssues(db, issue.companyId, userId, [issue.id]);
|
||||
if (!archive) return activeInboxArchiveFields(archive, issue.updatedAt);
|
||||
const [activity] = await lastActivityStatsForIssues(db, issue.companyId, [issue.id]);
|
||||
const lastActivityAt =
|
||||
latestIssueActivityAt(
|
||||
issue.updatedAt,
|
||||
@@ -9215,8 +9214,8 @@ export function issueService(db: Db) {
|
||||
return getIssueByIdentifier(identifier);
|
||||
},
|
||||
|
||||
getCurrentScheduledRetry: async (issueId: string) => {
|
||||
const issue = await db
|
||||
getCurrentScheduledRetry: async (issueId: string, known?: { companyId: string }) => {
|
||||
const issue = known ? { id: issueId, companyId: known.companyId } : await db
|
||||
.select({ id: issues.id, companyId: issues.companyId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
@@ -9225,8 +9224,8 @@ export function issueService(db: Db) {
|
||||
return getCurrentScheduledRetryForIssue(issue.id, issue.companyId);
|
||||
},
|
||||
|
||||
getRelationSummaries: async (issueId: string) => {
|
||||
const issue = await db
|
||||
getRelationSummaries: async (issueId: string, known?: { companyId: string }) => {
|
||||
const issue = known ? { id: issueId, companyId: known.companyId } : await db
|
||||
.select({ id: issues.id, companyId: issues.companyId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
@@ -14633,9 +14632,12 @@ export function issueService(db: Db) {
|
||||
|
||||
findMentionedProjectIds: async (
|
||||
issueId: string,
|
||||
opts?: { includeCommentBodies?: boolean },
|
||||
opts?: {
|
||||
includeCommentBodies?: boolean;
|
||||
issue?: { companyId: string; title: string; description: string | null };
|
||||
},
|
||||
) => {
|
||||
const issue = await db
|
||||
const issue = opts?.issue ?? await db
|
||||
.select({
|
||||
companyId: issues.companyId,
|
||||
title: issues.title,
|
||||
@@ -14686,7 +14688,7 @@ export function issueService(db: Db) {
|
||||
return [...mentionedIds].filter((projectId) => valid.has(projectId));
|
||||
},
|
||||
|
||||
getAncestors: async (issueId: string) => {
|
||||
getAncestors: async (issueId: string, known?: { parentId: string | null }) => {
|
||||
const raw: Array<{
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
@@ -14698,44 +14700,56 @@ export function issueService(db: Db) {
|
||||
projectId: string | null;
|
||||
goalId: string | null;
|
||||
}> = [];
|
||||
const visited = new Set<string>([issueId]);
|
||||
const start = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
.then((r) => r[0] ?? null);
|
||||
let currentId = start?.parentId ?? null;
|
||||
while (currentId && !visited.has(currentId) && raw.length < 50) {
|
||||
visited.add(currentId);
|
||||
const parent = await db
|
||||
.select({
|
||||
id: issues.id,
|
||||
identifier: issues.identifier,
|
||||
title: issues.title,
|
||||
description: issues.description,
|
||||
status: issues.status,
|
||||
priority: issues.priority,
|
||||
assigneeAgentId: issues.assigneeAgentId,
|
||||
projectId: issues.projectId,
|
||||
goalId: issues.goalId,
|
||||
parentId: issues.parentId,
|
||||
})
|
||||
const firstParentId = known
|
||||
? known.parentId
|
||||
: await db
|
||||
.select({ parentId: issues.parentId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, currentId))
|
||||
.then((r) => r[0] ?? null);
|
||||
if (!parent) break;
|
||||
raw.push({
|
||||
id: parent.id,
|
||||
identifier: parent.identifier ?? null,
|
||||
title: parent.title,
|
||||
description: parent.description ?? null,
|
||||
status: parent.status,
|
||||
priority: parent.priority,
|
||||
assigneeAgentId: parent.assigneeAgentId ?? null,
|
||||
projectId: parent.projectId ?? null,
|
||||
goalId: parent.goalId ?? null,
|
||||
});
|
||||
currentId = parent.parentId ?? null;
|
||||
.where(eq(issues.id, issueId))
|
||||
.then((r) => r[0]?.parentId ?? null);
|
||||
if (firstParentId && firstParentId !== issueId) {
|
||||
const chain = await db.execute<{
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
description: string | null;
|
||||
status: string;
|
||||
priority: string;
|
||||
assignee_agent_id: string | null;
|
||||
project_id: string | null;
|
||||
goal_id: string | null;
|
||||
}>(sql`
|
||||
with recursive chain as (
|
||||
select i.id, i.identifier, i.title, i.description, i.status, i.priority,
|
||||
i.assignee_agent_id, i.project_id, i.goal_id, i.parent_id,
|
||||
1 as depth, array[${issueId}::uuid, i.id] as path
|
||||
from ${issues} i
|
||||
where i.id = ${firstParentId}::uuid
|
||||
union all
|
||||
select p.id, p.identifier, p.title, p.description, p.status, p.priority,
|
||||
p.assignee_agent_id, p.project_id, p.goal_id, p.parent_id,
|
||||
chain.depth + 1, chain.path || p.id
|
||||
from chain
|
||||
join ${issues} p on p.id = chain.parent_id
|
||||
where chain.depth < 50 and not (p.id = any(chain.path))
|
||||
)
|
||||
select id, identifier, title, description, status, priority, assignee_agent_id, project_id, goal_id
|
||||
from chain
|
||||
order by depth
|
||||
`);
|
||||
for (const parent of chain) {
|
||||
raw.push({
|
||||
id: parent.id,
|
||||
identifier: parent.identifier ?? null,
|
||||
title: parent.title,
|
||||
description: parent.description ?? null,
|
||||
status: parent.status,
|
||||
priority: parent.priority,
|
||||
assigneeAgentId: parent.assignee_agent_id ?? null,
|
||||
projectId: parent.project_id ?? null,
|
||||
goalId: parent.goal_id ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Batch-fetch referenced projects and goals
|
||||
|
||||
@@ -326,10 +326,16 @@ function pickPrimaryWorkspace(
|
||||
}
|
||||
|
||||
/** Batch-load workspace refs for a set of projects. */
|
||||
async function attachWorkspaces(db: Db, rows: ProjectWithGoals[]): Promise<ProjectWithGoals[]> {
|
||||
async function attachWorkspaces(
|
||||
db: Db,
|
||||
rows: ProjectWithGoals[],
|
||||
options: { workspaceProvider?: boolean } = {},
|
||||
): Promise<ProjectWithGoals[]> {
|
||||
if (rows.length === 0) return [];
|
||||
|
||||
const providerCatalog = await listProjectWorkspaceProviders(db, rows[0]!.companyId);
|
||||
const providerCatalog = options.workspaceProvider === false
|
||||
? null
|
||||
: await listProjectWorkspaceProviders(db, rows[0]!.companyId);
|
||||
const projectIds = rows.map((r) => r.id);
|
||||
const workspaceRows = await db
|
||||
.select()
|
||||
@@ -412,8 +418,10 @@ async function attachWorkspaces(db: Db, rows: ProjectWithGoals[]): Promise<Proje
|
||||
workspaces,
|
||||
primaryWorkspace,
|
||||
managedByPlugin: managedByProjectId.get(row.id) ?? null,
|
||||
workspaceProvider: resolveProjectWorkspaceProvider(row.executionWorkspacePolicy, providerCatalog,
|
||||
workspaces.some(workspace => Boolean(workspace.repoUrl))),
|
||||
...(providerCatalog ? {
|
||||
workspaceProvider: resolveProjectWorkspaceProvider(row.executionWorkspacePolicy, providerCatalog,
|
||||
workspaces.some(workspace => Boolean(workspace.repoUrl))),
|
||||
} : {}),
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -708,7 +716,10 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
|
||||
});
|
||||
};
|
||||
|
||||
const getProjectById = async (id: string): Promise<ProjectWithGoals | null> => {
|
||||
const getProjectById = async (
|
||||
id: string,
|
||||
options: { workspaceProvider?: boolean } = {},
|
||||
): Promise<ProjectWithGoals | null> => {
|
||||
const row = await db
|
||||
.select()
|
||||
.from(projects)
|
||||
@@ -717,7 +728,7 @@ export function projectService(db: Db, options: { captureWorkspaceUpdates?: bool
|
||||
if (!row) return null;
|
||||
const [withGoals] = await attachGoals(db, [row]);
|
||||
if (!withGoals) return null;
|
||||
const [enriched] = await attachWorkspaces(db, [withGoals]);
|
||||
const [enriched] = await attachWorkspaces(db, [withGoals], options);
|
||||
return enriched ?? null;
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user