feat(customer-success): add runs.search (/read-v3) and structured platform run diagnostics (#22985)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Paperclip Cloud inspects tenant stacks read-only through
`/api/customer-success/v1`
> - Today, inspection can only read raw byte slices of one run log at a
time, and platform guard or launcher errors inside agent shell commands
leave runs marked `succeeded` with `exitCode: 0` and no `errorCode`
> - Finding how many runs hit an error string requires downloading
megabytes of raw logs and pulling customer prompts into agent context
> - This pull request adds bounded, match-only `runs.search` and
stack-wide `count` on `/read-v3`, plus closed-vocabulary platform run
diagnostics recorded on runs and surfaced in `view: "summary"`
> - The benefit is fast, privacy-preserving prevalence diagnosis without
exposing raw customer prose or missing errors hidden inside succeeded
runs

## Linked Issues or Issue Description

**Subsystem affected**

Server and shared contracts: `/api/customer-success/v1` inspection
endpoints, shared inspection wire contract, and run-event platform
diagnostics.

**Problem or motivation**

When a platform wrapper (such as the Git storage guard or GitHub
credential launcher) fails inside an agent tool call, the outer agent
run often still finishes with `status: "succeeded"` and `errorCode:
null`. Investigating prevalence through customer-success inspection
previously required paging raw `runs.log` byte ranges one run at a time,
pulling customer prompts into context and making fleet-wide triage
impractical.

**Proposed solution**

1. Extend the shared customer-success wire contract
(`packages/shared/src/customer-success.ts`) with `runs.search` (1 to 5
literal substrings, no regex, optional creation window,
counts/co-occurrence/sample pointers only by default, redacted excerpts
only when `companyId` and `includeExcerpts: true` are set) and
stack-wide `count` on `/api/customer-success/v1/read-v3`.
2. Execute `runs.search` inside the existing read-only, repeatable-read
transaction using in-database `strpos` matching over
`heartbeat_run_events` plus `heartbeat_runs` error fields, falling back
to chunked `RunLogStore` scans with overlap windows for
legacy/non-native runs or runs without stored events.
3. Add a closed-vocabulary platform diagnostic detector
(`packages/shared/src/run-diagnostics.ts`) that records deduplicated
`platform.diagnostic` rows in `heartbeat_run_events`, attaches
`diagnostics` to `view: "summary"` run reads, and optionally reports
bounded PII-free diagnostic codes to Paperclip Cloud when a stack
diagnostics capability is configured.

**Alternatives considered**

Paging raw `runs.log` slices from Cloud or the agent. That transfers
megabytes of unrelated customer prose, hits rate limits, and still fails
to surface known platform errors in structured run summaries.

## What Changed

- `packages/shared/src/customer-success.ts`: add
`INSPECTION_SEARCH_READ_PATH` (`"/read-v3"`), `runs.search` operation
and strict parser bounds, optional `companyId` for `runs.search`
(without excerpts) and stack-wide `count`, and
`InspectionRunSearchResult` types.
- `packages/shared/src/run-diagnostics.ts` &
`packages/shared/src/index.ts`: add closed-vocabulary
`RUN_PLATFORM_DIAGNOSTIC_CODES` and deterministic
`detectRunPlatformDiagnostics()`.
- `server/src/services/customer-success-run-search.ts`: implement
bounded read-only `searchCustomerSuccessRuns()` with in-DB `strpos`
event matching, overlap-window `RunLogStore` fallback, co-occurrence
tracking, diagnostic aggregation, and opt-in secret-redacted excerpts.
- `server/src/services/customer-success-inspection.ts` &
`server/src/routes/customer-success.ts`: mount `/read-v3`, enforce
versioned path gating, support stack-wide `count`, and attach
`diagnostics` to `runs` `view: "summary"`.
- `server/src/services/run-platform-diagnostics.ts`,
`server/src/services/native-runtime/paperclip-control-plane-port.ts`,
`server/src/services/agent-task-run-telemetry.ts`,
`server/src/services/native-runtime/native-run-log-export.ts`: detect
and deduplicate `platform.diagnostic` run events, exclude them from PRP
log export, and emit bounded PII-free Cloud reports when configured.
- `server/src/__tests__/customer-success.test.ts`,
`server/src/__tests__/run-platform-diagnostics.test.ts`,
`server/src/__tests__/customer-success-cloud.test.ts`,
`server/src/__tests__/openapi-routes.test.ts`,
`doc/CUSTOMER-SUCCESS-INSPECTION.md`: unit tests, coordinated PostgreSQL
qualification coverage, OpenAPI route list update, and documentation.

## Verification

- `pnpm --filter @paperclipai/shared build && pnpm --filter
@paperclipai/shared typecheck && pnpm --filter @paperclipai/server
typecheck` — passed.
- `cd server && pnpm exec vitest run
src/__tests__/customer-success.test.ts
src/__tests__/run-platform-diagnostics.test.ts
src/__tests__/openapi-routes.test.ts` — 78/78 passed.
- `cd server && PAPERCLIP_INSPECTION_CLOUD_DIST=<cloud-dist> pnpm exec
vitest run src/__tests__/customer-success-cloud.test.ts` — passed
end-to-end against two live PostgreSQL databases, verifying `/read-v3`
`runs.search`, `diagnostics` in run summaries, default non-waking fleet
queries, and `fleet.diagnostics`.

## Risks

- Low risk. All inspection reads remain inside repeatable-read,
read-only transactions behind EdDSA Cloud permits and replay fencing.
- Older tenants without `/read-v3` answer 404, so Cloud fails closed
with `tenant_inspection_version_unsupported` during rolling upgrades.
- `platform.diagnostic` rows stay in the instance database
(`heartbeat_run_events`); Cloud reporting is a no-op unless Cloud
explicitly delivers `PAPERCLIP_RUNTIME_DIAGNOSTICS_CAPABILITY`, and
emits only closed enum codes and run/driver metadata (never customer
prose).

## Model Used

- Google Gemini 4 Neon (High) in Antigravity with tool use (shell, file
editing, test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-11-30 14:44:08 +00:00
1 parent bc98abda0c
commit 2d764bebc6
17 files changed
+2446 -30

No files matched your search

+139 -1
View File
@@ -6,6 +6,10 @@ export const INSPECTION_HEADER = "x-paperclip-cloud-inspection";
export const CHALLENGE_DOMAIN = "paperclip-customer-success-challenge/v1\n";
export const MAX_INSPECTION_BYTES = 1024 * 1024;
export const MAX_INSPECTION_ROWS = 100;
export const MAX_INSPECTION_SEARCH_PATTERNS = 5;
export const MAX_INSPECTION_PATTERN_LENGTH = 200;
export const MAX_INSPECTION_SEARCH_RUNS = 200;
export const MAX_INSPECTION_SEARCH_SAMPLE_RUNS = 10;
export const INSPECTION_RESOURCES = [
"companies",
"goals",
@@ -77,11 +81,47 @@ export const INSPECTION_READ_PATH = "/read";
* `tenant_inspection_version_unsupported` instead of misreading the query.
*/
export const INSPECTION_EXTENDED_READ_PATH = "/read-v2";
/**
* The tenant path for `runs.search` and stack-wide `count` (omitting `companyId`).
* A tenant predating these answers 404 here, so Cloud classifies it as
* `tenant_inspection_version_unsupported` instead of misreading the query.
*/
export const INSPECTION_SEARCH_READ_PATH = "/read-v3";
export interface InspectionCount {
total: number;
/** Counts grouped by the resource's `status` column, or null when it has none. */
byStatus: Record<string, number> | null;
}
export interface InspectionRunSearchSample {
runId: string;
companyId: string;
status: string;
driverKind: string | null;
runtimeMode: string;
createdAt: string;
diagnostics: string[];
excerpt?: string;
}
export interface InspectionRunSearchPatternHit {
pattern: string;
matchedRuns: number;
byStatus: Record<string, number>;
byDriver: Record<string, number>;
byRuntimeMode: Record<string, number>;
firstSeenAt: string | null;
lastSeenAt: string | null;
sampleRuns: InspectionRunSearchSample[];
}
export interface InspectionRunSearchResult {
runsScanned: number;
runsTotalInWindow: number;
truncated: boolean;
byStatus: Record<string, number>;
byDriver: Record<string, number>;
byDiagnostic: Record<string, number>;
patterns: InspectionRunSearchPatternHit[];
coOccurrence: Array<{ patterns: string[]; matchedRuns: number }>;
}
export interface InspectionQuery {
operation:
| "list"
@@ -90,6 +130,7 @@ export interface InspectionQuery {
| "instructions.file"
| "skills.file"
| "runs.log"
| "runs.search"
| "files.list"
| "files.read"
| "files.download"
@@ -107,6 +148,16 @@ export interface InspectionQuery {
order?: InspectionOrder;
/** `list`/`get` on `runs` only: leave out the large JSON columns. */
view?: InspectionView;
/** `runs.search` only: 1-5 literal substrings (never regex) to search for. */
patterns?: string[];
/** `runs.search` only: ISO-8601 lower bound (inclusive) on run creation time. */
createdAfter?: string;
/** `runs.search` only: ISO-8601 upper bound (exclusive) on run creation time. */
createdBefore?: string;
/** `runs.search` only: literal match case sensitivity (default false). */
caseSensitive?: boolean;
/** `runs.search` with `companyId` only: include one short redacted excerpt per sample hit. */
includeExcerpts?: boolean;
context?: {
projectId?: string;
workspaceId?: string;
@@ -152,10 +203,22 @@ export function canonicalJson(value: unknown): string {
throw new Error("Invalid JSON value");
}
export function inspectionReadPath(query: InspectionQuery): string {
if (
query.operation === "runs.search" ||
(query.operation === "count" && query.companyId === undefined)
) {
return INSPECTION_SEARCH_READ_PATH;
}
return query.operation === "count" || query.order !== undefined || query.view !== undefined
? INSPECTION_EXTENDED_READ_PATH
: INSPECTION_READ_PATH;
}
function parseIsoTimestamp(value: unknown, field: string): number {
if (typeof value !== "string" || value.length > 64) throw new Error(`Invalid ${field}`);
const parsed = Date.parse(value);
if (!Number.isFinite(parsed)) throw new Error(`Invalid ${field}`);
return parsed;
}
export function parseInspectionQuery(value: unknown): InspectionQuery {
if (!value || typeof value !== "object" || Array.isArray(value))
throw new Error("Invalid inspection query");
@@ -173,6 +236,11 @@ export function parseInspectionQuery(value: unknown): InspectionQuery {
"range",
"order",
"view",
"patterns",
"createdAfter",
"createdBefore",
"caseSensitive",
"includeExcerpts",
"context",
]);
if (Object.keys(q).some((k) => !allowed.has(k)))
@@ -185,6 +253,7 @@ export function parseInspectionQuery(value: unknown): InspectionQuery {
"instructions.file",
"skills.file",
"runs.log",
"runs.search",
"files.list",
"files.read",
"files.download",
@@ -198,10 +267,79 @@ export function parseInspectionQuery(value: unknown): InspectionQuery {
}
if (q.resource !== undefined && !INSPECTION_RESOURCES.includes(q.resource))
throw new Error("Unsupported inspection resource");
const isSearch = q.operation === "runs.search";
if (isSearch) {
for (const forbidden of [
"resource",
"resourceId",
"parentId",
"path",
"versionId",
"offset",
"range",
"order",
"view",
"context",
] as const) {
if (q[forbidden] !== undefined) throw new Error(`${forbidden} does not apply to runs.search`);
}
if (
!Array.isArray(q.patterns) ||
q.patterns.length < 1 ||
q.patterns.length > MAX_INSPECTION_SEARCH_PATTERNS
)
throw new Error("runs.search requires 1 to 5 literal patterns");
const seen = new Set<string>();
for (const pattern of q.patterns) {
if (
typeof pattern !== "string" ||
pattern.trim().length === 0 ||
pattern.length > MAX_INSPECTION_PATTERN_LENGTH ||
pattern.includes("\0")
)
throw new Error("Invalid search pattern");
const key = q.caseSensitive ? pattern : pattern.toLowerCase();
if (seen.has(key)) throw new Error("Duplicate search pattern");
seen.add(key);
}
const after =
q.createdAfter !== undefined ? parseIsoTimestamp(q.createdAfter, "createdAfter") : undefined;
const before =
q.createdBefore !== undefined
? parseIsoTimestamp(q.createdBefore, "createdBefore")
: undefined;
if (after !== undefined && before !== undefined && before <= after)
throw new Error("createdBefore must be after createdAfter");
if (q.caseSensitive !== undefined && typeof q.caseSensitive !== "boolean")
throw new Error("Invalid caseSensitive");
if (q.includeExcerpts !== undefined && typeof q.includeExcerpts !== "boolean")
throw new Error("Invalid includeExcerpts");
if (q.includeExcerpts === true && !q.companyId)
throw new Error("includeExcerpts requires companyId");
if (
q.limit !== undefined &&
(!Number.isSafeInteger(q.limit) || q.limit < 1 || q.limit > MAX_INSPECTION_SEARCH_RUNS)
)
throw new Error("Invalid limit");
return JSON.parse(canonicalJson(q)) as InspectionQuery;
}
for (const searchOnly of [
"patterns",
"createdAfter",
"createdBefore",
"caseSensitive",
"includeExcerpts",
] as const) {
if (q[searchOnly] !== undefined) throw new Error(`${searchOnly} applies only to runs.search`);
}
if (q.operation === "get" && !q.resourceId) throw new Error("resourceId required");
if (["get", "list", "count"].includes(q.operation) && !q.resource)
throw new Error("resource required");
if (!(q.operation === "list" && q.resource === "companies") && !q.companyId)
if (
!(q.operation === "list" && q.resource === "companies") &&
q.operation !== "count" &&
!q.companyId
)
throw new Error("companyId required");
if (!["get", "list", "count"].includes(q.operation) && !q.resourceId)
throw new Error("resourceId required");
+1
View File
@@ -3155,6 +3155,7 @@ export { readBoardBootstrap } from "./board-bootstrap.js";
export * from "./provider-rate-limits.js";
export * from "./agent-interaction-permissions.js";
export * from "./run-failure-cause.js";
export * from "./run-diagnostics.js";
export {
TASK_IDENTITY_CHANGED_FIELD,
issueActivityChangesTaskIdentity,
+70
View File
@@ -0,0 +1,70 @@
/**
* Closed vocabulary of platform-owned runtime diagnostic codes observed inside
* agent runs, including runs whose outer process still exited 0 ("succeeded").
*
* Privacy boundary: these codes are fixed, low-cardinality platform identifiers.
* Never add customer text, paths, commands, or arbitrary error messages here.
*/
export const RUN_PLATFORM_DIAGNOSTIC_CODES = [
"git_storage_guard_unavailable",
"git_storage_limit",
"github_capability_missing",
"github_capability_rejected",
"github_broker_unavailable",
"sandbox_disk_full",
] as const;
export type RunPlatformDiagnosticCode = (typeof RUN_PLATFORM_DIAGNOSTIC_CODES)[number];
const DIAGNOSTIC_CODE_SET = new Set<string>(RUN_PLATFORM_DIAGNOSTIC_CODES);
export function isRunPlatformDiagnosticCode(value: unknown): value is RunPlatformDiagnosticCode {
return typeof value === "string" && DIAGNOSTIC_CODE_SET.has(value);
}
const GIT_STORAGE_DISK_RE =
/paperclip_git_storage_limit:[^\n]*(?:too little free disk space|too few free inodes)/i;
const GIT_STORAGE_BUDGET_RE =
/paperclip_git_storage_limit:[^\n]*stopped at its storage budget/i;
const GIT_STORAGE_GUARD_UNAVAILABLE_RE =
/paperclip_git_storage_limit:[^\n]*(?:unavailable or misconfigured|cannot verify available sandbox storage)|\b(?:reason=git_storage_guard_unavailable|git=storage_guard_unavailable)\b/i;
const GITHUB_CAPABILITY_MISSING_RE = /Paperclip:\s*GitHub\s+capability_missing\b/i;
const GITHUB_CAPABILITY_REJECTED_RE = /Paperclip:\s*GitHub\s+capability_rejected\b/i;
const GITHUB_BROKER_UNAVAILABLE_RE =
/Paperclip:\s*GitHub\s+(?:broker_response_unavailable\b|credential service is not reachable)/i;
const SANDBOX_DISK_FULL_RE =
/\bremote_workspace_sandbox_disk_full\b|sandbox[^\n]*(?:\bENOSPC\b|\bEDQUOT\b|No space left on device|Disk quota exceeded)/i;
/**
* Classify known platform guard/launcher diagnostic messages from run text.
* Pure and deterministic; returns sorted unique diagnostic codes.
*/
export function detectRunPlatformDiagnostics(text: string): RunPlatformDiagnosticCode[] {
if (!text) return [];
const found = new Set<RunPlatformDiagnosticCode>();
if (GIT_STORAGE_DISK_RE.test(text)) {
found.add("git_storage_limit");
found.add("sandbox_disk_full");
}
if (GIT_STORAGE_BUDGET_RE.test(text)) {
found.add("git_storage_limit");
}
if (GIT_STORAGE_GUARD_UNAVAILABLE_RE.test(text)) {
found.add("git_storage_guard_unavailable");
}
if (GITHUB_CAPABILITY_MISSING_RE.test(text)) {
found.add("github_capability_missing");
}
if (GITHUB_CAPABILITY_REJECTED_RE.test(text)) {
found.add("github_capability_rejected");
}
if (GITHUB_BROKER_UNAVAILABLE_RE.test(text)) {
found.add("github_broker_unavailable");
}
if (SANDBOX_DISK_FULL_RE.test(text)) {
found.add("sandbox_disk_full");
}
return [...found].sort();
}