Merge current master into external agent sleep recovery

This commit is contained in:
Dotta committed 2026-11-14 23:58:18 -06:00
commit e5604f3e4d
88 files changed
+3360 -350

No files matched your search

@@ -0,0 +1,290 @@
import express from "express";
import request from "supertest";
import { eq } from "drizzle-orm";
import { afterEach, describe, expect, it, vi } from "vitest";
import { and, eq as equals } from "drizzle-orm";
import { authUsers, companyMemberships, instanceUserRoles, issues, projects } from "@paperclipai/db";
import { actorMiddleware } from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { issueRoutes } from "../routes/issues.js";
import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerRequest } from "../services/authorization-read-scope.js";
import { readInstanceAdmin } from "../services/authorization.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("authorization reads per request", () => {
const ctx = useEmbeddedPostgres("authorization-request-reads-");
function appFor(userId: string) {
const app = express();
app.use(express.json());
app.use(actorMiddleware(ctx.db, {
deploymentMode: "authenticated",
resolveSession: async () => ({
session: { id: `session-${userId}`, userId },
user: { id: userId, name: "Reader", email: `${userId}@example.test` },
}),
}));
app.use(authorizationReadScope);
app.use("/api", issueRoutes(ctx.db, {} as never));
app.use(errorHandler);
return app;
}
async function seed(name: string) {
const company = await seedCompanyWithBoardAccess(ctx.db, name);
const now = new Date();
await ctx.db.insert(authUsers).values({
id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now,
});
const [project] = await ctx.db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning();
const [issue] = await ctx.db.insert(issues).values({
companyId: company.companyId, title: `${name} task`, status: "todo", projectId: project!.id, createdByUserId: company.userId,
}).returning();
return { ...company, issue: issue! };
}
it("reads the instance role once per request and the membership once for the authorization of one issue read", async () => {
const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
const meter = meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/authorization`);
try {
const fixture = await seed("Reads");
const app = appFor(fixture.userId);
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
meter.startLog();
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
const log = meter.stopLog();
const roleReads = log.filter((entry) => /from "instance_user_roles"/.test(entry.sql));
const membershipReads = log.filter((entry) => /from "company_memberships"/.test(entry.sql));
expect(roleReads).toHaveLength(1);
expect(membershipReads).toHaveLength(2);
meter.startLog();
await request(app).get(`/api/companies/${fixture.companyId}/issues`).expect(200);
await request(app).get(`/api/companies/${fixture.companyId}/issues/summaries?ids=${fixture.issue.id}`).expect(200);
const listLog = meter.stopLog();
expect(listLog.filter((entry) => /from "instance_user_roles"/.test(entry.sql))).toHaveLength(2);
} finally {
meter.uninstall();
}
}, 60_000);
it("denies the very next request after the membership is removed", async () => {
const fixture = await seed("Revoked");
const app = appFor(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);
}, 60_000);
function membershipRead(companyId: string, userId: string) {
return readOncePerRequest(`membership:${companyId}:user:${userId}`, () => ctx.db.select({ id: companyMemberships.id })
.from(companyMemberships)
.where(and(equals(companyMemberships.companyId, companyId), equals(companyMemberships.principalId, userId),
equals(companyMemberships.status, "active")))
.then((rows) => rows.length > 0));
}
function streamApp(userId: string, companyId: string, events: { afterRevoke: Promise<void>; late: (allowed: boolean) => void }) {
const app = express();
app.use(actorMiddleware(ctx.db, {
deploymentMode: "authenticated",
resolveSession: async () => ({
session: { id: `session-${userId}`, userId },
user: { id: userId, name: "Reader", email: `${userId}@example.test` },
}),
}));
app.use(authorizationReadScope);
app.get("/stream", async (_req, res) => {
const atConnect = await membershipRead(companyId, userId);
res.writeHead(200, { "Content-Type": "text/event-stream" });
res.flushHeaders();
res.write(`data: ${atConnect}\n\n`);
await events.afterRevoke;
res.end(`data: ${await membershipRead(companyId, userId)}\n\n`);
});
app.get("/later", async (_req, res) => {
await membershipRead(companyId, userId);
setTimeout(() => { void events.afterRevoke.then(() => membershipRead(companyId, userId)).then(events.late); }, 0);
res.json({ ok: true });
});
return app;
}
it("re-reads the membership during a stream after it is removed", async () => {
const fixture = await seed("Stream");
let revoked!: () => void;
const afterRevoke = new Promise<void>((resolve) => { revoked = resolve; });
const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late: () => {} });
const pending = request(app).get("/stream").buffer(true).parse((res, done) => {
let text = "";
res.on("data", (chunk: Buffer) => {
text += chunk.toString();
if (text.includes("data: true") && !text.includes("data: false")) {
void ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)).then(revoked);
}
});
res.on("end", () => done(null, text));
});
const response = await pending;
expect(response.body).toBe("data: true\n\ndata: false\n\n");
}, 60_000);
it("re-reads in a callback that runs after the response and after a revoke", async () => {
const fixture = await seed("Later");
let revoked!: () => void;
const afterRevoke = new Promise<void>((resolve) => { revoked = resolve; });
let late!: (allowed: boolean) => void;
const lateResult = new Promise<boolean>((resolve) => { late = resolve; });
const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late });
await request(app).get("/later").expect(200);
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
revoked();
expect(await lateResult).toBe(false);
}, 60_000);
it("seeds the instance role from a session read that matches the authorization predicate", async () => {
const now = new Date();
const cases = [
{ userId: `user-admin-${Date.now()}`, roles: ["instance_admin"], expected: true },
{ userId: `user-other-${Date.now()}`, roles: ["instance_viewer"], expected: false },
{ userId: `user-none-${Date.now()}`, roles: [], expected: false },
];
for (const entry of cases) {
await ctx.db.insert(authUsers).values({ id: entry.userId, name: entry.userId, email: `${entry.userId}@example.test`,
emailVerified: true, createdAt: now, updatedAt: now });
if (entry.roles.length) await ctx.db.insert(instanceUserRoles).values(entry.roles.map((role) => ({ userId: entry.userId, role })));
const app = express();
app.use(actorMiddleware(ctx.db, {
deploymentMode: "authenticated",
resolveSession: async () => ({ session: { id: `session-${entry.userId}`, userId: entry.userId },
user: { id: entry.userId, name: "Admin check", email: `${entry.userId}@example.test` } }),
}));
app.get("/actor", (req, res) => { res.json({ isInstanceAdmin: req.actor.isInstanceAdmin }); });
const seeded = (await request(app).get("/actor").expect(200)).body.isInstanceAdmin;
expect({ seeded, read: await readInstanceAdmin(ctx.db, entry.userId) }).toEqual({ seeded: entry.expected, read: entry.expected });
}
await ctx.db.delete(instanceUserRoles);
}, 60_000);
it("treats HEAD like GET for an authorized read and denies it after a revoke", async () => {
const fixture = await seed("Head");
const app = appFor(fixture.userId);
await request(app).head(`/api/issues/${fixture.issue.id}`).expect(200);
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
await request(app).head(`/api/issues/${fixture.issue.id}`).expect(404);
}, 60_000);
});
describe("authorization read scope boundaries", () => {
afterEach(() => { vi.useRealTimers(); });
function countingApp(actor: Express.Request["actor"] = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }) {
let reads = 0;
const gates: Array<() => void> = [];
const app = express();
app.use((req, _res, next) => {
req.actor = actor;
next();
});
app.use(authorizationReadScope);
app.all("/read", async (req, res) => {
const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => ++reads);
const first = await read();
if (req.query.wait) await new Promise<void>((resolve) => gates.push(resolve));
res.json({ first, second: await read(), admin: await readOncePerRequest("admin:user-1", async () => "read") });
});
return { app, gates, reads: () => reads };
}
it("shares a read only inside one GET request", async () => {
const { app, reads } = countingApp();
expect((await request(app).get("/read")).body).toEqual({ first: 1, second: 1, admin: false });
expect((await request(app).get("/read")).body).toEqual({ first: 2, second: 2, admin: false });
expect(reads()).toBe(2);
});
it("reads again for every call in a write request", async () => {
const { app, reads } = countingApp();
expect((await request(app).post("/read")).body).toEqual({ first: 1, second: 2, admin: "read" });
expect((await request(app).delete("/read")).body).toEqual({ first: 3, second: 4, admin: "read" });
expect(reads()).toBe(4);
});
it("keeps overlapping GET requests apart", async () => {
const { app, gates } = countingApp();
const slow = request(app).get("/read?wait=1").then((res) => res.body);
while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));
const fast = await request(app).get("/read");
gates[0]!();
expect(await slow).toEqual({ first: 1, second: 1, admin: false });
expect(fast.body).toEqual({ first: 2, second: 2, admin: false });
});
it("ignores an entry older than the age bound", async () => {
const { app, gates, reads } = countingApp();
vi.useFakeTimers({ toFake: ["Date"] });
const pending = request(app).get("/read?wait=1").then((res) => res.body);
while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));
vi.setSystemTime(Date.now() + AUTHORIZATION_READ_MAX_AGE_MS + 1);
gates[0]!();
expect(await pending).toEqual({ first: 1, second: 2, admin: "read" });
expect(reads()).toBe(2);
});
it("does not keep a rejected read", async () => {
let attempts = 0;
const app = express();
app.use((req, _res, next) => {
req.actor = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false };
next();
});
app.use(authorizationReadScope);
app.get("/read", async (_req, res) => {
const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => {
attempts += 1;
if (attempts === 1) throw new Error("connection reset");
return attempts;
});
const first = await read().catch((error: Error) => error.message);
res.json({ first, second: await read(), third: await read() });
});
expect((await request(app).get("/read")).body).toEqual({ first: "connection reset", second: 2, third: 2 });
});
it.each([
["an agent key", { type: "agent", source: "agent_key", agentId: "agent-1", companyId: "company-1" }],
["a board key", { type: "board", source: "board_key", userId: "user-1", isInstanceAdmin: true }],
["a cloud tenant", { type: "board", source: "cloud_tenant", userId: "user-1", isInstanceAdmin: true }],
] as const)("seeds nothing for %s", async (_label, actor) => {
const { app } = countingApp(actor as Express.Request["actor"]);
expect((await request(app).get("/read")).body.admin).toBe("read");
});
it("keeps response hooks that later middleware installs", async () => {
const app = express();
app.use(authorizationReadScope);
app.use((_req, res, next) => {
const { writeHead, write } = res;
let writes = 0;
res.writeHead = function (this: typeof res, ...args: Parameters<typeof res.writeHead>) {
this.setHeader("x-late-hook", "kept");
return writeHead.apply(this, args);
} as typeof res.writeHead;
res.write = function (this: typeof res, ...args: Parameters<typeof res.write>) {
writes += 1;
res.locals.writes = writes;
return write.apply(this, args);
} as typeof res.write;
next();
});
app.get("/json", (_req, res) => { res.json({ ok: true }); });
app.get("/stream", (_req, res) => {
res.write("a");
res.write("b");
res.end(String(res.locals.writes));
});
const json = await request(app).get("/json").expect(200);
expect(json.headers["x-late-hook"]).toBe("kept");
const stream = await request(app).get("/stream").expect(200);
expect(stream.headers["x-late-hook"]).toBe("kept");
expect(stream.text).toBe("ab2");
});
});
@@ -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,104 @@
import request from "supertest";
import { and, eq, like } from "drizzle-orm";
import { expect, it } from "vitest";
import { folders } from "@paperclipai/db";
import { companySkillRoutes } from "../routes/company-skills.js";
import { folderService } from "../services/folders.js";
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
import { describeEmbeddedPostgres, routeApp, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("GET /api/companies/:companyId/skills statements per request", () => {
const ctx = useEmbeddedPostgres("company-skills-list-statements-");
function meter() {
const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
return meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/skills`);
}
const bundledFolders = (companyId: string) => ctx.db.select().from(folders)
.where(and(eq(folders.companyId, companyId), like(folders.systemKey, "bundled%")));
it("lists skills with plain reads once the bundled folders exist", async () => {
const statements = meter();
try {
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills list");
const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db));
const first = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200);
expect(first.body.length).toBeGreaterThan(0);
const foldersAfterFirst = await bundledFolders(company.companyId);
const before = statements.read();
statements.startLog();
const second = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200);
const log = statements.stopLog();
const after = statements.read();
expect(second.body).toEqual(first.body);
expect(after.transactions - before.transactions).toBe(0);
expect(log.filter((entry) => /pg_advisory/.test(entry.sql))).toEqual([]);
expect(after.statements - before.statements).toBeLessThanOrEqual(45);
expect(await bundledFolders(company.companyId)).toEqual(foldersAfterFirst);
} finally {
statements.uninstall();
}
}, 60_000);
it("creates exactly one folder when two first requests ensure the same category at once", async () => {
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills race");
const [left, right] = await Promise.all([
folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"),
folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"),
]);
expect(left.id).toBe(right.id);
const rows = await bundledFolders(company.companyId);
expect(rows.filter((row) => row.systemKey === "bundled:race-category")).toHaveLength(1);
expect(rows.filter((row) => row.systemKey === "bundled")).toHaveLength(1);
const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db));
await Promise.all([
request(app).get(`/api/companies/${company.companyId}/skills`).expect(200),
request(app).get(`/api/companies/${company.companyId}/skills`).expect(200),
]);
const systemKeys = (await bundledFolders(company.companyId)).map((row) => row.systemKey);
expect(new Set(systemKeys).size).toBe(systemKeys.length);
}, 60_000);
it("still renames a changed category and prunes an empty one under the lock", async () => {
const statements = meter();
try {
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills repair");
const svc = folderService(ctx.db);
const locked = async (write: () => Promise<unknown>) => {
const before = statements.read();
statements.startLog();
await write();
const log = statements.stopLog();
const lockIndex = log.findIndex((entry) => /pg_advisory_xact_lock/.test(entry.sql));
const writes = log.filter((entry) => /^\s*(insert|update|delete)\b/i.test(entry.sql));
return {
transactions: statements.read().transactions - before.transactions,
lockedBeforeWrite: lockIndex >= 0 && writes.every((entry) => entry.inTransaction && log.indexOf(entry) > lockIndex),
writes: writes.length,
};
};
const created = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category"));
expect(created).toMatchObject({ transactions: 1, lockedBeforeWrite: true });
expect(created.writes).toBeGreaterThan(0);
const [category] = (await bundledFolders(company.companyId)).filter((row) => row.systemKey === "bundled:repair-category");
await ctx.db.update(folders).set({ name: "Renamed by hand" }).where(eq(folders.id, category!.id));
const renamed = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category"));
expect(renamed).toMatchObject({ transactions: 1, lockedBeforeWrite: true, writes: 1 });
expect((await bundledFolders(company.companyId)).find((row) => row.id === category!.id)?.name).toBe("Repair Category");
expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, ["Repair Category"])))
.toEqual({ transactions: 0, lockedBeforeWrite: false, writes: 0 });
expect((await bundledFolders(company.companyId)).map((row) => row.id)).toContain(category!.id);
expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, [])))
.toEqual({ transactions: 1, lockedBeforeWrite: true, writes: 1 });
expect((await bundledFolders(company.companyId)).map((row) => row.id)).not.toContain(category!.id);
} finally {
statements.uninstall();
}
}, 60_000);
});
@@ -5,6 +5,7 @@ import { environmentTaskErrorCodeData, environmentTaskOperationSchema, parseEnvi
readEnvironmentTaskErrorCode, readEnvironmentTaskErrorDiagnostic } from "@paperclipai/plugin-sdk";
import { executeEnvironmentTask, isSettledReadyRunnerState, settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js";
import { NativeExecutionContext } from "../services/native-runtime/native-execution-context.js";
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
const state = vi.hoisted(() => ({ plugin: {} as any, release: vi.fn(), identity: vi.fn(), config: vi.fn() }));
vi.mock("../services/provider-fresh-workspace.js", () => ({
@@ -344,7 +345,7 @@ describe("plugin-provided Runner execution", () => {
await expect(executeEnvironmentTask(database(row(), []).db, denied as never, { companyId: "company", leaseId, operation })).rejects.toThrow("project unavailable");
expect(denied.call).not.toHaveBeenCalled();
});
it.each([false, true])("prepares scoped configuration with submit-time auth %s", async atSubmit => {
it("accepts prepare launch digests only when they match the requirements", async () => {
const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: {
schema: "paperclip.runner.launch-requirements.v1" as const,
identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run",
@@ -353,7 +354,35 @@ describe("plugin-provided Runner execution", () => {
settings: {}, approvalPolicy: "on-request" as const, readOnly: false,
preparedConversation: false, includeCollaborationModeInstructions: true,
} };
const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), launch: { configurationId: "configuration-1",
const preparationDigest = runnerLaunchPreparationDigest(operation.requirements);
const runDigest = runnerLaunchRunDigest(preparationDigest, operation.requirements);
const result = { kind: "prepared", taskId: "attempt-1", launch: { configurationId: "configuration-1",
requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } };
const accepted = worker(result);
await expect(executeEnvironmentTask(database().db, accepted as never, { companyId: "company", leaseId,
operation: { ...operation, preparationDigest, runDigest } })).resolves.toEqual(result);
expect(accepted.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({
operation: expect.objectContaining({ preparationDigest, runDigest }) }), 15_000);
const forged = `sha256:${"b".repeat(64)}`;
for (const digests of [{ preparationDigest: forged, runDigest }, { preparationDigest, runDigest: forged },
{ preparationDigest }, { runDigest }]) {
const refused = worker(result);
await expect(executeEnvironmentTask(database().db, refused as never, { companyId: "company", leaseId,
operation: { ...operation, ...digests } })).rejects.toThrow("launch digest mismatch");
expect(refused.call).not.toHaveBeenCalled();
}
});
it.each([[false, false], [true, false], [false, true], [true, true]])("prepares scoped configuration with submit-time auth %s and in-prepare auth %s", async (atSubmit, checked) => {
const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: {
schema: "paperclip.runner.launch-requirements.v1" as const,
identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run",
normalizedSessionId: "session", turnId: "turn", itemId: "item" },
provider: "codex" as const, model: "selected", instructions: "Core instructions", runtimeContext: null,
settings: {}, approvalPolicy: "on-request" as const, readOnly: false,
preparedConversation: false, includeCollaborationModeInstructions: true,
} };
const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}),
...(checked ? {projectAuthChecked: true} : {}), launch: { configurationId: "configuration-1",
requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } };
const workers = worker(result), store = database();
await expect(executeEnvironmentTask(store.db, workers as never, { companyId: "company", leaseId, operation }))
@@ -361,9 +390,10 @@ describe("plugin-provided Runner execution", () => {
expect(workers.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({
companyId: "company", runId: "run", agentId: "agent", projectIds: [projectId], operation,
}), 15_000);
expect(store.sets).toHaveLength(atSubmit ? 2 : 1);
if (atSubmit) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({
runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], atSubmit: true },
expect(store.sets).toHaveLength(atSubmit || checked ? 2 : 1);
if (atSubmit || checked) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({
runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId],
...(checked ? {} : { atSubmit: true }) },
}));
const denied = worker(result);
const inactive = row(); inactive.lease.status = "released";
@@ -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,140 @@
import { createHash, randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agentApiKeys, agents, authUsers, boardApiKeys, companies, companyMemberships, createDb, databaseStatementCount,
instanceUserRoles } from "@paperclipai/db";
import { createApp } from "../app.js";
import { activeServerMetrics, recordMissedLeaseRenewal, recordRunEventCommitted } from "../services/server-metrics.js";
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
import { createStorageService } from "../storage/service.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const describePostgres = support.supported ? describe : describe.skip;
const PATH = "/api/instance/server-metrics";
const FIELDS = [
"schema", "processId", "buildRevision", "uptimeSec", "sampledAt", "windowMs", "mainThreadCpu", "processCpu",
"eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond", "runEventLatenessP99Ms", "runEventLatenessSamples",
"agentApiPreHandlerP99Ms", "agentApiPreHandlerSamples", "leaseRenewalsMissed", "dedicatedConnections",
].sort();
type Db = ReturnType<typeof createDb>;
type App = Awaited<ReturnType<typeof createApp>>;
describePostgres("instance server metrics route", () => {
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let db: Db;
let directory: string;
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
const ids = { companyId: randomUUID(), agentId: randomUUID(), adminId: randomUUID(), memberId: randomUUID() };
const keys = { admin: `pcp_board_${randomUUID()}`, member: `pcp_board_${randomUUID()}`, agent: `pcp_agent_${randomUUID()}` };
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("instance-server-metrics-");
db = createDb(database.connectionString);
directory = await mkdtemp(join(tmpdir(), "instance-server-metrics-storage-"));
await db.insert(companies).values({ id: ids.companyId, name: "Metrics company", issuePrefix: "MET" });
await db.insert(authUsers).values([ids.adminId, ids.memberId].map(id => ({ id, name: "Person", email: `${id}@example.com`,
createdAt: new Date(), updatedAt: new Date() })));
await db.insert(instanceUserRoles).values({ userId: ids.adminId, role: "instance_admin" });
await db.insert(agents).values({ id: ids.agentId, companyId: ids.companyId, name: "Metrics agent", adapterType: "process",
status: "idle", permissions: {}, runtimeConfig: { heartbeat: { wakeOnDemand: false, intervalSec: 0 } } });
await db.insert(companyMemberships).values([
{ companyId: ids.companyId, principalType: "user", principalId: ids.memberId, membershipRole: "owner", status: "active" },
{ companyId: ids.companyId, principalType: "agent", principalId: ids.agentId, membershipRole: "member", status: "active" },
]);
await db.insert(boardApiKeys).values([
{ userId: ids.adminId, name: "Admin", keyHash: hash(keys.admin) },
{ userId: ids.memberId, name: "Member", keyHash: hash(keys.member) },
]);
await db.insert(agentApiKeys).values({ companyId: ids.companyId, agentId: ids.agentId, name: "Agent", keyHash: hash(keys.agent),
responsibleUserId: ids.memberId });
}, 120_000);
afterAll(async () => {
await db?.$client.end();
await database?.cleanup();
if (directory) await rm(directory, { recursive: true, force: true });
});
async function serve<T>(serverMetricsEnabled: boolean, body: (call: (path: string, token?: string) => Promise<{ status: number; body: any; text: string }>) => Promise<T>) {
const app: App = await createApp(db, {
uiMode: "none", serverPort: 0, bindHost: "127.0.0.1", allowedHostnames: ["127.0.0.1"],
deploymentMode: "authenticated", deploymentExposure: "private", authReady: true, companyDeletionEnabled: false,
managedPluginAutoInstall: [], storageService: createStorageService(createLocalDiskStorageProvider(directory)),
decisionServiceOptions: { wakeOriginAgent: async () => null }, serverMetricsEnabled,
});
await app.locals.bundledPluginsStartup;
const server = app.listen(0, "127.0.0.1");
try {
await new Promise<void>(resolve => server.once("listening", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("No HTTP test address");
const call = async (path: string, token?: string) => {
const response = await fetch(`http://127.0.0.1:${address.port}${path}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
const text = await response.text();
let parsed: unknown = null;
try { parsed = JSON.parse(text); } catch { parsed = null; }
return { status: response.status, body: parsed, text };
};
return await body(call);
} finally {
await app.locals.paperclipShutdown?.();
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
}
}
it("serves numbers to an instance admin only, and they move with load", async () => {
await serve(true, async (call) => {
expect(activeServerMetrics()).not.toBeNull();
expect([401, 403]).toContain((await call(PATH)).status);
expect((await call(PATH, keys.member)).status).toBe(403);
expect((await call(PATH, keys.agent)).status).toBe(403);
const first = await call(PATH, keys.admin);
expect(first.status).toBe(200);
expect(Object.keys(first.body).sort()).toEqual(FIELDS);
expect(first.body).toMatchObject({ schema: "paperclip.server-metrics.v1", processId: expect.stringMatching(/^[0-9a-f]{16}$/) });
expect(first.body.buildRevision === null || /^[0-9a-f]{40}$/.test(first.body.buildRevision)).toBe(true);
for (const field of ["uptimeSec", "windowMs", "processCpu", "eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond",
"runEventLatenessSamples", "agentApiPreHandlerSamples", "leaseRenewalsMissed"]) {
expect(typeof first.body[field], field).toBe("number");
}
expect(first.body.eventLoopUtilization).toBeGreaterThanOrEqual(0);
expect(first.body.dedicatedConnections).toMatchObject({ limit: expect.any(Number), inUse: expect.any(Number), waiting: expect.any(Number),
queued: expect.any(Number) });
expect(first.body.eventLoopUtilization).toBeLessThanOrEqual(1);
const statementsBefore = databaseStatementCount();
for (let index = 0; index < 5; index += 1) expect((await call("/api/agents/me", keys.agent)).status).toBe(200);
expect(databaseStatementCount()).toBeGreaterThan(statementsBefore);
recordRunEventCommitted(new Date(Date.now() - 750).toISOString(), Date.now());
recordMissedLeaseRenewal();
const second = await call(PATH, keys.admin);
expect(second.status).toBe(200);
expect(second.body.processId).toBe(first.body.processId);
expect(second.body.agentApiPreHandlerSamples).toBeGreaterThanOrEqual(first.body.agentApiPreHandlerSamples + 5);
expect(second.body.agentApiPreHandlerP99Ms).toBeGreaterThan(0);
expect(second.body.statementsPerSecond).toBeGreaterThan(0);
expect(second.body.runEventLatenessSamples).toBe(first.body.runEventLatenessSamples + 1);
expect(second.body.runEventLatenessP99Ms).toBeGreaterThanOrEqual(700);
expect(second.body.leaseRenewalsMissed).toBe(first.body.leaseRenewalsMissed + 1);
for (const secret of [...Object.values(ids), ...Object.values(keys)]) expect(second.text).not.toContain(secret);
expect(second.text).not.toMatch(/select|insert|update|from\s/i);
});
expect(activeServerMetrics()).toBeNull();
}, 240_000);
it("is absent and collects nothing when the kill switch is off", async () => {
await serve(false, async (call) => {
expect(activeServerMetrics()).toBeNull();
expect((await call(PATH, keys.admin)).status).toBe(404);
expect((await call(PATH, keys.member)).status).toBe(404);
expect((await call("/api/agents/me", keys.agent)).status).toBe(200);
expect(activeServerMetrics()).toBeNull();
});
}, 240_000);
});
@@ -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();
});
@@ -76,6 +76,7 @@ const apiPrefixes: Record<string, string> = {
"inbox-agent-policy.ts": "/api",
"inbox-dismissals.ts": "/api",
"instance-database-backups.ts": "/api",
"instance-server-metrics.ts": "/api",
"instance-settings.ts": "/api",
"issues.ts": "/api",
"issue-tree-control.ts": "/api",
+196
View File
@@ -0,0 +1,196 @@
import { readFileSync, writeFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import type { EventLoopUtilization } from "node:perf_hooks";
import {
activeServerMetrics,
recordMissedLeaseRenewal,
recordRunEventCommitted,
ServerMetricsCollector,
serverMetricsEnabledFromEnv,
startServerMetrics,
stopServerMetrics,
type ServerMetricsProbes,
} from "../services/server-metrics.js";
const FIXTURE = fileURLToPath(new URL("../../../scripts/scale-ramp/server-metrics.fixture.json", import.meta.url));
function fakeProbes() {
const state = { now: 0, wall: Date.parse("2026-11-14T12:00:00.000Z"), idle: 0, active: 0, cpuMicros: 0, mainMs: 0, statements: 0, uptime: 100 };
const elu = (): EventLoopUtilization => ({ idle: state.idle, active: state.active, utilization: 0 });
const probes: ServerMetricsProbes = {
now: () => state.now,
wallNow: () => state.wall,
eventLoopUtilization: (current?: EventLoopUtilization, previous?: EventLoopUtilization) => {
if (!current) return elu();
const idle = current.idle - (previous?.idle ?? 0);
const active = current.active - (previous?.active ?? 0);
return { idle, active, utilization: idle + active > 0 ? active / (idle + active) : 0 };
},
processCpuMicros: () => state.cpuMicros,
mainThreadCpuMs: () => state.mainMs,
statementCount: () => state.statements,
uptimeSec: () => state.uptime,
dedicatedConnections: () => ({ limit: 24, inUse: 3, peakInUse: 9, waiting: 1, queued: 12, overLimit: 0, nestedOverLimit: 0 }),
};
const advance = (ms: number, load: { busy: number; cpu?: number; statementsPerSecond?: number }) => {
state.now += ms;
state.wall += ms;
state.uptime += ms / 1000;
state.active += ms * load.busy;
state.idle += ms * (1 - load.busy);
state.mainMs += ms * load.busy;
state.cpuMicros += ms * (load.cpu ?? load.busy) * 1000;
state.statements += (ms / 1000) * (load.statementsPerSecond ?? 0);
};
return { probes, advance };
}
const collectors: ServerMetricsCollector[] = [];
function collector(probes: ServerMetricsProbes) {
const created = new ServerMetricsCollector({ probes, bucketMs: 10_000, buckets: 6, buildRevision: "0123456789abcdef0123456789abcdef01234567",
monitorEventLoop: false, processId: "a1b2c3d4e5f60718" });
collectors.push(created);
return created;
}
afterEach(() => {
for (const created of collectors.splice(0)) created.stop();
const active = activeServerMetrics();
if (active) stopServerMetrics(active);
});
describe("server metrics collector", () => {
it("reports rates and utilization over the sliding window, dropping buckets older than the window", () => {
const { probes, advance } = fakeProbes();
const metrics = collector(probes);
for (let bucket = 0; bucket < 6; bucket += 1) {
advance(10_000, { busy: 0.9, statementsPerSecond: 500 });
metrics.rotate();
}
const busy = metrics.snapshot();
expect(busy.windowMs).toBe(50_000);
expect(busy.eventLoopUtilization).toBeCloseTo(0.9, 4);
expect(busy.mainThreadCpu).toBeCloseTo(0.9, 4);
expect(busy.statementsPerSecond).toBeCloseTo(500, 2);
for (let bucket = 0; bucket < 6; bucket += 1) {
advance(10_000, { busy: 0.1, statementsPerSecond: 20 });
metrics.rotate();
}
const quiet = metrics.snapshot();
expect(quiet.eventLoopUtilization).toBeCloseTo(0.1, 4);
expect(quiet.statementsPerSecond).toBeCloseTo(20, 2);
});
it("expires buckets by elapsed time when the rotation timer fires late", () => {
const { probes, advance } = fakeProbes();
const metrics = collector(probes);
for (let bucket = 0; bucket < 6; bucket += 1) {
advance(10_000, { busy: 0.1, statementsPerSecond: 10 });
metrics.rotate();
}
metrics.recordRunEventLatenessMs(5_000);
advance(35_000, { busy: 0.5, statementsPerSecond: 100 });
metrics.rotate();
const late = metrics.snapshot();
expect(late.windowMs).toBe(55_000);
expect(late.statementsPerSecond).toBeCloseTo((20 * 10 + 35 * 100) / 55, 2);
expect(late.runEventLatenessSamples).toBe(1);
});
it("reports the real window after a block longer than the window, and the block shows in it", () => {
const { probes, advance } = fakeProbes();
const metrics = collector(probes);
for (let bucket = 0; bucket < 6; bucket += 1) {
advance(10_000, { busy: 0.1 });
metrics.rotate();
}
metrics.recordRunEventLatenessMs(20);
advance(300_000, { busy: 1 });
metrics.rotate();
const blocked = metrics.snapshot();
expect(blocked.windowMs).toBe(300_000);
expect(blocked.eventLoopUtilization).toBeCloseTo(1, 4);
expect(blocked.runEventLatenessSamples).toBe(1);
advance(10_000, { busy: 0.2 });
metrics.rotate();
expect(metrics.snapshot()).toMatchObject({ windowMs: 10_000, runEventLatenessSamples: 0 });
for (let bucket = 0; bucket < 5; bucket += 1) {
advance(10_000, { busy: 0.2 });
metrics.rotate();
}
const recovered = metrics.snapshot();
expect(recovered.windowMs).toBe(50_000);
expect(recovered.eventLoopUtilization).toBeCloseTo(0.2, 4);
});
it("reports latency percentiles only for the window and absent when nothing was recorded", () => {
const { probes, advance } = fakeProbes();
const metrics = collector(probes);
expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0,
agentApiPreHandlerP99Ms: null, agentApiPreHandlerSamples: 0 });
for (let index = 0; index < 100; index += 1) metrics.recordRunEventLatenessMs(index < 98 ? 20 : 2_000);
metrics.recordAgentApiPreHandlerMs(3.5);
const recorded = metrics.snapshot();
expect(recorded.runEventLatenessSamples).toBe(100);
expect(recorded.runEventLatenessP99Ms).toBeGreaterThan(1_900);
expect(recorded.agentApiPreHandlerP99Ms).toBeCloseTo(3.5, 1);
for (let bucket = 0; bucket < 6; bucket += 1) {
advance(10_000, { busy: 0 });
metrics.rotate();
}
expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0, agentApiPreHandlerSamples: 0 });
});
it("counts missed lease renewals since start and never resets them with the window", () => {
const { probes, advance } = fakeProbes();
const metrics = collector(probes);
metrics.recordMissedLeaseRenewal();
metrics.recordMissedLeaseRenewal();
for (let bucket = 0; bucket < 8; bucket += 1) {
advance(10_000, { busy: 0 });
metrics.rotate();
}
expect(metrics.snapshot().leaseRenewalsMissed).toBe(2);
});
it("records into the process collector only while it runs", () => {
recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now());
recordMissedLeaseRenewal();
expect(activeServerMetrics()).toBeNull();
const started = startServerMetrics();
expect(startServerMetrics()).toBe(started);
recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now());
recordRunEventCommitted("not a time", Date.now());
recordMissedLeaseRenewal();
const snapshot = started.snapshot();
expect(snapshot.runEventLatenessSamples).toBe(1);
expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(450);
expect(snapshot.leaseRenewalsMissed).toBe(1);
stopServerMetrics(started);
expect(activeServerMetrics()).toBeNull();
});
it("reads the kill switch strictly and defaults it off", () => {
expect(serverMetricsEnabledFromEnv({})).toBe(false);
expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "true" })).toBe(true);
expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "0" })).toBe(false);
expect(() => serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "yes" })).toThrow(/PAPERCLIP_SERVER_METRICS/);
});
it("serializes exactly the fixture the scale-ramp harness parses", () => {
const { probes, advance } = fakeProbes();
const metrics = collector(probes);
for (let bucket = 0; bucket < 6; bucket += 1) {
advance(10_000, { busy: 0.42, cpu: 0.55, statementsPerSecond: 180 });
metrics.rotate();
}
for (let index = 0; index < 50; index += 1) metrics.recordRunEventLatenessMs(120);
for (let index = 0; index < 50; index += 1) metrics.recordAgentApiPreHandlerMs(15);
metrics.recordMissedLeaseRenewal();
const snapshot = JSON.parse(JSON.stringify(metrics.snapshot()));
if (process.env.UPDATE_SERVER_METRICS_FIXTURE === "1") writeFileSync(FIXTURE, `${JSON.stringify(snapshot, null, 2)}\n`);
expect(snapshot).toEqual(JSON.parse(readFileSync(FIXTURE, "utf8")));
});
});