## 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>
7.9 KiB
Cloud customer-success inspection support
Paperclip exposes /api/customer-success/v1/run-authority, /run-liveness,
/read, /read-v2 and /read-v3 for the coordinated Cloud inspection broker. This foundation supports one registered
Paperclip agent; bot creation, scheduling, scoring and reporting are separate.
The authority endpoint is disabled unless
PAPERCLIP_CUSTOMER_SUCCESS_AUTHORITY_ENABLED=true. It accepts only a strict,
current instance/company-derived managed-run JWT. It requires the authenticated
agent's existing provisioned Ed25519 identity and an active running heartbeat;
paused, cancelled/stopped, finished and unsupported-runtime agents are rejected.
No identity GET provisions keys. Normal API JWT compatibility remains unchanged;
legacy signatures are rejected specifically at this authority boundary.
The run liveness check (POST /run-liveness) is also disabled unless
PAPERCLIP_CUSTOMER_SUCCESS_AUTHORITY_ENABLED=true. It lets Cloud ask, with its
own inspection key rather than an agent credential, whether one run of one agent
in one company is live. It refuses cookies and Authorization headers and
accepts only an Ed25519 JWS in the inspection header, verified against
PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_JWKS, with type
paperclip-inspection-liveness+jwt, audience
paperclip-customer-success-liveness/v1, this stack as subject and a window of
at most sixty seconds. The canonical JSON body {agentId, companyId, runId} must
equal the signed claims. The answer is {version: 1, companyId, agentId, runId, active}, using the same run rules as the authority endpoint (one shared
predicate) but without requiring a provisioned identity key. It runs in a
read-only transaction and creates no actor, session, activity or key.
Tenant reads are disabled unless
PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED=true. Configure the public-only
PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_JWKS and the stable HTTPS
PAPERCLIP_CUSTOMER_SUCCESS_CLOUD_ORIGIN. Cloud provision/roll delivers the trust
configuration. The persisted runtime stack identity is authoritative; an explicit
PAPERCLIP_CLOUD_STACK_ID is usable on operator-configured qualification stacks.
Cloud's dedicated inspection key is distinct from the inspecting agent's key.
The tenant verifies a maximum-sixty-second, audience/type-bound Ed25519 permit with exact stack, query, grant, registered key/agent/run, request and binding version. It calls Cloud's permit-consumption endpoint before reading, so replay fencing and every inspection record live in Cloud. Cloud remains responsible for stack eligibility, seven days from creation/pooled claim, human older-stack approval, active source-run checks, limits, revocation and audits. The source run bearer is never forwarded to tenants.
The namespace terminates before actor middleware. It never creates users, memberships, sessions, run-identity snapshots, activity records or read receipts. All database readers run inside repeatable-read, read-only transactions. An explicit catalog avoids existing GET side effects such as skill reconciliation, instruction recovery/adoption and provider-trace cleanup. There is no arbitrary GET proxy, write operation or credential-resolution operation.
The catalog in services/customer-success-inspection.ts covers companies,
directory/membership/permission metadata, agents/config/instruction revisions and
public identity, tasks/comments/documents/interactions, approvals/decisions,
routines/schedules, projects/workspaces/stored repository assignments, skill
sources/versions, execution events/trace metadata, activity/costs, work products/
assets/attachments, and existing readable connections/installs/grants/catalogs.
packages/shared/src/customer-success.ts is the versioned wire contract and is
mirrored byte-for-byte in the private Cloud broker; update both together.
list/get readers enforce company scope and bounded pagination. Special
operations read instruction files without repair, installed skill snapshots,
existing run logs, workspace files through the current file-resource service,
and company-scoped storage assets. Workspace context uses an owning task and
existing project/workspace checks. Binary envelopes and inclusive byte ranges
pass through Cloud; ranges cap at 1 MiB, JSON at 2 MiB, and lists at 100 rows.
Remote or unsnapshotted resources report unavailable; large content requires
pagination or download ranges. No storage credentials or bypass URLs are issued.
Summary reads keep a fleet-wide refresh cheap:
counttakes a cataloguedresource,companyIdand optionalparentId, and returns{total, byStatus}: counts grouped by the reader'sstatuscolumn, orbyStatus: nullwhen it has none. No row content is read out.order(listonly) isnewestoroldestby creation time, with the table's primary key as tie-breaker so offset pages never repeat or skip rows. Without it, lists keep their original id order.view: "summary"(list/getonrunsonly) returns an allowlist of ids, status, error code, retry counters and timestamps plus a computeddurationMsand recorded platformdiagnosticscodes, and leaves out the large JSON columns (result, usage, context snapshot, runner profile).RUN_SUMMARY_COLUMNSis the allowlist.runs.search(served on/read-v3) performs a bounded, read-only literal substring search (1 to 5 plain patterns, no regex) overheartbeat_runs,heartbeat_run_events, and (for non-native runs or runs without stored events)RunLogStore. It returns counts, breakdowns by status/driver/diagnostic, pattern co-occurrence, and sample run pointers without returning raw customer prose. SettingincludeExcerpts: truerequirescompanyIdand redacts every short excerpt through the run's secret redaction registry.- Stack-wide
count(omittingcompanyId) is also served on/read-v3so Cloud fleet queries can aggregate totals across all companies on a stack in one request.
Queries that use count (with companyId), order or view are served on
/read-v2, and runs.search or stack-wide count on /read-v3
(inspectionReadPath picks the path); older endpoints refuse newer queries. A
tenant that predates a path answers 404 there, so Cloud fails closed with
tenant_inspection_version_unsupported instead of misreading the query.
Existing config/event/run redactions and path/symlink/secret-file/size restrictions remain in use. Authentication account/session, secret, private-key/encrypted-key and raw provider-trace tables/readers are excluded. Identity-enabled trace suppression stays intact. No new prose/file scanner is added; arbitrary pasted secrets in otherwise readable content may be present.
Deploy this support first, then Cloud's migration/broker/admin UI. Keep both inspection and Cloud policy disabled until staging and internal canary checks pass. Wake only idle sleeps through Cloud's existing controller; normal startup and background writes after wake are separate from the inspection read. Existing human login/Slack alerts are unchanged.
Focused verification:
pnpm exec vitest run server/src/__tests__/customer-success.test.ts \
server/src/__tests__/agent-auth-jwt.test.ts server/src/__tests__/agent-identity.test.ts
# Coordinated qualification, with the sibling Cloud build:
PAPERCLIP_INSPECTION_CLOUD_DIST=/absolute/path/paperclip-cloud/dist \
pnpm exec vitest run server/src/__tests__/customer-success-cloud.test.ts
The coordinated test uses two disposable local PostgreSQL databases, a real managed process with the existing identity/env injection, a PostgreSQL-backed Cloud broker, HTTP permit consumption, the existing wake controller with a local provider, and bounded binary file reads. It tests durable replay fencing and never touches a customer. Cloud's operations document covers enrollment, capability grants, exclusions, approval/expiry/revocation, audit retention and rollback. During rollback, disable Cloud policy first, disable tenant inspection, and preserve identity material and Cloud audit history.