Add count, newest-first and lean run reads to customer-success inspection (#22781)

<!-- Write all pull request text in Simplified Technical English
(ASD-STE100): short sentences, one instruction per sentence, simple
approved vocabulary, and the active voice. -->

## 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 <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-11-24 11:41:16 -06:00
1 parent 11cfe0910d
commit 4daeab5c76
8 files changed
+355 -15

No files matched your search

@@ -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(
@@ -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<Record<string, unknown>>; 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<Record<string, unknown>> };
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<Record<string, unknown>> };
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<string, unknown>;
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 },
@@ -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.