Files
PaperClipAI/server/src/__tests__/customer-success-cloud.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

546 lines
24 KiB
TypeScript

import { createServer, type RequestListener } from "node:http";
import type { AddressInfo } from "node:net";
import { generateKeyPairSync, randomUUID } from "node:crypto";
import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import { pathToFileURL } from "node:url";
import express from "express";
import { describe, it, expect, vi } from "vitest";
import {
createDb,
agents,
companies,
heartbeatRuns,
heartbeatRunEvents,
issues,
projects,
projectWorkspaces,
} from "@paperclipai/db";
import { customerSuccessRoutes } from "../routes/customer-success.js";
import { agentIdentityService } from "../services/agent-identity.js";
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
import { execute } from "../adapters/process/execute.js";
import { errorHandler } from "../middleware/error-handler.js";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import type { StorageService } from "../storage/types.js";
// Coordinated qualification against the sibling Cloud build, never a customer
// stack or hosted provider. Default unit runs have no cross-repository dependency.
const cloudDist = process.env.PAPERCLIP_INSPECTION_CLOUD_DIST;
describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qualification", () => {
it("uses the existing managed-runtime identity, active JWT, PostgreSQL broker, HTTP permits, and audited tenant reads", async () => {
const load = (module: string) => import(pathToFileURL(resolve(cloudDist!, module)).href);
const [
{ CustomerSuccessInspection },
{ InspectionSigner },
{ PostgresInspectionStore },
{ inspectionRoute },
{ InMemoryCloudHarnessRegistry },
{ CloudStackSleepController },
pg,
] = await Promise.all([
load("customer-success/service.js"),
load("customer-success/crypto.js"),
load("customer-success/store.js"),
load("customer-success/routes.js"),
load("provisioner/memory.js"),
load("sleep/controller.js"),
load("../node_modules/pg/lib/index.js"),
]);
const home = await startEmbeddedPostgresTestDatabase("inspection-home-");
const tenant = await startEmbeddedPostgresTestDatabase("inspection-customer-");
const directory = await mkdtemp(join(tmpdir(), "inspection-journey-"));
const servers: ReturnType<typeof createServer>[] = [];
const serverErrors: string[] = [];
const pool = new pg.default.Pool({
connectionString: home.connectionString,
max: 2,
connectionTimeoutMillis: 1000,
});
try {
vi.stubEnv("PAPERCLIP_HOME", directory);
vi.stubEnv("PAPERCLIP_INSTANCE_ID", "qualification-home");
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "isolated-qualification-jwt");
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(directory, "master.key"));
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "");
vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_AUTHORITY_ENABLED", "true");
vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED", "true");
vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "qualification-stack");
const homeDb = createDb(home.connectionString);
const tenantDb = createDb(tenant.connectionString);
const [homeCompany] = await homeDb
.insert(companies)
.values({ name: "Internal", issuePrefix: "INT" })
.returning();
const [agent] = await homeDb
.insert(agents)
.values({
companyId: homeCompany.id,
name: "Success qualification",
adapterType: "process",
})
.returning();
const identity = await agentIdentityService(homeDb).ensureAgentIdentity(
homeCompany.id,
agent.id,
);
const [run] = await homeDb
.insert(heartbeatRuns)
.values({
companyId: homeCompany.id,
agentId: agent.id,
status: "running",
startedAt: new Date(),
})
.returning();
const [customer] = await tenantDb
.insert(companies)
.values({ name: "Synthetic customer", issuePrefix: "SYN" })
.returning();
const [project] = await tenantDb
.insert(projects)
.values({ companyId: customer.id, name: "Qualification project" })
.returning();
const [workspace] = await tenantDb
.insert(projectWorkspaces)
.values({
companyId: customer.id,
projectId: project.id,
name: "Qualification files",
cwd: directory,
})
.returning();
const filePath = join(directory, "result.bin");
await writeFile(filePath, Buffer.from([0, 1, 2, 3, 4, 5]));
const fileBefore = await stat(filePath);
const [task] = await tenantDb
.insert(issues)
.values({ companyId: customer.id, projectId: project.id, title: "First successful task" })
.returning();
const [tenantAgent] = await tenantDb
.insert(agents)
.values({ companyId: customer.id, name: "Tenant Codex", adapterType: "codex_local" })
.returning();
const [tenantRun] = await tenantDb
.insert(heartbeatRuns)
.values({
companyId: customer.id,
agentId: tenantAgent.id,
status: "succeeded",
exitCode: 0,
runtimeMode: "native",
driverKind: "codex",
startedAt: new Date(Date.now() - 60_000),
finishedAt: new Date(),
})
.returning();
await tenantDb.insert(heartbeatRunEvents).values([
{
companyId: customer.id,
runId: tenantRun.id,
agentId: tenantAgent.id,
seq: 1,
eventType: "item.completed",
stream: "system",
payload: {
prpEvent: {
payload: {
kind: "commandExecution",
aggregatedOutput:
"paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete.",
},
},
},
},
{
companyId: customer.id,
runId: tenantRun.id,
agentId: tenantAgent.id,
seq: 2,
eventType: "platform.diagnostic",
stream: "system",
message: "git_storage_guard_unavailable",
payload: { code: "git_storage_guard_unavailable" },
},
]);
const storage = { provider: "local_disk" } as StorageService;
const start = async (handler: RequestListener) => {
const server = createServer(handler);
servers.push(server);
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
};
const homeApp = express();
homeApp.use(express.json());
homeApp.use("/api/customer-success/v1", customerSuccessRoutes(homeDb, storage));
homeApp.use(errorHandler);
const sourceOrigin = await start(homeApp);
const tenantApp = express();
tenantApp.use(express.json());
tenantApp.use("/api/customer-success/v1", customerSuccessRoutes(tenantDb, storage));
tenantApp.use(errorHandler);
const tenantOrigin = await start(tenantApp);
await pool.query("CREATE SCHEMA cloud_harness");
await pool.query(
await readFile(
resolve(cloudDist!, "../migrations/0058_customer_success_inspection.sql"),
"utf8",
),
);
await pool.query(
await readFile(
resolve(cloudDist!, "../migrations/0097_customer_success_fleet_queries.sql"),
"utf8",
),
);
const registry = new InMemoryCloudHarnessRegistry();
let transactionReads = 0;
const registryForClient = (client: any) => ({
getStack: async (id: string) => {
await client.query("SELECT 1");
transactionReads++;
return registry.getStack(id);
},
getAccount: async (id: string) => {
await client.query("SELECT 1");
transactionReads++;
return registry.getCustomerSuccessAccount(id);
},
getStacks: async (ids: readonly string[]) => {
await client.query("SELECT 1");
transactionReads++;
return (await Promise.all(ids.map((id) => registry.getStack(id)))).filter(Boolean);
},
getAccounts: async (ids: readonly string[]) => {
await client.query("SELECT 1");
transactionReads++;
return (
await Promise.all(ids.map((id) => registry.getCustomerSuccessAccount(id)))
).filter(Boolean);
},
listStackIds: async () => registry.listCustomerSuccessStackIds(),
});
const store = new PostgresInspectionStore(pool, registryForClient);
const now = new Date();
registry.accountGroups.set("fixture-account", {
id: "fixture-account",
kind: "customer",
billingStatus: "unconfigured",
});
registry.stacks.set("qualification-stack", {
id: "qualification-stack",
accountGroupId: "fixture-account",
displayName: "Synthetic customer",
primaryHost: "fixture.example.test",
kind: "customer_production",
lifecycleState: "sleeping",
sleepState: "sleeping",
sleepReason: "idle",
version: 1,
updatedAt: now,
rolloutMetadata: { track: "stable" },
providerRefs: [
{
provider: "railway",
resourceType: "service_domain:web",
externalId: "fixture",
metadata: { upstreamOrigin: tenantOrigin },
},
],
createdAt: now,
});
const signer = new InspectionSigner(
"qualification",
generateKeyPairSync("ed25519").privateKey.export({ format: "jwk" }),
);
vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_JWKS", signer.publicJwks);
// Use the production wake controller with a disposable local provider.
// The tenant HTTP process is already listening; no hosted stack is woken.
const sleep = new CloudStackSleepController({
registry,
provider: {
name: "fake",
wakeStack: async (
_id: string,
context: { stack: Record<string, unknown>; providerRefs: unknown[] },
) => ({
stack: { ...context.stack, lifecycleState: "active", sleepState: "awake" },
resources: context.providerRefs,
secretRefs: { providerAdminCredentials: {} },
operations: [],
}),
inspectStack: async () => ({
stackId: "qualification-stack",
lifecycleState: "active",
sleepState: "awake",
resources: registry.stacks.get("qualification-stack").providerRefs,
}),
},
});
const broker = new CustomerSuccessInspection({
store,
registry,
signer,
allowLoopback: true,
wakeStack: async (stackId: string) => {
await sleep.wakeStack({ stackId });
},
});
const cloudOrigin = await start(async (req, res) => {
try {
const handled = await inspectionRoute({
req,
res,
url: new URL(req.url!, "http://localhost"),
service: broker,
authenticateHuman: async () => {
throw new Error("Qualification never uses human access");
},
readJson: async (request: AsyncIterable<Buffer>, max: number) => {
const parts: Buffer[] = [];
let bytes = 0;
for await (const part of request) {
bytes += part.length;
if (bytes > max) throw new Error("Too large");
parts.push(part);
}
return JSON.parse(Buffer.concat(parts).toString());
},
});
if (!handled) {
res.statusCode = 404;
res.end();
}
} catch (error) {
serverErrors.push(String(error));
res.statusCode = 503;
res.end("{}");
}
});
vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_CLOUD_ORIGIN", cloudOrigin);
await broker.configure("qualification-operator", {
binding: {
sourceOrigin,
instanceId: "qualification-home",
companyId: homeCompany.id,
agentId: agent.id,
keyId: identity.keyId,
publicKeyPem: identity.publicKeyPem,
},
});
await broker.configure("qualification-operator", { enabled: true });
const program = `
const {inspectionAgentClient}=await import(${JSON.stringify(pathToFileURL(resolve(cloudDist!, "customer-success/client.js")).href)});
const call=inspectionAgentClient();
const discovery=await call('discover',{order:'newest'});
// Default fleet query MUST NOT wake the sleeping qualification-stack.
const fleetDefault=await call('fleet.query.start',{cohort:{stackIds:['qualification-stack']},query:{operation:'runs.search',patterns:['paperclip_git_storage_limit']}});
const grant=await call('grant',{stackId:'qualification-stack'});
const tasks=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
const file=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'files.download',companyId:${JSON.stringify(customer.id)},resourceId:${JSON.stringify(task.id)},context:{projectId:${JSON.stringify(project.id)},workspaceId:${JSON.stringify(workspace.id)}},path:'result.bin',range:{start:2,end:5}}});
const taskCount=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'count',resource:'tasks',companyId:${JSON.stringify(customer.id)}}});
const latestRuns=await call('read',{stackId:'qualification-stack',grantToken:grant.token,query:{operation:'list',resource:'runs',companyId:${JSON.stringify(customer.id)},order:'newest',view:'summary',limit:1}});
// Now qualification-stack is awake: run a fleet query across /read-v3!
const fleetAwake=await call('fleet.query.start',{cohort:{stackIds:['qualification-stack']},query:{operation:'runs.search',patterns:['paperclip_git_storage_limit']}});
let fleetDone=fleetAwake;
for(let i=0;i<50&&fleetDone.status==='running';i++){await new Promise(r=>setTimeout(r,20));fleetDone=await call('fleet.query.status',{queryId:fleetAwake.id});}
const fleetDiag=await call('fleet.diagnostics',{stackIds:['qualification-stack']});
console.log(JSON.stringify({stackCount:discovery.items.length,fleetDefault,fleetDone,fleetDiag,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')],taskCount,latestRuns}));
`;
const programFile = join(directory, "qualify.mjs");
await writeFile(programFile, program);
const output: string[] = [];
const result = await execute({
runId: run.id,
agent,
agentIdentity: identity,
authToken: createLocalAgentJwt(agent.id, homeCompany.id, "process", run.id)!,
config: {
command: process.execPath,
args: [programFile],
cwd: directory,
env: { PAPERCLIP_CUSTOMER_SUCCESS_CLOUD_ORIGIN: cloudOrigin },
},
context: {},
runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null },
onLog: async (_stream, chunk) => {
output.push(chunk);
},
onMeta: async () => {},
});
expect(result.exitCode, [...output, ...serverErrors].join("\n")).toBe(0);
const parsedOut = JSON.parse(output.join("").trim());
expect(parsedOut.titles).toContain("First successful task");
expect(parsedOut.fileBytes).toEqual([2, 3, 4, 5]);
// Count and newest-first summary reads travel the extended tenant path and include diagnostics.
expect(parsedOut.taskCount).toMatchObject({ total: 1 });
expect(parsedOut.latestRuns.items).toHaveLength(1);
expect(parsedOut.latestRuns.items[0].diagnostics).toEqual(["git_storage_guard_unavailable"]);
// Default fleet query did NOT wake the sleeping stack and reported skippedSleeping: 1.
expect(parsedOut.fleetDefault.wakeSleeping).toBe(false);
expect(parsedOut.fleetDefault.status).toBe("completed");
expect(parsedOut.fleetDefault.coverage.skippedSleeping).toBe(1);
expect(parsedOut.fleetDefault.coverage.scanned).toBe(0);
// Fleet query against the awake stack over /read-v3 caught paperclip_git_storage_limit on a succeeded run!
expect(parsedOut.fleetDone.status).toBe("completed");
expect(parsedOut.fleetDone.coverage.scanned).toBe(1);
expect(parsedOut.fleetDone.summary.patterns[0].matchedStacks).toBe(1);
expect(parsedOut.fleetDone.summary.patterns[0].matchedRuns).toBe(1);
expect(parsedOut.fleetDone.summary.byDiagnostic).toEqual({ git_storage_guard_unavailable: 1 });
// PostgreSQL-backed zero-wake fleet diagnostics query ran cleanly.
expect(parsedOut.fleetDiag.totalEligibleStacks).toBe(1);
expect((await stat(filePath)).mtimeMs).toBe(fileBefore.mtimeMs);
expect(await readFile(filePath)).toEqual(Buffer.from([0, 1, 2, 3, 4, 5]));
const audit = await pool.query(
"SELECT event FROM cloud_harness.customer_success_audit ORDER BY occurred_at",
);
expect(audit.rows.map((r: { event: string }) => r.event)).toContain("permit.consumed");
expect(audit.rows.map((r: { event: string }) => r.event)).toContain("read.completed");
expect(audit.rows.map((r: { event: string }) => r.event)).toContain("stack.woken");
expect(await tenantDb.select().from(issues)).toEqual([task]);
// The production SQL reader scopes before pagination and hides mixed
// approval cohorts and global policy records from tenant approvers.
await store.transaction(async (tx: any) => {
const localId = randomUUID();
const mixedId = randomUUID();
const foreignId = randomUUID();
for (const [id, detail, stackId] of [
[localId, { stackIds: ["qualification-stack"] }, undefined],
[mixedId, { stackIds: ["qualification-stack", "foreign-stack"] }, undefined],
[foreignId, {}, "foreign-stack"],
])
await tx.audit({ id, at: tx.now, event: "scope.fixture", detail, stackId });
const scoped = await tx.audits(0, 100, ["qualification-stack"]);
expect(scoped.some((event: any) => event.id === localId)).toBe(true);
expect(scoped.some((event: any) => event.id === mixedId || event.id === foreignId)).toBe(
false,
);
expect(scoped.some((event: any) => event.event === "policy.changed")).toBe(false);
expect(await tx.audits(0, 100, [])).toEqual([]);
const last = await tx.audits(scoped.length - 1, 100, ["qualification-stack"]);
expect(last).toHaveLength(1);
});
// Two independent pool connections prove consumption is durable, not a
// process-local Set: exactly one replica can consume a signed challenge.
const token = createLocalAgentJwt(agent.id, homeCompany.id, "process", run.id)!;
const c = await broker.challenge(token, "discover", {});
const { sign } = await import("node:crypto");
const sig = sign(null, Buffer.from(c.bytes), identity.privateKeyPem).toString("base64url");
const replica = new CustomerSuccessInspection({
store: new PostgresInspectionStore(pool, registryForClient),
registry,
signer,
allowLoopback: true,
});
const competing = await Promise.allSettled([
broker.execute(token, c.challengeId, sig),
replica.execute(token, c.challengeId, sig),
]);
expect(competing.filter((r) => r.status === "fulfilled")).toHaveLength(1);
const grants = await Promise.all(
Array.from({ length: 4 }, () =>
broker.challenge(token, "grant", { stackId: "qualification-stack" }),
),
);
const concurrentGrants = await Promise.all(
grants.map((proof) =>
broker.execute(
token,
proof.challengeId,
sign(null, Buffer.from(proof.bytes), identity.privateKeyPem).toString("base64url"),
),
),
);
expect(concurrentGrants).toHaveLength(4);
expect(transactionReads).toBeGreaterThan(0);
// Prove append-only enforcement with a runtime role, even if someone
// accidentally grants it UPDATE/DELETE privileges on the audit table.
const client = await pool.connect();
const runtimeRole = `inspection_runtime_${randomUUID().replaceAll("-", "")}`;
try {
await client.query(`CREATE ROLE ${runtimeRole}`);
await client.query(`GRANT USAGE ON SCHEMA cloud_harness TO ${runtimeRole}`);
await client.query(
`GRANT SELECT, UPDATE, DELETE ON cloud_harness.customer_success_audit TO ${runtimeRole}`,
);
await client.query(`SET ROLE ${runtimeRole}`);
await expect(
client.query("UPDATE cloud_harness.customer_success_audit SET event = 'rewritten'"),
).rejects.toThrow("append-only");
await expect(
client.query("DELETE FROM cloud_harness.customer_success_audit"),
).rejects.toThrow("append-only");
} finally {
await client.query("RESET ROLE");
client.release();
}
// Exercise PostgresInspectionStore.recordDiagnostics + SQL aggregateDiagnostics end-to-end.
await store.recordDiagnostics([
{
stackId: "qualification-stack",
runId: "diag-run-1",
diagnosticCode: "git_storage_guard_unavailable",
runStatus: "succeeded",
driverKind: "codex",
runtimeMode: "native",
appVersion: "v2026.1125.0",
sandboxSnapshot: "snap-qual",
occurredAt: new Date(now.getTime() - 60_000).toISOString(),
},
{
stackId: "qualification-stack",
runId: "diag-run-1",
diagnosticCode: "github_capability_missing",
runStatus: "succeeded",
driverKind: "codex",
runtimeMode: "native",
appVersion: "v2026.1125.0",
sandboxSnapshot: "snap-qual",
occurredAt: new Date(now.getTime() - 60_000).toISOString(),
},
]);
const pgDiagSummary = await store.aggregateDiagnostics(
[
{
stackId: "qualification-stack",
host: "fixture.example.test",
createdAt: now.toISOString(),
},
],
{},
);
expect(pgDiagSummary.matchedStacks).toBe(1);
expect(pgDiagSummary.matchedRuns).toBe(1);
expect(pgDiagSummary.diagnostics).toHaveLength(2);
expect(pgDiagSummary.coOccurrence).toEqual([
{
diagnosticCodes: ["git_storage_guard_unavailable", "github_capability_missing"],
matchedStacks: 1,
matchedRuns: 1,
},
]);
const { applyInspectionRetention } = await load("customer-success/retention.js");
await expect(applyInspectionRetention(pool, 364)).rejects.toThrow("at least one year");
await pool.query(
"INSERT INTO cloud_harness.customer_success_audit VALUES ($1,clock_timestamp() - interval '366 days','old.fixture','{}')",
[randomUUID()],
);
expect((await applyInspectionRetention(pool)).auditDeleted).toBe(1);
expect(
(await pool.query("SELECT count(*) FROM cloud_harness.customer_success_audit")).rows[0]
.count,
).not.toBe("0");
} finally {
for (const server of servers.reverse())
await new Promise<void>((resolve) => server.close(() => resolve()));
await pool.end();
await tenant.cleanup();
await home.cleanup();
vi.unstubAllEnvs();
await rm(directory, { recursive: true, force: true });
}
}, 60000);
});