Files
PaperClipAI/server/src/__tests__/run-platform-diagnostics.test.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

281 lines
9.2 KiB
TypeScript

import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import * as schema from "@paperclipai/db";
import { detectRunPlatformDiagnostics } from "@paperclipai/shared";
import {
extractRunPlatformDiagnosticsFromEvent,
listRunPlatformDiagnostics,
recordRunPlatformDiagnostics,
reportFinalizedRunDiagnostics,
RUNTIME_DIAGNOSTICS_CAPABILITY_ENV,
} from "../services/run-platform-diagnostics.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
describe("run platform diagnostics", () => {
let db: schema.Db;
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
let companyId: string;
let agentId: string;
beforeAll(async () => {
database = await startEmbeddedPostgresTestDatabase("run-platform-diagnostics-");
db = schema.createDb(database.connectionString);
const [company] = await db
.insert(schema.companies)
.values({ name: "DiagCo", issuePrefix: "DGC" })
.returning();
companyId = company.id;
const [agent] = await db
.insert(schema.agents)
.values({ companyId, name: "Codex", adapterType: "codex_local" })
.returning();
agentId = agent.id;
});
afterAll(async () => {
await database?.cleanup();
});
it("classifies git storage guard, github capability, and disk full markers cleanly", () => {
expect(
detectRunPlatformDiagnostics(
"paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete.",
),
).toEqual(["git_storage_guard_unavailable"]);
expect(
detectRunPlatformDiagnostics(
"paperclip_git_storage_limit: The sandbox has too little free disk space or too few free inodes; Git did not start.",
),
).toEqual(["git_storage_limit", "sandbox_disk_full"]);
// Storage budget refusal is NOT disk/inode exhaustion.
expect(
detectRunPlatformDiagnostics(
"paperclip_git_storage_limit: Git stopped at its storage budget.",
),
).toEqual(["git_storage_limit"]);
// Arbitrary customer command output unrelated to sandbox disk exhaustion is ignored.
expect(
detectRunPlatformDiagnostics("customer script stderr: No space left on device"),
).toEqual([]);
expect(
detectRunPlatformDiagnostics(
"Paperclip: GitHub capability_missing; continuing without managed credentials.\n" +
"paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured.",
),
).toEqual(["git_storage_guard_unavailable", "github_capability_missing"]);
expect(detectRunPlatformDiagnostics("ordinary git clone succeeded")).toEqual([]);
});
it("extracts diagnostics from native PRP commandExecution payloads", () => {
expect(
extractRunPlatformDiagnosticsFromEvent("item.completed", null, {
prpEvent: {
payload: {
kind: "commandExecution",
aggregatedOutput:
"Paperclip: GitHub capability_rejected; token denied\n" +
"remote_workspace_archive_failed: reason=git_storage_guard_unavailable",
},
},
}),
).toEqual(["git_storage_guard_unavailable", "github_capability_rejected"]);
});
it("deduplicates persisted platform.diagnostic rows and posts PII-free reports to Cloud", async () => {
const [run] = await db
.insert(schema.heartbeatRuns)
.values({
companyId,
agentId,
status: "succeeded",
exitCode: 0,
runtimeMode: "native",
driverKind: "codex",
})
.returning();
const sent: Array<{ url: string; headers: Record<string, string>; body: unknown }> = [];
const fetcher: typeof fetch = vi.fn(async (input, init) => {
sent.push({
url: String(input),
headers: Object.fromEntries(new Headers(init?.headers).entries()),
body: JSON.parse(String(init?.body ?? "{}")),
});
return new Response(JSON.stringify({ recorded: 2 }), { status: 200 });
});
const env = {
PAPERCLIP_CLOUD_API_ORIGIN: "https://cloud.example.test",
PAPERCLIP_PRIMARY_HOST: "tenant.example.test",
[RUNTIME_DIAGNOSTICS_CAPABILITY_ENV]: "a".repeat(64),
};
const first = await recordRunPlatformDiagnostics(
db,
{
companyId,
runId: run.id,
agentId,
codes: ["git_storage_guard_unavailable", "github_capability_missing"],
runStatus: "running",
driverKind: "codex",
runtimeMode: "native",
},
{ env, fetcher },
);
expect(first).toEqual(["git_storage_guard_unavailable", "github_capability_missing"]);
// Second recording for the same run/codes is idempotent (no duplicate DB rows, no extra Cloud POST).
const second = await recordRunPlatformDiagnostics(
db,
{
companyId,
runId: run.id,
agentId,
codes: ["git_storage_guard_unavailable"],
runStatus: "running",
driverKind: "codex",
runtimeMode: "native",
},
{ env, fetcher },
);
expect(second).toEqual([]);
expect(sent).toHaveLength(1);
const listed = await listRunPlatformDiagnostics(db, [run.id], companyId);
expect(listed.get(run.id)).toEqual([
"git_storage_guard_unavailable",
"github_capability_missing",
]);
// Finalization sends the terminal status ("succeeded") with zero customer prose.
const finalized = await reportFinalizedRunDiagnostics(
db,
{
id: run.id,
companyId,
agentId,
status: "succeeded",
driverKind: "codex",
runtimeMode: "native",
finishedAt: new Date("2026-11-25T15:00:00.000Z"),
},
{ env, fetcher },
);
expect(finalized).toEqual(["git_storage_guard_unavailable", "github_capability_missing"]);
expect(sent).toHaveLength(2);
expect(sent[1]!.url).toBe("https://cloud.example.test/v1/customer-success/stack/diagnostics");
expect(sent[1]!.headers["x-paperclip-cloud-tenant-host"]).toBe("tenant.example.test");
expect(sent[1]!.body).toEqual({
runId: run.id,
diagnosticCodes: ["git_storage_guard_unavailable", "github_capability_missing"],
runStatus: "succeeded",
driverKind: "codex",
runtimeMode: "native",
occurredAt: "2026-11-25T15:00:00.000Z",
});
});
it("persists distinct diagnostic codes recorded in separate calls without sequence collisions", async () => {
const [run] = await db
.insert(schema.heartbeatRuns)
.values({
companyId,
agentId,
status: "running",
runtimeMode: "native",
driverKind: "codex",
})
.returning();
const first = await recordRunPlatformDiagnostics(
db,
{
companyId,
runId: run.id,
agentId,
codes: ["github_capability_missing"],
},
{ reportToCloud: false },
);
const second = await recordRunPlatformDiagnostics(
db,
{
companyId,
runId: run.id,
agentId,
codes: ["git_storage_guard_unavailable"],
},
{ reportToCloud: false },
);
expect(first).toEqual(["github_capability_missing"]);
expect(second).toEqual(["git_storage_guard_unavailable"]);
const listed = await listRunPlatformDiagnostics(db, [run.id], companyId);
expect(listed.get(run.id)).toEqual([
"git_storage_guard_unavailable",
"github_capability_missing",
]);
});
it("reloads missing error and metadata fields from heartbeat_runs during finalization", async () => {
const [run] = await db
.insert(schema.heartbeatRuns)
.values({
companyId,
agentId,
status: "failed",
exitCode: 1,
runtimeMode: "legacy",
driverKind: "claude",
error: "remote_workspace_archive_failed: reason=git_storage_guard_unavailable",
stderrExcerpt: "Paperclip: GitHub capability_rejected; token denied",
})
.returning();
const sent: unknown[] = [];
const fetcher: typeof fetch = vi.fn(async (_input, init) => {
sent.push(JSON.parse(String(init?.body ?? "{}")));
return new Response(JSON.stringify({ recorded: 2 }), { status: 200 });
});
const env = {
PAPERCLIP_CLOUD_API_ORIGIN: "https://cloud.example.test",
PAPERCLIP_PRIMARY_HOST: "tenant.example.test",
[RUNTIME_DIAGNOSTICS_CAPABILITY_ENV]: "b".repeat(64),
};
// Pass only minimal fields — error/stderrExcerpt/driverKind/runtimeMode are omitted.
const finalized = await reportFinalizedRunDiagnostics(
db,
{
id: run.id,
companyId,
agentId,
status: "failed",
finishedAt: new Date("2026-11-25T16:00:00.000Z"),
},
{ env, fetcher },
);
expect(finalized).toEqual(["git_storage_guard_unavailable", "github_capability_rejected"]);
const listed = await listRunPlatformDiagnostics(db, [run.id], companyId);
expect(listed.get(run.id)).toEqual([
"git_storage_guard_unavailable",
"github_capability_rejected",
]);
expect(sent).toEqual([
{
runId: run.id,
diagnosticCodes: ["git_storage_guard_unavailable", "github_capability_rejected"],
runStatus: "failed",
driverKind: "claude",
runtimeMode: "legacy",
occurredAt: "2026-11-25T16:00:00.000Z",
},
]);
});
});