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

@@ -7,12 +7,13 @@ import { parseObject } from "../adapters/utils.js";
import { logger } from "../middleware/logger.js";
import { getTelemetryClient } from "../telemetry.js";
import { resolveTelemetryPerson, withTelemetryActor } from "../telemetry-company-scope.js";
import { reportFinalizedRunDiagnostics } from "./run-platform-diagnostics.js";
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
type TelemetryRun = Pick<HeartbeatRun,
"id" | "companyId" | "agentId" | "status" | "startedAt" | "finishedAt" | "usageJson" | "contextSnapshot"
| "errorCode" | "resultJson">
& Partial<Pick<HeartbeatRun, "responsibleUserId">>;
& Partial<Pick<HeartbeatRun, "responsibleUserId" | "error" | "stderrExcerpt" | "driverKind" | "runtimeMode">>;
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -205,6 +206,7 @@ function resolveDurationSeconds(
* remove the delay.
*/
export async function emitAgentTaskRun(db: Db, run: TelemetryRun): Promise<void> {
void reportFinalizedRunDiagnostics(db, run);
try {
const client = getTelemetryClient();
if (!client) return;
@@ -310,6 +312,10 @@ export async function emitAgentTaskRunById(
responsibleUserId: heartbeatRuns.responsibleUserId,
contextSnapshot: sql<Record<string, unknown>>`jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId')`,
errorCode: heartbeatRuns.errorCode,
error: heartbeatRuns.error,
stderrExcerpt: heartbeatRuns.stderrExcerpt,
driverKind: heartbeatRuns.driverKind,
runtimeMode: heartbeatRuns.runtimeMode,
resultJson: sql<Record<string, unknown> | null>`jsonb_build_object('providerFailure', jsonb_build_object('category', ${heartbeatRuns.resultJson}->'providerFailure'->'category'))`,
})
.from(heartbeatRuns)
@@ -26,6 +26,8 @@ import { createSavedWorkspaceLoader } from "./remote-workspaces.js";
import { createSavedWorkspaceArchiveOpener } from "./saved-workspace-archive.js";
import { environmentRuntimeService } from "./environment-runtime.js";
import type { PluginWorkerManager } from "./plugin-worker-manager.js";
import { searchCustomerSuccessRuns } from "./customer-success-run-search.js";
import { listRunPlatformDiagnostics } from "./run-platform-diagnostics.js";
export interface CustomerSuccessInspectionOptions {
pluginWorkerManager?: PluginWorkerManager;
@@ -190,6 +192,11 @@ export async function readCustomerSuccessResource(
q: InspectionQuery,
options: CustomerSuccessInspectionOptions = {},
): Promise<unknown> {
// runs.search manages its own read-only repeatable-read DB transaction so
// fallback RunLogStore reads happen cleanly outside any open DB transaction.
if (q.operation === "runs.search") {
return searchCustomerSuccessRuns(db, q);
}
return db.transaction(
async (rawTx) => {
const tx = rawTx as unknown as Db;
@@ -211,15 +218,12 @@ export async function readCustomerSuccessResource(
if (q.companyId) predicates.push(eq(all.id, q.companyId));
} else if (q.resource === "users") {
// Directory only, never the authentication account/session tables.
const membershipPredicates = [eq(schema.companyMemberships.principalType, "user")];
if (q.companyId) membershipPredicates.push(eq(schema.companyMemberships.companyId, q.companyId));
const memberships = await tx
.select({ userId: schema.companyMemberships.principalId })
.selectDistinct({ userId: schema.companyMemberships.principalId })
.from(schema.companyMemberships)
.where(
and(
eq(schema.companyMemberships.companyId, q.companyId!),
eq(schema.companyMemberships.principalType, "user"),
),
);
.where(and(...membershipPredicates));
const { inArray } = await import("drizzle-orm");
if (!memberships.length) {
if (q.operation === "get") throw notFound("Inspection resource not found");
@@ -234,7 +238,7 @@ export async function readCustomerSuccessResource(
);
} else {
if (!all.companyId) throw unprocessable("Reader has no company boundary");
predicates.push(eq(all.companyId, q.companyId!));
if (q.companyId) predicates.push(eq(all.companyId, q.companyId));
}
if (q.operation === "get" && !all[reader.id ?? "id"])
throw unprocessable("This resource supports listing only");
@@ -327,7 +331,15 @@ export async function readCustomerSuccessResource(
q.companyId!,
rows as Array<{ id: string }>,
);
if (q.view === "summary") rows = rows.map((r) => ({ ...r, durationMs: durationMs(r) }));
if (q.view === "summary") {
const summaryRunIds = rows.map((r) => String(r.id));
const diagnosticsByRun = await listRunPlatformDiagnostics(tx, summaryRunIds, q.companyId);
rows = rows.map((r) => ({
...r,
durationMs: durationMs(r),
diagnostics: diagnosticsByRun.get(String(r.id)) ?? [],
}));
}
// Match the existing structured event/config redaction, without scanning
// prose, documents, instructions, skill contents, or workspace files.
if (
@@ -0,0 +1,800 @@
import { and, desc, eq, gte, inArray, lt, sql, type SQL } from "drizzle-orm";
import * as schema from "@paperclipai/db";
import type { Db } from "@paperclipai/db";
import {
MAX_INSPECTION_SEARCH_RUNS,
MAX_INSPECTION_SEARCH_SAMPLE_RUNS,
withoutSqlStatementText,
type InspectionQuery,
type InspectionRunSearchPatternHit,
type InspectionRunSearchResult,
type InspectionRunSearchSample,
} from "@paperclipai/shared";
import { notFound } from "../errors.js";
import { REDACTED_EVENT_VALUE, redactEventPayload } from "../redaction.js";
import {
createRunSecretRedactionRegistry,
redactRegisteredSecretValues,
} from "./run-secret-redaction.js";
import { getRunLogStore, isRunLogStoreType, type RunLogStore } from "./run-log-store.js";
import { listRunPlatformDiagnostics } from "./run-platform-diagnostics.js";
const DEFAULT_SEARCH_RUN_LIMIT = 100;
const MAX_COUNTED_RUNS_IN_WINDOW = 10_000;
const SEARCH_WALL_BUDGET_MS = 6_000;
const LOG_CHUNK_BYTES = 128 * 1024;
const MAX_LOG_BYTES_PER_RUN = 2 * 1024 * 1024;
const MAX_TOTAL_LOG_BYTES = 12 * 1024 * 1024;
const MAX_EXCERPT_CHARS = 240;
type RunTextRedactor = {
redact: (text: string) => string;
redactObject: <T>(value: T) => T;
maxSecretLen: number;
};
function increment(map: Record<string, number>, key: string): void {
map[key] = (map[key] ?? 0) + 1;
}
function findLiteralIndex(haystack: string, needle: string, caseSensitive: boolean): number {
if (!haystack || !needle) return -1;
return caseSensitive
? haystack.indexOf(needle)
: haystack.toLowerCase().indexOf(needle.toLowerCase());
}
/**
* Redact the full decoded source text BEFORE choosing, slicing, or collapsing
* whitespace for the excerpt so registered secrets crossing excerpt boundaries
* or spanning multiple lines can never leak partial fragments.
*/
function extractRedactedExcerpt(
rawSource: string,
needle: string,
caseSensitive: boolean,
redactor: RunTextRedactor,
): string | undefined {
if (!rawSource || findLiteralIndex(rawSource, needle, caseSensitive) < 0) return undefined;
// Remove complete registered secret values FIRST before structural redaction can
// alter any substring inside them, then apply structural redaction to catch any
// unregistered credentials/tokens before choosing or slicing the excerpt window.
const afterRegistered = redactor.redact(rawSource);
const redacted = String(redactEventPayload({ text: afterRegistered })?.text ?? afterRegistered);
let idx = findLiteralIndex(redacted, needle, caseSensitive);
if (idx < 0) {
// Pattern overlapped a redacted secret; center around the redaction marker.
idx = redacted.indexOf(REDACTED_EVENT_VALUE);
if (idx < 0) idx = 0;
}
const radius = Math.floor((MAX_EXCERPT_CHARS - Math.min(needle.length, MAX_EXCERPT_CHARS / 2)) / 2);
const start = Math.max(0, idx - Math.max(20, radius));
const end = Math.min(redacted.length, start + MAX_EXCERPT_CHARS);
const snippet = redacted.slice(start, end).replace(/\s+/g, " ").trim();
const prefix = start > 0 ? "…" : "";
const suffix = end < redacted.length ? "…" : "";
return `${prefix}${snippet}${suffix}`;
}
function isStatementTimeoutError(err: unknown): boolean {
if (!err || typeof err !== "object") return false;
const record = err as { code?: unknown; cause?: { code?: unknown } };
return record.code === "57014" || record.cause?.code === "57014";
}
function buildEventMatchCondition(pattern: string, caseSensitive: boolean): SQL {
const jsonInner = JSON.stringify(pattern).slice(1, -1);
if (caseSensitive) {
if (jsonInner === pattern) {
return sql`(strpos(coalesce(${schema.heartbeatRunEvents.message}, ''), ${pattern}) > 0 OR strpos(coalesce(${schema.heartbeatRunEvents.payload}::text, ''), ${pattern}) > 0)`;
}
return sql`(strpos(coalesce(${schema.heartbeatRunEvents.message}, ''), ${pattern}) > 0 OR strpos(coalesce(${schema.heartbeatRunEvents.payload}::text, ''), ${pattern}) > 0 OR strpos(coalesce(${schema.heartbeatRunEvents.payload}::text, ''), ${jsonInner}) > 0)`;
}
if (jsonInner === pattern) {
return sql`(strpos(lower(coalesce(${schema.heartbeatRunEvents.message}, '')), lower(${pattern})) > 0 OR strpos(lower(coalesce(${schema.heartbeatRunEvents.payload}::text, '')), lower(${pattern})) > 0)`;
}
return sql`(strpos(lower(coalesce(${schema.heartbeatRunEvents.message}, '')), lower(${pattern})) > 0 OR strpos(lower(coalesce(${schema.heartbeatRunEvents.payload}::text, '')), lower(${pattern})) > 0 OR strpos(lower(coalesce(${schema.heartbeatRunEvents.payload}::text, '')), lower(${jsonInner})) > 0)`;
}
function collectDecodedStrings(value: unknown, out: string[]): void {
if (value == null) return;
if (typeof value === "string") {
if (value.length > 0) out.push(value);
return;
}
if (Array.isArray(value)) {
for (const item of value) collectDecodedStrings(item, out);
return;
}
if (typeof value === "object") {
for (const v of Object.values(value as Record<string, unknown>)) {
collectDecodedStrings(v, out);
}
}
}
function findDecodedEventMatch(
message: string | null | undefined,
payload: unknown,
pattern: string,
caseSensitive: boolean,
redactor: RunTextRedactor | null = null,
): string | undefined {
// Remove complete registered secret values FIRST (when excerpts are requested)
// before structural redaction runs, then apply structural event redaction so
// unregistered secret-named fields, JWTs, and embedded command credentials never
// match or leak via excerpts.
const rawEvent: Record<string, unknown> = {
...(typeof message === "string" ? { message } : {}),
...(payload && typeof payload === "object" && !Array.isArray(payload)
? { payload: payload as Record<string, unknown> }
: {}),
};
const afterRegistered = redactor ? redactor.redactObject(rawEvent) : rawEvent;
const redactedEvent = redactEventPayload(afterRegistered);
const safeMessage = typeof redactedEvent?.message === "string" ? redactedEvent.message : null;
if (safeMessage && findLiteralIndex(safeMessage, pattern, caseSensitive) >= 0) {
return safeMessage;
}
const strings: string[] = [];
collectDecodedStrings(redactedEvent?.payload, strings);
for (const text of strings) {
if (findLiteralIndex(text, pattern, caseSensitive) >= 0) return text;
}
return undefined;
}
/**
* Decode complete NDJSON run-log lines into their literal `chunk` payloads so
* callers can search literal quotes, backslashes, and newlines rather than JSON
* escape sequences. Non-JSON lines fall back to their literal text.
*/
function decodeNdjsonChunkText(content: string): string {
const parts: string[] = [];
for (const line of content.split("\n")) {
if (!line) continue;
const trimmed = line.endsWith("\r") ? line.slice(0, -1) : line;
if (!trimmed) continue;
if (trimmed.startsWith("{")) {
try {
const parsed = JSON.parse(trimmed) as { chunk?: unknown };
if (typeof parsed.chunk === "string") {
parts.push(parsed.chunk);
continue;
}
} catch {
// Fall back to literal line below when not valid JSON.
}
}
parts.push(trimmed);
}
return parts.join("");
}
async function readWithDeadline<T>(
promise: Promise<T>,
remainingMs: number,
controller: AbortController,
): Promise<T> {
if (remainingMs <= 0) {
controller.abort();
throw new Error("search deadline exceeded");
}
let timer: NodeJS.Timeout | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_, reject) => {
timer = setTimeout(() => {
controller.abort();
reject(new Error("search deadline exceeded"));
}, remainingMs);
timer.unref?.();
}),
]);
} finally {
if (timer) clearTimeout(timer);
}
}
async function scanRunLogForPatterns(
logStore: RunLogStore,
store: "local_file" | "s3_segments" | "s3_archive",
logRef: string,
patterns: readonly string[],
caseSensitive: boolean,
remainingIndexes: Set<number>,
redactor: RunTextRedactor | null,
budget: { bytes: number; deadlineMs: number; now: () => number },
): Promise<{
matched: Map<number, string | undefined>;
truncated: boolean;
}> {
const matched = new Map<number, string | undefined>();
if (remainingIndexes.size === 0) return { matched, truncated: false };
const maxPatternLen = Math.max(...patterns.map((p) => p.length));
const secretMargin = redactor ? redactor.maxSecretLen + MAX_EXCERPT_CHARS : 0;
// Keep enough overlap across paged log reads so neither a pattern nor a
// registered secret overlapping an excerpt window is split across page edges.
const overlapChars = Math.max(0, maxPatternLen - 1, secretMargin);
const pendingExcerpts = new Map<number, string>();
let offset = 0;
let scannedForRun = 0;
let tail = "";
let lineRemainder = "";
let truncated = false;
while (remainingIndexes.size > 0 || pendingExcerpts.size > 0) {
const remainingMs = budget.deadlineMs - budget.now();
if (remainingMs <= 0 || budget.bytes <= 0 || scannedForRun >= MAX_LOG_BYTES_PER_RUN) {
truncated = true;
break;
}
const readLimit = Math.min(LOG_CHUNK_BYTES, budget.bytes, MAX_LOG_BYTES_PER_RUN - scannedForRun);
const controller = new AbortController();
let chunk: { content: string; nextOffset?: number };
try {
chunk = await readWithDeadline(
logStore.read({ store, logRef }, { offset, limitBytes: readLimit, signal: controller.signal }),
remainingMs,
controller,
);
} catch {
truncated = true;
break;
}
if (!chunk.content) break;
// Preserve multibyte UTF-8 boundaries and whole NDJSON lines across paged reads.
let usableContent = chunk.content;
let nextOffset = chunk.nextOffset;
const isEof = nextOffset === undefined || nextOffset <= offset;
if (!isEof) {
const lastNewline = chunk.content.lastIndexOf("\n");
if (lastNewline >= 0) {
usableContent = chunk.content.slice(0, lastNewline + 1);
const usableBytes = Buffer.byteLength(usableContent, "utf8");
if (usableBytes > 0) nextOffset = offset + usableBytes;
} else if (usableContent.endsWith("\uFFFD")) {
// A multibyte UTF-8 character was cut at the page boundary. Re-encoding the
// clean prefix gives the exact byte offset where that character begins.
const cleanPrefix = usableContent.replace(/\uFFFD+$/, "");
const cleanBytes = Buffer.byteLength(cleanPrefix, "utf8");
if (cleanBytes > 0) {
usableContent = cleanPrefix;
nextOffset = offset + cleanBytes;
}
}
}
const chunkBytes = Buffer.byteLength(usableContent, "utf8");
budget.bytes -= chunkBytes;
scannedForRun += chunkBytes;
const combinedLines = lineRemainder + usableContent;
let textToDecode = "";
if (isEof) {
textToDecode = combinedLines;
lineRemainder = "";
} else {
const lastNewline = combinedLines.lastIndexOf("\n");
if (lastNewline >= 0) {
textToDecode = combinedLines.slice(0, lastNewline + 1);
lineRemainder = combinedLines.slice(lastNewline + 1);
} else if (combinedLines.length <= LOG_CHUNK_BYTES * 2) {
lineRemainder = combinedLines;
} else {
// Extremely long non-newline line: decode incrementally instead of buffering unboundedly.
textToDecode = combinedLines;
lineRemainder = "";
}
}
if (textToDecode) {
const decoded = decodeNdjsonChunkText(textToDecode);
const windowText = tail + decoded;
// Resolve any excerpts deferred from the previous page now that the right-edge
// context has arrived (or at EOF), ensuring secrets crossing the right edge
// are redacted in full before slicing.
if (redactor && pendingExcerpts.size > 0) {
for (const [idx, buffered] of [...pendingExcerpts.entries()]) {
const extended = buffered + decoded;
const pattern = patterns[idx]!;
const matchPos = findLiteralIndex(extended, pattern, caseSensitive);
const safeRightEdge =
isEof ||
(matchPos >= 0 && matchPos + pattern.length + secretMargin <= extended.length);
if (safeRightEdge) {
matched.set(idx, extractRedactedExcerpt(extended, pattern, caseSensitive, redactor));
pendingExcerpts.delete(idx);
} else if (extended.length <= MAX_EXCERPT_CHARS * 4 + secretMargin * 3) {
pendingExcerpts.set(idx, extended);
} else {
// Fail closed: omit excerpt if right-edge margin could not be bounded.
pendingExcerpts.delete(idx);
}
}
}
for (const idx of [...remainingIndexes]) {
const pattern = patterns[idx]!;
const matchPos = findLiteralIndex(windowText, pattern, caseSensitive);
if (matchPos >= 0) {
remainingIndexes.delete(idx);
if (!redactor) {
matched.set(idx, undefined);
} else if (isEof || matchPos + pattern.length + secretMargin <= windowText.length) {
matched.set(idx, extractRedactedExcerpt(windowText, pattern, caseSensitive, redactor));
} else {
// Defer excerpt until the next page supplies full right-edge secret context.
matched.set(idx, undefined);
const sliceStart = Math.max(0, matchPos - secretMargin);
pendingExcerpts.set(idx, windowText.slice(sliceStart));
}
}
}
tail = overlapChars > 0 ? windowText.slice(-overlapChars) : "";
}
if (isEof) break;
offset = nextOffset!;
}
return { matched, truncated };
}
/**
* Bounded, read-only, match-only search across a tenant stack's runs.
*
* Phase 1 runs inside a read-only repeatable-read DB transaction with a local
* statement timeout bound to the remaining search deadline: it loads candidate
* runs, runs in-database `strpos` matching over `heartbeat_run_events` (both raw
* and JSON-escaped literal forms, verified against decoded JSON strings), and
* pre-resolves run secret redactors only when `includeExcerpts: true`.
*
* Phase 2 runs OUTSIDE the database transaction so fallback `RunLogStore` reads
* (local disk or S3) never hold a DB snapshot or pool connection open, and each
* read is bounded by the remaining wall-clock deadline via `AbortSignal`.
*
* Zero customer prose leaves the stack unless `includeExcerpts: true` (which
* requires an explicit `companyId` and redacts the full decoded text before
* choosing or slicing any excerpt).
*/
export async function searchCustomerSuccessRuns(
db: Db,
q: InspectionQuery,
options: { now?: () => number; wallBudgetMs?: number; logStore?: RunLogStore } = {},
): Promise<InspectionRunSearchResult> {
const now = options.now ?? Date.now;
const wallBudgetMs = options.wallBudgetMs ?? SEARCH_WALL_BUDGET_MS;
const deadlineMs = now() + wallBudgetMs;
const patterns = q.patterns!;
const caseSensitive = q.caseSensitive === true;
const includeExcerpts = q.includeExcerpts === true;
const limit = Math.min(MAX_INSPECTION_SEARCH_RUNS, Math.max(1, q.limit ?? DEFAULT_SEARCH_RUN_LIMIT));
type CandidateRun = {
id: string;
companyId: string;
status: string;
driverKind: string | null;
runtimeMode: string;
error: string | null;
errorCode: string | null;
stderrExcerpt: string | null;
stdoutExcerpt: string | null;
logStore: string | null;
logRef: string | null;
createdAt: Date;
};
// Phase 1: Bounded DB queries inside a read-only repeatable-read transaction.
const dbPhase = await db.transaction(
async (rawTx) => {
const tx = rawTx as unknown as Db;
const statementTimeoutMs = Math.max(100, Math.min(wallBudgetMs, deadlineMs - now()));
await tx.execute(sql.raw(`SET LOCAL statement_timeout = '${Math.floor(statementTimeoutMs)}'`));
if (q.companyId) {
const [company] = await tx
.select({ id: schema.companies.id })
.from(schema.companies)
.where(eq(schema.companies.id, q.companyId));
if (!company) throw notFound("Inspection company not found");
}
const runPredicates: SQL[] = [];
if (q.companyId) runPredicates.push(eq(schema.heartbeatRuns.companyId, q.companyId));
if (q.createdAfter) runPredicates.push(gte(schema.heartbeatRuns.createdAt, new Date(q.createdAfter)));
if (q.createdBefore) runPredicates.push(lt(schema.heartbeatRuns.createdAt, new Date(q.createdBefore)));
const whereClause = runPredicates.length > 0 ? and(...runPredicates) : undefined;
// Bound the total count scan so a stack with huge history never stalls here.
const cappedSubquery = tx
.select({ one: sql<number>`1`.as("one") })
.from(schema.heartbeatRuns)
.where(whereClause)
.limit(MAX_COUNTED_RUNS_IN_WINDOW + 1)
.as("capped_runs");
const [{ total: totalRaw }] = await tx
.select({ total: sql<number>`count(*)::int` })
.from(cappedSubquery);
const countHitCap = Number(totalRaw) > MAX_COUNTED_RUNS_IN_WINDOW;
const runsTotalInWindow = Math.min(Number(totalRaw), MAX_COUNTED_RUNS_IN_WINDOW);
const runs: CandidateRun[] = await tx
.select({
id: schema.heartbeatRuns.id,
companyId: schema.heartbeatRuns.companyId,
status: schema.heartbeatRuns.status,
driverKind: schema.heartbeatRuns.driverKind,
runtimeMode: schema.heartbeatRuns.runtimeMode,
error: schema.heartbeatRuns.error,
errorCode: schema.heartbeatRuns.errorCode,
stderrExcerpt: schema.heartbeatRuns.stderrExcerpt,
stdoutExcerpt: schema.heartbeatRuns.stdoutExcerpt,
logStore: schema.heartbeatRuns.logStore,
logRef: schema.heartbeatRuns.logRef,
createdAt: schema.heartbeatRuns.createdAt,
})
.from(schema.heartbeatRuns)
.where(whereClause)
.orderBy(desc(schema.heartbeatRuns.createdAt), desc(schema.heartbeatRuns.id))
.limit(limit);
let truncated = countHitCap || runsTotalInWindow > runs.length;
if (runs.length === 0) {
return {
runs,
runsTotalInWindow,
truncated,
diagnosticsByRun: new Map<string, string[]>(),
matchedByRun: new Map<string, Map<number, string | undefined>>(),
runsWithEvents: new Set<string>(),
redactorsByRun: new Map<string, RunTextRedactor>(),
};
}
const runIds = runs.map((r) => r.id);
const diagnosticsByRun = await listRunPlatformDiagnostics(tx, runIds, q.companyId);
const redactions = includeExcerpts ? createRunSecretRedactionRegistry(tx) : null;
const redactorsByRun = new Map<string, RunTextRedactor>();
const getRedactor = async (companyId: string, runId: string): Promise<RunTextRedactor | null> => {
if (!redactions) return null;
let redactor = redactorsByRun.get(runId);
if (!redactor) {
const values = await redactions.redactionValuesForRun(companyId, runId);
const maxSecretLen = values.reduce((max, v) => Math.max(max, v.length), 0);
redactor = {
redact: (text: string) => redactRegisteredSecretValues(text, values),
redactObject: <T>(value: T): T => redactRegisteredSecretValues(value, values),
maxSecretLen,
};
redactorsByRun.set(runId, redactor);
}
return redactor;
};
const matchedByRun = new Map<string, Map<number, string | undefined>>();
for (const run of runs) {
const hits = new Map<number, string | undefined>();
const sanitizedError = typeof run.error === "string" ? withoutSqlStatementText(run.error) : null;
const rawRunObj: Record<string, unknown> = {
...(sanitizedError ? { error: sanitizedError } : {}),
...(run.errorCode ? { errorCode: run.errorCode } : {}),
...(run.stderrExcerpt ? { stderrExcerpt: run.stderrExcerpt } : {}),
...(run.stdoutExcerpt ? { stdoutExcerpt: run.stdoutExcerpt } : {}),
};
const redactorForRow =
includeExcerpts && Object.keys(rawRunObj).length > 0
? await getRedactor(run.companyId, run.id)
: null;
const safeRunFields = redactEventPayload(
redactorForRow ? redactorForRow.redactObject(rawRunObj) : rawRunObj,
);
const runFields = [
safeRunFields?.error,
safeRunFields?.errorCode,
safeRunFields?.stderrExcerpt,
safeRunFields?.stdoutExcerpt,
]
.filter((v): v is string => typeof v === "string" && v.length > 0)
.join("\n");
if (runFields) {
for (let i = 0; i < patterns.length; i++) {
const pattern = patterns[i]!;
if (findLiteralIndex(runFields, pattern, caseSensitive) >= 0) {
hits.set(
i,
redactorForRow
? extractRedactedExcerpt(runFields, pattern, caseSensitive, redactorForRow)
: undefined,
);
}
}
}
matchedByRun.set(run.id, hits);
}
const eventRunRows = await tx
.selectDistinct({ runId: schema.heartbeatRunEvents.runId })
.from(schema.heartbeatRunEvents)
.where(inArray(schema.heartbeatRunEvents.runId, runIds));
const runsWithEvents = new Set(eventRunRows.map((r) => r.runId));
// Pre-resolve secret redactors BEFORE running event queries so even if an event
// query later hits statement_timeout, every fallback log-scan run already has its
// redactor loaded and the transaction does not need extra queries after recovery.
if (includeExcerpts) {
for (const run of runs) {
if (!run.logRef || !isRunLogStoreType(run.logStore)) continue;
const needsLogScan = run.runtimeMode !== "native" || !runsWithEvents.has(run.id);
if (!needsLogScan) continue;
const hits = matchedByRun.get(run.id)!;
if (hits.size < patterns.length) {
await getRedactor(run.companyId, run.id);
}
}
}
// Push literal substring pre-filtering into PostgreSQL (raw + JSON-escaped
// forms) and verify against decoded JSON string values in bounded batches so
// counts are identical with or without excerpts and genuine matches behind
// JSON-key hits are never silently dropped.
const EVENT_CANDIDATE_BATCH_SIZE = 10;
const MAX_EVENT_CANDIDATES_PER_RUN = 100;
const runById = new Map(runs.map((r) => [r.id, r]));
let eventQueryTimedOut = false;
for (let i = 0; i < patterns.length && !eventQueryTimedOut; i++) {
if (now() >= deadlineMs) {
truncated = true;
break;
}
const pattern = patterns[i]!;
let remainingIds = runIds.filter((id) => !matchedByRun.get(id)!.has(i) && runsWithEvents.has(id));
if (remainingIds.length === 0) continue;
const matchCondition = buildEventMatchCondition(pattern, caseSensitive);
let excerptsAdded = runs.filter((r) => matchedByRun.get(r.id)!.has(i)).length;
for (
let batchStart = 1;
remainingIds.length > 0 && batchStart <= MAX_EVENT_CANDIDATES_PER_RUN;
batchStart += EVENT_CANDIDATE_BATCH_SIZE
) {
const remainingMs = deadlineMs - now();
if (remainingMs <= 0) {
truncated = true;
break;
}
const batchEnd = Math.min(batchStart + EVENT_CANDIDATE_BATCH_SIZE - 1, MAX_EVENT_CANDIDATES_PER_RUN);
// Refresh statement_timeout to the remaining wall-clock budget and guard with
// a savepoint so a 57014 timeout rolls back only this query instead of aborting
// the entire read-only transaction and discarding partial matches.
await tx.execute(sql.raw(`SAVEPOINT cs_run_search_batch`));
let eventRows: Array<{ runId: string; message: string | null; payload: unknown }>;
try {
const batchTimeoutMs = Math.max(50, Math.min(wallBudgetMs, Math.floor(remainingMs)));
await tx.execute(sql.raw(`SET LOCAL statement_timeout = '${batchTimeoutMs}'`));
const ranked = tx
.select({
runId: schema.heartbeatRunEvents.runId,
message: schema.heartbeatRunEvents.message,
payload: schema.heartbeatRunEvents.payload,
rn: sql<number>`row_number() over (partition by ${schema.heartbeatRunEvents.runId} order by ${schema.heartbeatRunEvents.seq} asc)`.as(
"rn",
),
})
.from(schema.heartbeatRunEvents)
.where(and(inArray(schema.heartbeatRunEvents.runId, remainingIds), matchCondition))
.as("ranked_events");
eventRows = await tx
.select({
runId: ranked.runId,
message: ranked.message,
payload: ranked.payload,
})
.from(ranked)
.where(sql`${ranked.rn} >= ${batchStart} and ${ranked.rn} <= ${batchEnd}`);
await tx.execute(sql.raw(`RELEASE SAVEPOINT cs_run_search_batch`));
} catch (err) {
await tx.execute(sql.raw(`ROLLBACK TO SAVEPOINT cs_run_search_batch`)).catch(() => undefined);
await tx.execute(sql.raw(`RELEASE SAVEPOINT cs_run_search_batch`)).catch(() => undefined);
if (isStatementTimeoutError(err)) {
truncated = true;
eventQueryTimedOut = true;
break;
}
throw err;
}
const rowsSeenByRun = new Map<string, number>();
for (const eventRow of eventRows) {
rowsSeenByRun.set(eventRow.runId, (rowsSeenByRun.get(eventRow.runId) ?? 0) + 1);
const hits = matchedByRun.get(eventRow.runId);
if (!hits || hits.has(i)) continue;
const run = runById.get(eventRow.runId)!;
const redactor =
includeExcerpts && excerptsAdded < MAX_INSPECTION_SEARCH_SAMPLE_RUNS
? await getRedactor(run.companyId, run.id)
: null;
const decoded = findDecodedEventMatch(
eventRow.message,
eventRow.payload,
pattern,
caseSensitive,
redactor,
);
if (decoded === undefined) continue;
let excerpt: string | undefined;
if (redactor) {
excerpt = extractRedactedExcerpt(decoded, pattern, caseSensitive, redactor);
excerptsAdded += 1;
}
hits.set(i, excerpt);
}
const expectedFullBatch = batchEnd - batchStart + 1;
// Only keep runs that have not yet matched AND filled the entire batch
// (meaning more SQL-matching events may exist for that run).
remainingIds = remainingIds.filter(
(id) => !matchedByRun.get(id)!.has(i) && (rowsSeenByRun.get(id) ?? 0) >= expectedFullBatch,
);
}
if (remainingIds.length > 0) {
truncated = true;
}
}
return {
runs,
runsTotalInWindow,
truncated,
diagnosticsByRun,
matchedByRun,
runsWithEvents,
redactorsByRun,
};
},
{ accessMode: "read only", isolationLevel: "repeatable read" },
);
// Phase 2: Outside any DB transaction, scan fallback RunLogStore streams with
// per-read AbortSignal + wall-clock budget.
const { runs, runsTotalInWindow, diagnosticsByRun, matchedByRun, runsWithEvents, redactorsByRun } = dbPhase;
let truncated = dbPhase.truncated;
const byStatus: Record<string, number> = {};
const byDriver: Record<string, number> = {};
const byDiagnostic: Record<string, number> = {};
const patternHits: InspectionRunSearchPatternHit[] = patterns.map((pattern) => ({
pattern,
matchedRuns: 0,
byStatus: {},
byDriver: {},
byRuntimeMode: {},
firstSeenAt: null,
lastSeenAt: null,
sampleRuns: [],
}));
if (runs.length === 0) {
return {
runsScanned: 0,
runsTotalInWindow,
truncated,
byStatus,
byDriver,
byDiagnostic,
patterns: patternHits,
coOccurrence: [],
};
}
for (const run of runs) {
increment(byStatus, run.status);
increment(byDriver, run.driverKind ?? "unknown");
for (const code of diagnosticsByRun.get(run.id) ?? []) {
increment(byDiagnostic, code);
}
}
const logStore = options.logStore ?? getRunLogStore();
const logBudget = { bytes: MAX_TOTAL_LOG_BYTES, deadlineMs, now };
for (const run of runs) {
if (!run.logRef || !isRunLogStoreType(run.logStore)) continue;
const needsLogScan = run.runtimeMode !== "native" || !runsWithEvents.has(run.id);
if (!needsLogScan) continue;
const hits = matchedByRun.get(run.id)!;
const remaining = new Set<number>();
for (let i = 0; i < patterns.length; i++) {
if (!hits.has(i)) remaining.add(i);
}
if (remaining.size === 0) continue;
const scanned = await scanRunLogForPatterns(
logStore,
run.logStore,
String(run.logRef),
patterns,
caseSensitive,
remaining,
// Fail closed: never use an identity fallback when includeExcerpts is true.
includeExcerpts ? (redactorsByRun.get(run.id) ?? null) : null,
logBudget,
);
if (scanned.truncated) truncated = true;
for (const [patternIdx, excerpt] of scanned.matched) {
hits.set(patternIdx, excerpt);
}
}
const coOccurrenceCounts = new Map<string, { patterns: string[]; matchedRuns: number }>();
for (const run of runs) {
const hits = matchedByRun.get(run.id)!;
if (hits.size === 0) continue;
const createdAtIso = run.createdAt.toISOString();
const driver = run.driverKind ?? "unknown";
const diagnostics = diagnosticsByRun.get(run.id) ?? [];
const matchedIndexes = [...hits.keys()].sort((a, b) => a - b);
const coKey = matchedIndexes.join(",");
const existingCo = coOccurrenceCounts.get(coKey);
if (existingCo) {
existingCo.matchedRuns += 1;
} else {
coOccurrenceCounts.set(coKey, {
patterns: matchedIndexes.map((idx) => patterns[idx]!),
matchedRuns: 1,
});
}
for (const idx of matchedIndexes) {
const bucket = patternHits[idx]!;
bucket.matchedRuns += 1;
increment(bucket.byStatus, run.status);
increment(bucket.byDriver, driver);
increment(bucket.byRuntimeMode, run.runtimeMode);
if (bucket.firstSeenAt === null || createdAtIso < bucket.firstSeenAt) bucket.firstSeenAt = createdAtIso;
if (bucket.lastSeenAt === null || createdAtIso > bucket.lastSeenAt) bucket.lastSeenAt = createdAtIso;
if (bucket.sampleRuns.length < MAX_INSPECTION_SEARCH_SAMPLE_RUNS) {
const excerpt = includeExcerpts ? hits.get(idx) : undefined;
const sample: InspectionRunSearchSample = {
runId: run.id,
companyId: run.companyId,
status: run.status,
driverKind: run.driverKind,
runtimeMode: run.runtimeMode,
createdAt: createdAtIso,
diagnostics,
...(excerpt ? { excerpt } : {}),
};
bucket.sampleRuns.push(sample);
}
}
}
const coOccurrence = [...coOccurrenceCounts.values()].sort(
(a, b) => b.matchedRuns - a.matchedRuns || a.patterns.join("\0").localeCompare(b.patterns.join("\0")),
);
return {
runsScanned: runs.length,
runsTotalInWindow,
truncated,
byStatus,
byDriver,
byDiagnostic,
patterns: patternHits,
coOccurrence,
};
}
@@ -32,6 +32,11 @@ export function nativeRunLogSourceWhere(companyId: string, runId: string) {
sql`${heartbeatRunEvents.sourceEventId} like 'provider-trace-reproject:%'`,
sql`${heartbeatRunEvents.sourceInstanceId} like 'provider-trace-reproject:%'`,
),
and(
eq(heartbeatRunEvents.eventType, "platform.diagnostic"),
sql`${heartbeatRunEvents.sourceEventId} like 'platform-diagnostic:%'`,
sql`${heartbeatRunEvents.sourceInstanceId} like '%:platform-diagnostic'`,
),
)}), false)`,
),
);
@@ -45,6 +45,10 @@ import { lockNativeRunnerCheckpointOwner, nativeRunnerCheckpointOwnerLock, valid
import { crashPoint } from "@paperclipai/shared/crash-points";
import { NATIVE_PROVIDER_DURABLE_EVENT_TYPES } from "./native-retired-backup-source.js";
import { recordRunEventCommitted } from "../server-metrics.js";
import {
extractRunPlatformDiagnosticsFromEvent,
recordRunPlatformDiagnostics,
} from "../run-platform-diagnostics.js";
export interface PaperclipControlPlaneBinding {
companyId: string;
@@ -542,6 +546,21 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
} catch {
}
await this.#onCommittedEvent?.(event, persisted.row.seq);
const diagnosticCodes = extractRunPlatformDiagnosticsFromEvent(
persisted.row.eventType,
persisted.row.message,
persisted.row.payload as Record<string, unknown> | null,
);
if (diagnosticCodes.length > 0) {
void recordRunPlatformDiagnostics(this.#db, {
companyId: this.#binding.companyId,
runId: this.#binding.runId,
agentId: this.#binding.agentId,
codes: diagnosticCodes,
runtimeMode: "native",
occurredAt: persisted.row.createdAt,
});
}
} else {
// A recovered runner may replay the event whose durable side effects
// parked the prior attempt. Do not repeat those effects, but let the
@@ -0,0 +1,347 @@
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 [];
}
}