From 4daeab5c764d2154de2bbaef9c40a0a710415fbf Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:41:16 -0600 Subject: [PATCH] Add count, newest-first and lean run reads to customer-success inspection (#22781) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud can inspect a tenant stack read-only through the customer-success inspection API > - That API can only list rows in id order. It has no totals, and each run row holds large JSON columns > - A customer-success agent must page every run of a stack to find the latest run or the failed-run total > - That is too slow and too large for a refresh across many stacks > - This pull request adds a `count` operation, a creation-time `order` for lists, and a lean `summary` view for runs > - The benefit is one small read per metric, with the same read-only, company-scoped rules ## Linked Issues or Issue Description **Subsystem affected** Server: the customer-success inspection API (`/api/customer-success/v1`) and its shared query contract. **Problem or motivation** Customer-success inspection reads cannot answer summary questions. To get the latest run, the run count or the failed-run count, a reader must page through every run. Each run row can be hundreds of KB, because it holds the result, usage, context snapshot and runner profile. **Proposed solution** Add read-only summary reads to the inspection contract: a `count` that groups by status, a newest-first or oldest-first `order` for `list`, and a `summary` view of runs without the large JSON columns. **Alternatives considered** Paging all runs with a smaller page size. That still reads every large row. A new aggregated endpoint outside the reader catalog. That would skip the existing catalog, permit and transaction rules. ## What Changed - `packages/shared/src/customer-success.ts`: add the `count` operation, `order` (`newest`/`oldest`, `list` only), `view` (`summary`, `runs` list/get only), `InspectionCount`, and `inspectionReadPath()`. The parser rejects these fields where they do not apply. - `server/src/services/customer-success-inspection.ts`: `count` returns `{total, byStatus}` (grouped by the reader's `status` column, or `byStatus: null`). `order` sorts by `createdAt`, then id. `view: "summary"` selects the `RUN_SUMMARY_COLUMNS` allowlist and adds `durationMs`. All reads stay in the same read-only, repeatable-read transaction and keep the existing run redaction. - `server/src/routes/customer-success.ts`: serve the same handler on `/read` and the new `/read-v2`. `/read` refuses queries that use the new features. A tenant without `/read-v2` answers 404, so Cloud fails closed with `tenant_inspection_version_unsupported`. - `server/src/__tests__/customer-success.test.ts`: tests for counts, company scope, newest-first paging, the summary allowlist and duration, parser bounds, and the path split. - `server/src/__tests__/customer-success-cloud.test.ts`: the registry double now has the batch reads (`getStacks`, `getAccounts`) that the current Cloud broker uses. The test also runs a count and a newest-first summary read end to end. - `server/src/__tests__/openapi-routes.test.ts`: list `/read-v2` with the other inspection protocol routes. - `doc/CUSTOMER-SUCCESS-INSPECTION.md`: document the summary reads and the path split. ## Verification - `cd server && pnpm exec vitest run src/__tests__/customer-success.test.ts src/__tests__/openapi-routes.test.ts src/__tests__/customer-success-run-liveness.test.ts`: 78 tests pass. - Red check: the new count/order/summary test fails against the previous service (`Unsupported inspection operation`). - Coordinated qualification with a local build of the Cloud broker branch: `PAPERCLIP_INSPECTION_CLOUD_DIST=… pnpm exec vitest run src/__tests__/customer-success-cloud.test.ts` passes, including the count and newest-first summary reads over `/read-v2`. ## Risks - Low risk. The new features are read-only and use the existing catalog, company boundary, permit check and read-only transaction. - The summary view is an allowlist. A new run column stays out of the summary until someone adds it. - Mixed versions are safe in both orders. An older Cloud never sends the new fields. A newer Cloud sends them only to `/read-v2`, and an older tenant answers 404 there. - No migration. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, file edits) and extended thinking. ## 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 - [ ] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Paperclip Co-authored-by: Claude Opus 5.5 --- doc/CUSTOMER-SUCCESS-INSPECTION.md | 21 ++- packages/shared/src/customer-success.ts | 44 ++++- .../__tests__/customer-success-cloud.test.ts | 19 +- server/src/__tests__/customer-success.test.ts | 173 ++++++++++++++++++ server/src/__tests__/openapi-routes.test.ts | 1 + server/src/routes/customer-success.ts | 15 +- .../services/customer-success-inspection.ts | 95 +++++++++- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 8 files changed, 355 insertions(+), 15 deletions(-) diff --git a/doc/CUSTOMER-SUCCESS-INSPECTION.md b/doc/CUSTOMER-SUCCESS-INSPECTION.md index bd27a2ad95c..d3fddfca430 100644 --- a/doc/CUSTOMER-SUCCESS-INSPECTION.md +++ b/doc/CUSTOMER-SUCCESS-INSPECTION.md @@ -1,7 +1,7 @@ # Cloud customer-success inspection support -Paperclip exposes `/api/customer-success/v1/run-authority`, `/run-liveness` and -`/read` for the coordinated Cloud inspection broker. This foundation supports one registered +Paperclip exposes `/api/customer-success/v1/run-authority`, `/run-liveness`, +`/read` and `/read-v2` for the coordinated Cloud inspection broker. This foundation supports one registered Paperclip agent; bot creation, scheduling, scoring and reporting are separate. The authority endpoint is disabled unless @@ -67,6 +67,23 @@ pass through Cloud; ranges cap at 1 MiB, JSON at 2 MiB, and lists at 100 rows. Remote or unsnapshotted resources report unavailable; large content requires pagination or download ranges. No storage credentials or bypass URLs are issued. +Summary reads keep a fleet-wide refresh cheap: + +- `count` takes a catalogued `resource`, `companyId` and optional `parentId`, + and returns `{total, byStatus}`: counts grouped by the reader's `status` + column, or `byStatus: null` when it has none. No row content is read out. +- `order` (`list` only) is `newest` or `oldest` by creation time, with the table's + primary key as tie-breaker so offset pages never repeat or skip rows. Without it, lists keep their original id order. +- `view: "summary"` (`list`/`get` on `runs` only) returns an allowlist of ids, + status, error code, retry counters and timestamps plus a computed + `durationMs`, and leaves out the large JSON columns (result, usage, context + snapshot, runner profile). `RUN_SUMMARY_COLUMNS` is the allowlist. + +Queries that use `count`, `order` or `view` are served only on `/read-v2` +(`inspectionReadPath` picks the path); `/read` refuses them. A tenant that +predates them answers 404 on `/read-v2`, so Cloud fails closed with +`tenant_inspection_version_unsupported` instead of misreading the query. + Existing config/event/run redactions and path/symlink/secret-file/size restrictions remain in use. Authentication account/session, secret, private-key/encrypted-key and raw provider-trace tables/readers are excluded. Identity-enabled trace diff --git a/packages/shared/src/customer-success.ts b/packages/shared/src/customer-success.ts index a2d02aaa822..cf22017ffdd 100644 --- a/packages/shared/src/customer-success.ts +++ b/packages/shared/src/customer-success.ts @@ -65,10 +65,28 @@ export const INSPECTION_RESOURCES = [ "threads", ] as const; export type InspectionResource = (typeof INSPECTION_RESOURCES)[number]; +export const INSPECTION_ORDERS = ["newest", "oldest"] as const; +export type InspectionOrder = (typeof INSPECTION_ORDERS)[number]; +export const INSPECTION_VIEWS = ["summary"] as const; +export type InspectionView = (typeof INSPECTION_VIEWS)[number]; +/** The tenant path for queries that use only the original (version 1) features. */ +export const INSPECTION_READ_PATH = "/read"; +/** + * The tenant path for queries that use `count`, `order` or `view`. A tenant + * that predates them answers 404 here, so Cloud fails closed with + * `tenant_inspection_version_unsupported` instead of misreading the query. + */ +export const INSPECTION_EXTENDED_READ_PATH = "/read-v2"; +export interface InspectionCount { + total: number; + /** Counts grouped by the resource's `status` column, or null when it has none. */ + byStatus: Record | null; +} export interface InspectionQuery { operation: | "list" | "get" + | "count" | "instructions.file" | "skills.file" | "runs.log" @@ -85,6 +103,10 @@ export interface InspectionQuery { limit?: number; offset?: number; range?: { start: number; end: number }; + /** `list` only: order by creation time instead of by id. */ + order?: InspectionOrder; + /** `list`/`get` on `runs` only: leave out the large JSON columns. */ + view?: InspectionView; context?: { projectId?: string; workspaceId?: string; @@ -129,6 +151,11 @@ export function canonicalJson(value: unknown): string { } throw new Error("Invalid JSON value"); } +export function inspectionReadPath(query: InspectionQuery): string { + return query.operation === "count" || query.order !== undefined || query.view !== undefined + ? INSPECTION_EXTENDED_READ_PATH + : INSPECTION_READ_PATH; +} export function parseInspectionQuery(value: unknown): InspectionQuery { if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid inspection query"); @@ -144,6 +171,8 @@ export function parseInspectionQuery(value: unknown): InspectionQuery { "limit", "offset", "range", + "order", + "view", "context", ]); if (Object.keys(q).some((k) => !allowed.has(k))) @@ -152,6 +181,7 @@ export function parseInspectionQuery(value: unknown): InspectionQuery { ![ "list", "get", + "count", "instructions.file", "skills.file", "runs.log", @@ -169,11 +199,21 @@ export function parseInspectionQuery(value: unknown): InspectionQuery { if (q.resource !== undefined && !INSPECTION_RESOURCES.includes(q.resource)) throw new Error("Unsupported inspection resource"); if (q.operation === "get" && !q.resourceId) throw new Error("resourceId required"); - if (["get", "list"].includes(q.operation) && !q.resource) throw new Error("resource required"); + if (["get", "list", "count"].includes(q.operation) && !q.resource) + throw new Error("resource required"); if (!(q.operation === "list" && q.resource === "companies") && !q.companyId) throw new Error("companyId required"); - if (!["get", "list"].includes(q.operation) && !q.resourceId) + if (!["get", "list", "count"].includes(q.operation) && !q.resourceId) throw new Error("resourceId required"); + if (q.operation === "count" && q.resourceId !== undefined) + throw new Error("count does not take resourceId"); + if (q.order !== undefined && (q.operation !== "list" || !INSPECTION_ORDERS.includes(q.order))) + throw new Error("Invalid order"); + if ( + q.view !== undefined && + (!["list", "get"].includes(q.operation) || q.resource !== "runs" || !INSPECTION_VIEWS.includes(q.view)) + ) + throw new Error("Invalid view"); if ( q.path !== undefined && (typeof q.path !== "string" || q.path.length > 1024 || q.path.includes("\0")) diff --git a/server/src/__tests__/customer-success-cloud.test.ts b/server/src/__tests__/customer-success-cloud.test.ts index c1557a7ce22..25dcc5a9bd3 100644 --- a/server/src/__tests__/customer-success-cloud.test.ts +++ b/server/src/__tests__/customer-success-cloud.test.ts @@ -154,6 +154,18 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua transactionReads++; return registry.getCustomerSuccessAccount(id); }, + getStacks: async (ids: readonly string[]) => { + await client.query("SELECT 1"); + transactionReads++; + return (await Promise.all(ids.map((id) => registry.getStack(id)))).filter(Boolean); + }, + getAccounts: async (ids: readonly string[]) => { + await client.query("SELECT 1"); + transactionReads++; + return ( + await Promise.all(ids.map((id) => registry.getCustomerSuccessAccount(id))) + ).filter(Boolean); + }, listStackIds: async () => registry.listCustomerSuccessStackIds(), }); const store = new PostgresInspectionStore(pool, registryForClient); @@ -272,7 +284,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua const grant=await call('grant',{stackId:'qualification-stack'}); const tasks=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'tasks',companyId:${JSON.stringify(customer.id)}}}); const file=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'files.download',companyId:${JSON.stringify(customer.id)},resourceId:${JSON.stringify(task.id)},context:{projectId:${JSON.stringify(project.id)},workspaceId:${JSON.stringify(workspace.id)}},path:'result.bin',range:{start:2,end:5}}}); - console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')]})); + const taskCount=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'count',resource:'tasks',companyId:${JSON.stringify(customer.id)}}}); + const latestRuns=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'runs',companyId:${JSON.stringify(customer.id)},order:'newest',view:'summary',limit:1}}); + console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')],taskCount,latestRuns})); `; const programFile = join(directory, "qualify.mjs"); await writeFile(programFile, program); @@ -298,6 +312,9 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua expect(result.exitCode, [...output, ...serverErrors].join("\n")).toBe(0); expect(output.join("")).toContain("First successful task"); expect(output.join("")).toContain('"fileBytes":[2,3,4,5]'); + // Count and newest-first summary reads travel the extended tenant path. + expect(output.join("")).toContain('"taskCount":{"total":1,"byStatus":{'); + expect(output.join("")).toContain('"latestRuns":{"items":[],"nextOffset":null}'); expect((await stat(filePath)).mtimeMs).toBe(fileBefore.mtimeMs); expect(await readFile(filePath)).toEqual(Buffer.from([0, 1, 2, 3, 4, 5])); const audit = await pool.query( diff --git a/server/src/__tests__/customer-success.test.ts b/server/src/__tests__/customer-success.test.ts index 19b48f979b2..1f05481faf0 100644 --- a/server/src/__tests__/customer-success.test.ts +++ b/server/src/__tests__/customer-success.test.ts @@ -13,6 +13,7 @@ import { INSPECTION_HEADER, INSPECTION_PERMIT_TYPE, INSPECTION_RESOURCES, + inspectionReadPath, parseInspectionQuery, type InspectionQuery, type InspectionPermit, @@ -21,6 +22,8 @@ import { customerSuccessRunAuthority } from "../services/customer-success-author import { readCustomerSuccessResource, inspectionReaders, + RUN_SUMMARY_COLUMNS, + primaryKeyColumns, } from "../services/customer-success-inspection.js"; import { customerSuccessRoutes, @@ -438,6 +441,29 @@ describe("customer-success read authority", () => { expect((await request(app).post("/api/customer-success/v1/unknown").send({})).status).toEqual( 404, ); + // Count, order and view live only on the extended path, so a tenant that + // predates them answers 404 there and Cloud fails closed. + const countQuery: InspectionQuery = { operation: "count", resource: "tasks", companyId }; + const countToken = () => token({ ...claims, jti: randomUUID(), query: countQuery }); + expect( + ( + await request(app) + .post("/api/customer-success/v1/read") + .set(INSPECTION_HEADER, countToken()) + .send(countQuery) + ).status, + ).toEqual(403); + const counted = await request(app) + .post("/api/customer-success/v1/read-v2") + .set(INSPECTION_HEADER, countToken()) + .send(countQuery); + expect(counted.status).toEqual(200); + expect(counted.body).toEqual({ total: expect.any(Number), byStatus: expect.any(Object) }); + const original = await request(app) + .post("/api/customer-success/v1/read-v2") + .set(INSPECTION_HEADER, token()) + .send(query); + expect(original.status).toEqual(200); fetcher.mockResolvedValue(new Response("", { status: 503 })); expect( ( @@ -692,6 +718,153 @@ describe("customer-success read authority", () => { })) as { items: unknown[] }; expect(versions.items).toHaveLength(1); }); + it("counts by status, orders newest first, and returns lean run summaries, company scoped", async () => { + const [company, other] = await db + .insert(schema.companies) + .values([ + { name: "Counted", issuePrefix: "CNT" }, + { name: "Elsewhere", issuePrefix: "ELS" }, + ]) + .returning(); + const [countedAgent] = await db + .insert(schema.agents) + .values({ companyId: company.id, name: "Counted agent", adapterType: "process" }) + .returning(); + const [otherAgent] = await db + .insert(schema.agents) + .values({ companyId: other.id, name: "Other agent", adapterType: "process" }) + .returning(); + const heavy = { transcript: "x".repeat(200_000) }; + const at = (minutes: number) => new Date(Date.UTC(2026, 0, 1, 0, minutes)); + const runs = await db + .insert(schema.heartbeatRuns) + .values([ + { companyId: company.id, agentId: countedAgent.id, status: "succeeded", createdAt: at(1), startedAt: at(1), finishedAt: at(3), resultJson: heavy, contextSnapshot: heavy }, + { companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(5), startedAt: at(5), finishedAt: at(6), errorCode: "adapter_failed", resultJson: heavy }, + { companyId: company.id, agentId: countedAgent.id, status: "failed", createdAt: at(9), startedAt: at(9), resultJson: heavy }, + { companyId: other.id, agentId: otherAgent.id, status: "failed", createdAt: at(20) }, + ]) + .returning(); + await db.insert(schema.issues).values([ + { companyId: company.id, title: "Open", status: "todo" }, + { companyId: company.id, title: "Shipped", status: "done" }, + { companyId: other.id, title: "Not ours", status: "done" }, + ]); + + expect( + await readCustomerSuccessResource(db, storage, { operation: "count", resource: "runs", companyId: company.id }), + ).toEqual({ total: 3, byStatus: { succeeded: 1, failed: 2 } }); + expect( + await readCustomerSuccessResource(db, storage, { operation: "count", resource: "tasks", companyId: company.id }), + ).toEqual({ total: 2, byStatus: { todo: 1, done: 1 } }); + expect( + await readCustomerSuccessResource(db, storage, { + operation: "count", + resource: "comments", + companyId: company.id, + }), + ).toEqual({ total: 0, byStatus: null }); + + const latest = (await readCustomerSuccessResource(db, storage, { + operation: "list", + resource: "runs", + companyId: company.id, + order: "newest", + view: "summary", + limit: 1, + })) as { items: Array>; nextOffset: number | null }; + expect(latest.items.map((r) => r.id)).toEqual([runs[2].id]); + expect(latest.nextOffset).toEqual(1); + expect(Object.keys(latest.items[0]).sort()).toEqual([...RUN_SUMMARY_COLUMNS, "durationMs"].sort()); + expect(latest.items[0].durationMs).toBeNull(); + expect(JSON.stringify(latest).length).toBeLessThan(2_000); + + const page = (await readCustomerSuccessResource(db, storage, { + operation: "list", + resource: "runs", + companyId: company.id, + order: "newest", + view: "summary", + limit: 2, + offset: 1, + })) as { items: Array> }; + expect(page.items.map((r) => [r.id, r.durationMs])).toEqual([ + [runs[1].id, 60_000], + [runs[0].id, 120_000], + ]); + const oldest = (await readCustomerSuccessResource(db, storage, { + operation: "list", + resource: "runs", + companyId: company.id, + order: "oldest", + limit: 1, + })) as { items: Array> }; + expect(oldest.items[0].id).toEqual(runs[0].id); + expect(oldest.items[0]).toHaveProperty("resultJson"); + + const one = (await readCustomerSuccessResource(db, storage, { + operation: "get", + resource: "runs", + companyId: company.id, + resourceId: runs[1].id, + view: "summary", + })) as Record; + expect(one).toMatchObject({ id: runs[1].id, status: "failed", errorCode: "adapter_failed", durationMs: 60_000 }); + expect(one).not.toHaveProperty("resultJson"); + expect(one).not.toHaveProperty("contextSnapshot"); + }); + it("ordered pages cover rows that share a creation time exactly once", async () => { + for (const resource of INSPECTION_RESOURCES) + expect(primaryKeyColumns(inspectionReaders[resource].table).length, resource).toBeGreaterThan(0); + const [company] = await db + .insert(schema.companies) + .values({ name: "Labelled", issuePrefix: "LBL" }) + .returning(); + const [issue] = await db.insert(schema.issues).values({ companyId: company.id, title: "Tagged" }).returning(); + const labels = await db + .insert(schema.labels) + .values(Array.from({ length: 5 }, (_, i) => ({ companyId: company.id, name: `label-${i}`, color: "#000000" }))) + .returning(); + const createdAt = new Date(Date.UTC(2026, 0, 2)); + await db + .insert(schema.issueLabels) + .values(labels.map((label) => ({ companyId: company.id, issueId: issue.id, labelId: label.id, createdAt }))); + for (const order of ["newest", "oldest"] as const) { + const seen: string[] = []; + for (let offset = 0; offset < labels.length; offset += 2) { + const page = (await readCustomerSuccessResource(db, storage, { + operation: "list", + resource: "taskLabels", + companyId: company.id, + order, + limit: 2, + offset, + })) as { items: Array<{ labelId: string }> }; + seen.push(...page.items.map((row) => row.labelId)); + } + expect(seen.sort()).toEqual(labels.map((label) => label.id).sort()); + } + }); + it("count, order and view are bounded and take the extended read path", () => { + expect(inspectionReadPath(parseInspectionQuery({ operation: "list", resource: "runs", companyId }))).toEqual("/read"); + for (const value of [ + { operation: "count", resource: "runs", companyId }, + { operation: "list", resource: "runs", companyId, order: "newest" }, + { operation: "get", resource: "runs", companyId, resourceId: agentId, view: "summary" }, + ]) + expect(inspectionReadPath(parseInspectionQuery(value))).toEqual("/read-v2"); + for (const value of [ + { operation: "count", companyId }, + { operation: "count", resource: "runs" }, + { operation: "count", resource: "runs", companyId, resourceId: agentId }, + { operation: "get", resource: "runs", companyId, resourceId: agentId, order: "newest" }, + { operation: "list", resource: "runs", companyId, order: "random" }, + { operation: "list", resource: "tasks", companyId, view: "summary" }, + { operation: "list", resource: "runs", companyId, view: "full" }, + { operation: "runs.log", companyId, resourceId: agentId, view: "summary" }, + ]) + expect(() => parseInspectionQuery(value)).toThrow(); + }); it("the operation contract has no writes, credentials or unknown parameters", () => { for (const value of [ { operation: "write", companyId }, diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index 46ccf86ebe2..f2c90f8c260 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -153,6 +153,7 @@ const explicitOpenApiOperationCoverageExclusions = new Set([ // Ordinary board sessions and agent API keys cannot invoke these endpoints. "GET /api/customer-success/v1/run-authority", "POST /api/customer-success/v1/read", + "POST /api/customer-success/v1/read-v2", "POST /api/customer-success/v1/run-liveness", // OAuth discovery and protocol endpoints have their own metadata contract; // browser connection-management operations remain documented in the board API. diff --git a/server/src/routes/customer-success.ts b/server/src/routes/customer-success.ts index 94083ffd5db..66e8731be33 100644 --- a/server/src/routes/customer-success.ts +++ b/server/src/routes/customer-success.ts @@ -1,9 +1,11 @@ import { createPublicKey, verify } from "node:crypto"; -import { Router } from "express"; +import { Router, type Request as ExpressRequest, type Response as ExpressResponse } from "express"; import type { Db } from "@paperclipai/db"; import { canonicalJson, + inspectionReadPath, parseInspectionQuery, + INSPECTION_READ_PATH, INSPECTION_AUDIENCE, INSPECTION_PERMIT_TYPE, INSPECTION_HEADER, @@ -180,7 +182,10 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: if (!match) throw forbidden("Managed run bearer required"); res.json(await customerSuccessRunAuthority(db, match[1])); }); - router.post("/read", async (req, res) => { + // `/read` serves the original query features; `/read-v2` also serves + // count, order and view. Cloud picks the path from the query, so a tenant + // without `/read-v2` answers 404 and Cloud fails closed. + const read = async (req: ExpressRequest, res: ExpressResponse) => { if (process.env.PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED !== "true") throw forbidden("Inspection is disabled"); if (req.headers.authorization || req.headers.cookie) @@ -209,6 +214,8 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: } if (canonicalJson(query) !== canonicalJson(permit.query)) throw forbidden("Inspection parameters do not match permit"); + if (req.path === INSPECTION_READ_PATH && inspectionReadPath(query) !== INSPECTION_READ_PATH) + throw forbidden("This inspection query needs the extended read path"); // Replay fencing and all inspection state live in Cloud. No tenant receipt. const consumed = await fetch(`${origin}/v1/customer-success/permits/consume`, { method: "POST", @@ -223,7 +230,9 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: if (body === null) throw unprocessable("Inspection response is too large; use pagination or a byte range"); res.type("application/json").send(body); - }); + }; + router.post("/read", read); + router.post("/read-v2", read); // Cloud run liveness check for inspection authority. Cloud asks with its // own signed, stack-addressed, 60-second question; no agent credential, // identity key, actor, session or activity is involved. diff --git a/server/src/services/customer-success-inspection.ts b/server/src/services/customer-success-inspection.ts index 63b5b49f1ce..caac018b04a 100644 --- a/server/src/services/customer-success-inspection.ts +++ b/server/src/services/customer-success-inspection.ts @@ -1,7 +1,7 @@ import fs from "node:fs/promises"; import { constants } from "node:fs"; -import { and, eq, getTableColumns, type SQL } from "drizzle-orm"; -import type { AnyPgTable, AnyPgColumn } from "drizzle-orm/pg-core"; +import { and, asc, count, desc, eq, getTableColumns, type SQL } from "drizzle-orm"; +import { getTableConfig, type AnyPgTable, type AnyPgColumn } from "drizzle-orm/pg-core"; import * as schema from "@paperclipai/db"; import type { Db } from "@paperclipai/db"; import { @@ -31,6 +31,42 @@ export interface CustomerSuccessInspectionOptions { pluginWorkerManager?: PluginWorkerManager; } +/** + * The `summary` view of a run: status, timestamps, ids and error codes, never + * the large JSON columns (result, usage, context snapshot, runner profile...), + * which make a full run row 170-540 KB. An allowlist, so a new column stays out + * until someone adds it here. + */ +export const RUN_SUMMARY_COLUMNS = [ + "id", + "companyId", + "agentId", + "issueId", + "scopeKind", + "invocationSource", + "triggerDetail", + "status", + "errorCode", + "exitCode", + "runtimeMode", + "driverKind", + "retryOfRunId", + "processLossRetryCount", + "scheduledRetryAttempt", + "continuationAttempt", + "livenessState", + "startedAt", + "finishedAt", + "createdAt", + "updatedAt", +] as const; + +function durationMs(row: Record): number | null { + const started = row.startedAt instanceof Date ? row.startedAt.getTime() : null; + const finished = row.finishedAt instanceof Date ? row.finishedAt.getTime() : null; + return started !== null && finished !== null ? Math.max(0, finished - started) : null; +} + // This is a reviewed catalog of readers, not a proxy for existing GET routes. // Select credentials out of queries; never load encrypted identity records. interface Reader { @@ -109,6 +145,13 @@ export const inspectionReaders: Record = { threads: { table: schema.chatConversations, parent: "endpointId" }, }; +/** The table's primary key columns: a stable tie-breaker for ordered pages. */ +export function primaryKeyColumns(table: AnyPgTable): AnyPgColumn[] { + const config = getTableConfig(table); + const single = config.columns.filter((column) => column.primary); + return single.length ? single : (config.primaryKeys[0]?.columns ?? []); +} + async function ownRow(tx: Db, table: AnyPgTable, companyId: string, id: string) { const columns = getTableColumns(table) as Record; const [row] = await tx @@ -157,7 +200,7 @@ export async function readCustomerSuccessResource( .where(eq(schema.companies.id, q.companyId)); if (!company) throw notFound("Inspection company not found"); } - if (q.operation === "list" || q.operation === "get") { + if (q.operation === "list" || q.operation === "get" || q.operation === "count") { const reader = inspectionReaders[q.resource!]; const all = getTableColumns(reader.table) as Record; const columns = Object.fromEntries( @@ -180,6 +223,7 @@ export async function readCustomerSuccessResource( const { inArray } = await import("drizzle-orm"); if (!memberships.length) { if (q.operation === "get") throw notFound("Inspection resource not found"); + if (q.operation === "count") return { total: 0, byStatus: all.status ? {} : null }; return { items: [], nextOffset: null }; } predicates.push( @@ -200,13 +244,51 @@ export async function readCustomerSuccessResource( throw unprocessable("This reader does not accept parentId"); predicates.push(eq(all[reader.parent], q.parentId)); } + if (q.operation === "count") { + // Totals only: no row content leaves the database. + if (!all.status) { + const [{ total }] = await tx + .select({ total: count() }) + .from(reader.table) + .where(and(...predicates)); + return { total: Number(total), byStatus: null }; + } + const groups = await tx + .select({ status: all.status, total: count() }) + .from(reader.table) + .where(and(...predicates)) + .groupBy(all.status); + const byStatus: Record = {}; + let total = 0; + for (const group of groups) { + byStatus[String(group.status)] = Number(group.total); + total += Number(group.total); + } + return { total, byStatus }; + } const limit = q.operation === "get" ? 1 : Math.max(1, q.limit ?? 25); - const order = all[reader.id ?? "id"] ?? all.createdAt ?? all.companyId; + const idColumn = all[reader.id ?? "id"]; + let orderBy: SQL[] | AnyPgColumn[]; + if (q.order) { + if (!all.createdAt) throw unprocessable("This resource has no creation time to order by"); + const direction = q.order === "newest" ? desc : asc; + // Rows written together share createdAt; the full primary key keeps + // offset pages from repeating or skipping them. + orderBy = [all.createdAt, ...primaryKeyColumns(reader.table)].map((column) => direction(column)); + } else { + orderBy = [idColumn ?? all.createdAt ?? all.companyId]; + } + const selected = + q.view === "summary" + ? Object.fromEntries( + RUN_SUMMARY_COLUMNS.filter((key) => columns[key]).map((key) => [key, columns[key]]), + ) + : columns; let rows = await tx - .select(columns) + .select(selected) .from(reader.table) .where(and(...predicates)) - .orderBy(order) + .orderBy(...orderBy) .limit(limit + (q.operation === "get" ? 0 : 1)) .offset(q.offset ?? 0); if (q.resource === "agents") @@ -245,6 +327,7 @@ export async function readCustomerSuccessResource( q.companyId!, rows as Array<{ id: string }>, ); + if (q.view === "summary") rows = rows.map((r) => ({ ...r, durationMs: durationMs(r) })); // Match the existing structured event/config redaction, without scanning // prose, documents, instructions, skill contents, or workspace files. if ( diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index a98da2aef16..e96931b7fe5 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -241,7 +241,7 @@ "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", - "packages/shared/src/customer-success.ts": "a2d02aaa8223164c0eae4267b2a6da82242eaa6f", + "packages/shared/src/customer-success.ts": "cf22017ffdd45123c1879f13c71c17516b8479a5", "packages/shared/src/decision-models.ts": "a07aefd87d2fae34283ce21a0334d57e2108aa7e", "packages/shared/src/decision.test.ts": "d0783d18613c73102f662e8a5da795ff6e7faed5", "packages/shared/src/document-anchors.test.ts": "6805d149ad66d91f2e3ba4841f82e9af05bf5d83",