Files
PaperClipAI/server/src/services/run-platform-diagnostics.ts
T
DottaandPaperclip 2d764bebc6 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>
2026-11-30 14:44:08 +00:00

348 lines
11 KiB
TypeScript

import { and, eq, inArray, sql } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { heartbeatRunEvents, heartbeatRuns } from "@paperclipai/db";
import {
detectRunPlatformDiagnostics,
isRunPlatformDiagnosticCode,
RUN_PLATFORM_DIAGNOSTIC_CODES,
type RunPlatformDiagnosticCode,
} from "@paperclipai/shared";
import { appendHeartbeatRunEvent } from "./heartbeat-run-events.js";
import { logger } from "../middleware/logger.js";
export const RUN_PLATFORM_DIAGNOSTIC_EVENT_TYPE = "platform.diagnostic";
export const RUN_PLATFORM_DIAGNOSTIC_SOURCE_PREFIX = "platform-diagnostic:";
export const RUNTIME_DIAGNOSTICS_CAPABILITY_ENV = "PAPERCLIP_RUNTIME_DIAGNOSTICS_CAPABILITY";
const STACK_HOST_HEADER = "x-paperclip-cloud-tenant-host";
const STACK_DIAGNOSTICS_PATH = "/v1/customer-success/stack/diagnostics";
const MAX_SCAN_TEXT_BYTES = 256 * 1024;
const DIAGNOSTIC_REPORT_TIMEOUT_MS = 5_000;
function collectTextFragments(value: unknown, out: string[], remaining: { bytes: number }): void {
if (remaining.bytes <= 0 || value == null) return;
if (typeof value === "string") {
const slice = value.length > remaining.bytes ? value.slice(0, remaining.bytes) : value;
remaining.bytes -= slice.length;
out.push(slice);
return;
}
if (Array.isArray(value)) {
for (const item of value) {
collectTextFragments(item, out, remaining);
if (remaining.bytes <= 0) break;
}
return;
}
if (typeof value === "object") {
const record = value as Record<string, unknown>;
for (const key of [
"aggregatedOutput",
"output",
"stderr",
"stdout",
"text",
"delta",
"message",
"error",
"detail",
"reason",
]) {
if (key in record) collectTextFragments(record[key], out, remaining);
}
for (const nestedKey of ["prpEvent", "payload", "item", "result", "update", "providerFailure"]) {
if (nestedKey in record && typeof record[nestedKey] === "object" && record[nestedKey] !== null) {
collectTextFragments(record[nestedKey], out, remaining);
}
}
}
}
/**
* Inspect a single persisted run event for closed-vocabulary platform diagnostics.
* Returns sorted unique codes; returns empty quickly for streaming deltas that
* do not carry known markers.
*/
export function extractRunPlatformDiagnosticsFromEvent(
eventType: string,
message: string | null | undefined,
payload: Record<string, unknown> | null | undefined,
): RunPlatformDiagnosticCode[] {
if (eventType === RUN_PLATFORM_DIAGNOSTIC_EVENT_TYPE) return [];
const fragments: string[] = [];
const budget = { bytes: MAX_SCAN_TEXT_BYTES };
if (message) collectTextFragments(message, fragments, budget);
if (payload) collectTextFragments(payload, fragments, budget);
if (fragments.length === 0) return [];
return detectRunPlatformDiagnostics(fragments.join("\n"));
}
export interface RecordRunPlatformDiagnosticsInput {
companyId: string;
runId: string;
agentId: string;
codes: readonly RunPlatformDiagnosticCode[];
runStatus?: string | null;
driverKind?: string | null;
runtimeMode?: string | null;
occurredAt?: Date;
}
/**
* Persist deduplicated `platform.diagnostic` rows into `heartbeat_run_events`
* (idempotent per `(runId, code)` via the existing unique `sourceEventId` index)
* and, when running in Cloud with a diagnostics stack capability, emit a
* bounded, PII-free summary to Paperclip Cloud.
*/
export async function recordRunPlatformDiagnostics(
db: Db,
input: RecordRunPlatformDiagnosticsInput,
options: {
env?: NodeJS.ProcessEnv;
fetcher?: typeof fetch;
reportToCloud?: boolean;
} = {},
): Promise<RunPlatformDiagnosticCode[]> {
const uniqueCodes = [...new Set(input.codes)].filter(isRunPlatformDiagnosticCode).sort();
if (uniqueCodes.length === 0) return [];
const recorded: RunPlatformDiagnosticCode[] = [];
for (const code of uniqueCodes) {
// Stable per-code sequence so separate calls on the same run for different
// codes never collide on the native (sourceInstanceId, sourceSeq) replay key.
const sourceSeq = RUN_PLATFORM_DIAGNOSTIC_CODES.indexOf(code) + 1;
if (sourceSeq <= 0) continue;
try {
const result = await appendHeartbeatRunEvent(db, {
companyId: input.companyId,
runId: input.runId,
agentId: input.agentId,
eventType: RUN_PLATFORM_DIAGNOSTIC_EVENT_TYPE,
stream: "system",
level: "warn",
message: code,
payload: {
code,
...(input.driverKind ? { driverKind: input.driverKind } : {}),
...(input.runtimeMode ? { runtimeMode: input.runtimeMode } : {}),
},
nativeSource: {
sourceInstanceId: `${input.runId}:platform-diagnostic`,
sourceEventId: `${RUN_PLATFORM_DIAGNOSTIC_SOURCE_PREFIX}${code}`,
sourceSeq,
protocolSchemaVersion: 1,
canonicalPayload: { code },
},
});
if (result.disposition === "committed") recorded.push(code);
} catch (err) {
logger.warn({ err, runId: input.runId, code }, "failed to persist platform.diagnostic event");
}
}
if (options.reportToCloud !== false && recorded.length > 0) {
await sendRunPlatformDiagnosticsToCloud(
{
runId: input.runId,
diagnosticCodes: recorded,
runStatus: input.runStatus ?? "running",
driverKind: input.driverKind ?? null,
runtimeMode: input.runtimeMode ?? "native",
occurredAt: (input.occurredAt ?? new Date()).toISOString(),
},
options,
);
}
return recorded;
}
export interface CloudDiagnosticReportPayload {
runId: string;
diagnosticCodes: RunPlatformDiagnosticCode[];
runStatus: string;
driverKind: string | null;
runtimeMode: string;
occurredAt: string;
}
/**
* Fire-and-forget PII-free report to Paperclip Cloud's stack-authenticated
* diagnostics endpoint. Never throws; no-ops outside Cloud.
*/
export async function sendRunPlatformDiagnosticsToCloud(
payload: CloudDiagnosticReportPayload,
options: { env?: NodeJS.ProcessEnv; fetcher?: typeof fetch } = {},
): Promise<boolean> {
const env = options.env ?? process.env;
const originRaw = env.PAPERCLIP_CLOUD_API_ORIGIN?.trim();
const host = env.PAPERCLIP_PRIMARY_HOST?.trim();
const capability = env[RUNTIME_DIAGNOSTICS_CAPABILITY_ENV]?.trim();
if (!originRaw || !host || !capability || payload.diagnosticCodes.length === 0) return false;
let origin: string;
try {
const parsed = new URL(originRaw);
if (
parsed.protocol !== "https:" &&
!(parsed.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname))
) {
return false;
}
origin = parsed.origin;
} catch {
return false;
}
try {
const response = await (options.fetcher ?? fetch)(`${origin}${STACK_DIAGNOSTICS_PATH}`, {
method: "POST",
headers: {
authorization: `Bearer ${capability}`,
[STACK_HOST_HEADER]: host,
"content-type": "application/json",
},
body: JSON.stringify(payload),
redirect: "error",
signal: AbortSignal.timeout(DIAGNOSTIC_REPORT_TIMEOUT_MS),
});
return response.ok;
} catch (err) {
logger.warn({ err, runId: payload.runId }, "failed to send platform diagnostics to Cloud");
return false;
}
}
/**
* Batch-load recorded platform diagnostic codes for a set of runs.
* Used by customer-success `view: "summary"` and `runs.search`.
*/
export async function listRunPlatformDiagnostics(
db: Db,
runIds: readonly string[],
companyId?: string,
): Promise<Map<string, RunPlatformDiagnosticCode[]>> {
const byRun = new Map<string, RunPlatformDiagnosticCode[]>();
if (runIds.length === 0) return byRun;
const predicates = [
inArray(heartbeatRunEvents.runId, [...runIds]),
eq(heartbeatRunEvents.eventType, RUN_PLATFORM_DIAGNOSTIC_EVENT_TYPE),
];
if (companyId) predicates.push(eq(heartbeatRunEvents.companyId, companyId));
const rows = await db
.select({
runId: heartbeatRunEvents.runId,
code: sql<string | null>`${heartbeatRunEvents.payload}->>'code'`,
})
.from(heartbeatRunEvents)
.where(and(...predicates));
const sets = new Map<string, Set<RunPlatformDiagnosticCode>>();
for (const row of rows) {
if (!isRunPlatformDiagnosticCode(row.code)) continue;
let set = sets.get(row.runId);
if (!set) {
set = new Set();
sets.set(row.runId, set);
}
set.add(row.code);
}
for (const [runId, set] of sets) {
byRun.set(runId, [...set].sort());
}
return byRun;
}
/**
* Finalize diagnostic recording when a run reaches a terminal state (including
* `succeeded`), catching errors from `heartbeat_runs` columns and ensuring Cloud
* receives the run's terminal `runStatus`, `driverKind`, and `runtimeMode`.
*/
export async function reportFinalizedRunDiagnostics(
db: Db,
run: {
id: string;
companyId: string;
agentId: string;
status: string;
error?: string | null;
stderrExcerpt?: string | null;
driverKind?: string | null;
runtimeMode?: string | null;
finishedAt?: Date | null;
},
options: { env?: NodeJS.ProcessEnv; fetcher?: typeof fetch } = {},
): Promise<RunPlatformDiagnosticCode[]> {
try {
const needsReload =
run.error === undefined ||
run.stderrExcerpt === undefined ||
run.driverKind === undefined ||
run.runtimeMode === undefined;
let errorText: string | null = run.error ?? null;
let stderrText: string | null = run.stderrExcerpt ?? null;
let driverKind: string | null = run.driverKind ?? null;
let runtimeMode: string | null = run.runtimeMode ?? null;
if (needsReload) {
const [row] = await db
.select({
error: heartbeatRuns.error,
stderrExcerpt: heartbeatRuns.stderrExcerpt,
driverKind: heartbeatRuns.driverKind,
runtimeMode: heartbeatRuns.runtimeMode,
})
.from(heartbeatRuns)
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId)))
.limit(1);
if (row) {
if (run.error === undefined) errorText = row.error;
if (run.stderrExcerpt === undefined) stderrText = row.stderrExcerpt;
if (run.driverKind === undefined) driverKind = row.driverKind;
if (run.runtimeMode === undefined) runtimeMode = row.runtimeMode;
}
}
const detected = detectRunPlatformDiagnostics([errorText ?? "", stderrText ?? ""].join("\n"));
const existing = (await listRunPlatformDiagnostics(db, [run.id], run.companyId)).get(run.id) ?? [];
const combined = [...new Set([...existing, ...detected])].sort();
if (combined.length === 0) return [];
// Persist any newly detected codes (e.g. from run.error / legacy stderrExcerpt).
if (detected.some((code) => !existing.includes(code))) {
await recordRunPlatformDiagnostics(
db,
{
companyId: run.companyId,
runId: run.id,
agentId: run.agentId,
codes: detected,
runStatus: run.status,
driverKind,
runtimeMode,
occurredAt: run.finishedAt ?? new Date(),
},
{ ...options, reportToCloud: false },
);
}
await sendRunPlatformDiagnosticsToCloud(
{
runId: run.id,
diagnosticCodes: combined,
runStatus: run.status,
driverKind,
runtimeMode: runtimeMode ?? "legacy",
occurredAt: (run.finishedAt ?? new Date()).toISOString(),
},
options,
);
return combined;
} catch (err) {
logger.warn({ err, runId: run.id }, "failed to finalize run platform diagnostics");
return [];
}
}