mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
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:
8 files changed
+355
-15
No files matched your search
@@ -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<string, unknown>): 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<InspectionResource, Reader> = {
|
||||
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<string, AnyPgColumn>;
|
||||
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<string, AnyPgColumn>;
|
||||
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<string, number> = {};
|
||||
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 (
|
||||
|
||||
Reference in new issue
Block a user