mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +01:00
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:
1 parent
bc98abda0c
commit
2d764bebc6
17 files changed
+2446
-30
No files matched your search
@@ -12,6 +12,7 @@ import {
|
||||
agents,
|
||||
companies,
|
||||
heartbeatRuns,
|
||||
heartbeatRunEvents,
|
||||
issues,
|
||||
projects,
|
||||
projectWorkspaces,
|
||||
@@ -117,6 +118,52 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
.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);
|
||||
@@ -141,6 +188,12 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
"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) => ({
|
||||
@@ -280,13 +333,20 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
const program = `
|
||||
const {inspectionAgentClient}=await import(${JSON.stringify(pathToFileURL(resolve(cloudDist!, "customer-success/client.js")).href)});
|
||||
const call=inspectionAgentClient();
|
||||
const discovery=await call('discover',{});
|
||||
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}});
|
||||
console.log(JSON.stringify({stackCount:discovery.items.length,titles:tasks.items.map(t=>t.title),fileBytes:[...Buffer.from(file.content,'base64')],taskCount,latestRuns}));
|
||||
// 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);
|
||||
@@ -310,11 +370,26 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
onMeta: async () => {},
|
||||
});
|
||||
expect(result.exitCode, [...output, ...serverErrors].join("\n")).toBe(0);
|
||||
expect(output.join("")).toContain("First successful task");
|
||||
expect(output.join("")).toContain('"fileBytes":[2,3,4,5]');
|
||||
// Count and newest-first summary reads travel the extended tenant path.
|
||||
expect(output.join("")).toContain('"taskCount":{"total":1,"byStatus":{');
|
||||
expect(output.join("")).toContain('"latestRuns":{"items":[],"nextOffset":null}');
|
||||
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(
|
||||
@@ -400,6 +475,52 @@ describe.skipIf(!cloudDist)("customer-success managed agent / Cloud / tenant qua
|
||||
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(
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import * as schema from "@paperclipai/db";
|
||||
import { readCustomerSuccessResource } from "../services/customer-success-inspection.js";
|
||||
import { searchCustomerSuccessRuns } from "../services/customer-success-run-search.js";
|
||||
import { createRunSecretRedactionRegistry } from "../services/run-secret-redaction.js";
|
||||
import type { RunLogStore } from "../services/run-log-store.js";
|
||||
import type { StorageService } from "../storage/types.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
describe("customer-success runs.search", () => {
|
||||
let db: schema.Db;
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let directory: string;
|
||||
const storage = {} as unknown as StorageService;
|
||||
|
||||
beforeAll(async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "cs-run-search-test-"));
|
||||
vi.stubEnv("PAPERCLIP_HOME", directory);
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(directory, "master.key"));
|
||||
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "");
|
||||
database = await startEmbeddedPostgresTestDatabase("customer-success-run-search-");
|
||||
db = schema.createDb(database.connectionString);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await database?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
if (directory) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("catches hidden platform errors inside succeeded runs, reports co-occurrence, and redacts excerpts", async () => {
|
||||
const [coA, coB] = await db
|
||||
.insert(schema.companies)
|
||||
.values([
|
||||
{ name: "SearchCoA", issuePrefix: "SCA" },
|
||||
{ name: "SearchCoB", issuePrefix: "SCB" },
|
||||
])
|
||||
.returning();
|
||||
const [agentA] = await db
|
||||
.insert(schema.agents)
|
||||
.values({ companyId: coA.id, name: "Codex A", adapterType: "codex_local" })
|
||||
.returning();
|
||||
const [agentB] = await db
|
||||
.insert(schema.agents)
|
||||
.values({ companyId: coB.id, name: "OpenCode B", adapterType: "opencode_local" })
|
||||
.returning();
|
||||
|
||||
const t1 = new Date("2026-11-23T10:00:00.000Z");
|
||||
const t2 = new Date("2026-11-24T10:00:00.000Z");
|
||||
const t3 = new Date("2026-11-24T12:00:00.000Z");
|
||||
|
||||
const [runBoth, runGitOnly] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values([
|
||||
{
|
||||
companyId: coA.id,
|
||||
agentId: agentA.id,
|
||||
status: "succeeded",
|
||||
exitCode: 0,
|
||||
runtimeMode: "native",
|
||||
driverKind: "codex",
|
||||
createdAt: t1,
|
||||
},
|
||||
{
|
||||
companyId: coA.id,
|
||||
agentId: agentA.id,
|
||||
status: "succeeded",
|
||||
exitCode: 0,
|
||||
runtimeMode: "native",
|
||||
driverKind: "codex",
|
||||
createdAt: t2,
|
||||
},
|
||||
])
|
||||
.returning();
|
||||
const [runOtherCo] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values([
|
||||
{
|
||||
companyId: coB.id,
|
||||
agentId: agentB.id,
|
||||
status: "failed",
|
||||
exitCode: 1,
|
||||
runtimeMode: "native",
|
||||
driverKind: "opencode",
|
||||
error: "remote_workspace_archive_failed: exit=75 program=git reason=git_storage_guard_unavailable",
|
||||
createdAt: t3,
|
||||
},
|
||||
])
|
||||
.returning();
|
||||
|
||||
await db.insert(schema.heartbeatRunEvents).values([
|
||||
{
|
||||
companyId: coA.id,
|
||||
runId: runBoth.id,
|
||||
agentId: agentA.id,
|
||||
seq: 1,
|
||||
eventType: "item.completed",
|
||||
stream: "system",
|
||||
payload: {
|
||||
prpEvent: {
|
||||
payload: {
|
||||
kind: "commandExecution",
|
||||
aggregatedOutput:
|
||||
"Paperclip: GitHub capability_missing; continuing without managed credentials.\n" +
|
||||
"paperclip_git_storage_limit: Git's storage guard is unavailable or misconfigured; Git did not complete.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
companyId: coA.id,
|
||||
runId: runBoth.id,
|
||||
agentId: agentA.id,
|
||||
seq: 2,
|
||||
eventType: "platform.diagnostic",
|
||||
stream: "system",
|
||||
message: "git_storage_guard_unavailable",
|
||||
payload: { code: "git_storage_guard_unavailable" },
|
||||
},
|
||||
{
|
||||
companyId: coA.id,
|
||||
runId: runGitOnly.id,
|
||||
agentId: agentA.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.",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
// Company-scoped search with excerpts returns redacted matches and co-occurrence.
|
||||
const scoped = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "runs.search",
|
||||
companyId: coA.id,
|
||||
patterns: ["paperclip_git_storage_limit", "capability_missing"],
|
||||
createdAfter: "2026-11-23T00:00:00.000Z",
|
||||
includeExcerpts: true,
|
||||
})) as {
|
||||
runsScanned: number;
|
||||
runsTotalInWindow: number;
|
||||
truncated: boolean;
|
||||
byDiagnostic: Record<string, number>;
|
||||
patterns: Array<{
|
||||
pattern: string;
|
||||
matchedRuns: number;
|
||||
byStatus: Record<string, number>;
|
||||
sampleRuns: Array<{ runId: string; excerpt?: string; diagnostics: string[] }>;
|
||||
}>;
|
||||
coOccurrence: Array<{ patterns: string[]; matchedRuns: number }>;
|
||||
};
|
||||
expect(scoped.runsScanned).toBe(2);
|
||||
expect(scoped.runsTotalInWindow).toBe(2);
|
||||
expect(scoped.truncated).toBe(false);
|
||||
expect(scoped.byDiagnostic).toEqual({ git_storage_guard_unavailable: 1 });
|
||||
expect(scoped.patterns[0]!.matchedRuns).toBe(2);
|
||||
expect(scoped.patterns[0]!.byStatus).toEqual({ succeeded: 2 });
|
||||
expect(scoped.patterns[0]!.sampleRuns[0]!.excerpt).toContain("paperclip_git_storage_limit");
|
||||
expect(scoped.patterns[1]!.matchedRuns).toBe(1);
|
||||
expect(scoped.coOccurrence).toEqual([
|
||||
{ patterns: ["paperclip_git_storage_limit"], matchedRuns: 1 },
|
||||
{ patterns: ["paperclip_git_storage_limit", "capability_missing"], matchedRuns: 1 },
|
||||
]);
|
||||
|
||||
// Stack-wide search (no companyId, zero excerpts) spans both companies on the stack.
|
||||
const stackWide = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "runs.search",
|
||||
patterns: ["paperclip_git_storage_limit", "git_storage_guard_unavailable"],
|
||||
createdAfter: "2026-11-23T00:00:00.000Z",
|
||||
createdBefore: "2026-11-25T00:00:00.000Z",
|
||||
})) as {
|
||||
runsScanned: number;
|
||||
patterns: Array<{ pattern: string; matchedRuns: number; sampleRuns: Array<{ runId: string; excerpt?: string }> }>;
|
||||
};
|
||||
expect(stackWide.runsScanned).toBe(3);
|
||||
expect(stackWide.patterns[0]!.matchedRuns).toBe(2);
|
||||
// Matches both runOtherCo (run.error) and runBoth (platform.diagnostic event).
|
||||
expect(stackWide.patterns[1]!.matchedRuns).toBe(2);
|
||||
expect(stackWide.patterns[1]!.sampleRuns.map((r) => r.runId)).toContain(runOtherCo.id);
|
||||
expect(stackWide.patterns[1]!.sampleRuns.map((r) => r.runId)).toContain(runBoth.id);
|
||||
expect(stackWide.patterns[0]!.sampleRuns[0]!.excerpt).toBeUndefined();
|
||||
|
||||
// Stack-wide count (no companyId) counts across all companies on the stack.
|
||||
const allRunCount = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "count",
|
||||
resource: "runs",
|
||||
})) as { total: number; byStatus: Record<string, number> };
|
||||
expect(allRunCount.total).toBeGreaterThanOrEqual(3);
|
||||
|
||||
// Summary view attaches structured diagnostics on succeeded runs.
|
||||
const summaryRun = (await readCustomerSuccessResource(db, storage, {
|
||||
operation: "get",
|
||||
resource: "runs",
|
||||
companyId: coA.id,
|
||||
resourceId: runBoth.id,
|
||||
view: "summary",
|
||||
})) as { status: string; diagnostics: string[] };
|
||||
expect(summaryRun.status).toBe("succeeded");
|
||||
expect(summaryRun.diagnostics).toEqual(["git_storage_guard_unavailable"]);
|
||||
});
|
||||
|
||||
it("redacts registered secrets before excerpt slicing, across paged log edges, decodes escaped literals, and marks unreadable/slow logs truncated", async () => {
|
||||
const [co] = await db
|
||||
.insert(schema.companies)
|
||||
.values({ name: "SearchEdgeCo", issuePrefix: "SEC" })
|
||||
.returning();
|
||||
const [agent] = await db
|
||||
.insert(schema.agents)
|
||||
.values({ companyId: co.id, name: "EdgeAgent", adapterType: "codex_local" })
|
||||
.returning();
|
||||
|
||||
// 1) Secret crossing the 240-char excerpt boundary AND a multiline secret must be
|
||||
// redacted in full BEFORE slicing or whitespace collapsing.
|
||||
const boundarySecret = "sk-boundary-secret-0123456789abcdef-tail";
|
||||
const multilineSecret = "BEGIN-SECRET-LINE1\nMIDDLE-SECRET-LINE2\nEND-SECRET-LINE3";
|
||||
const [secretRun] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values({
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "native",
|
||||
driverKind: "codex",
|
||||
})
|
||||
.returning();
|
||||
const redactions = createRunSecretRedactionRegistry(db);
|
||||
await redactions.register(co.id, secretRun.id, boundarySecret);
|
||||
await redactions.register(co.id, secretRun.id, multilineSecret);
|
||||
|
||||
await db.insert(schema.heartbeatRunEvents).values({
|
||||
companyId: co.id,
|
||||
runId: secretRun.id,
|
||||
agentId: agent.id,
|
||||
seq: 1,
|
||||
eventType: "item.completed",
|
||||
stream: "system",
|
||||
payload: {
|
||||
prpEvent: {
|
||||
payload: {
|
||||
kind: "commandExecution",
|
||||
aggregatedOutput:
|
||||
`MARKER_BOUNDARY ${"x".repeat(100)} ${boundarySecret} ` +
|
||||
`and multiline ${multilineSecret} plus say "hello"\\world`,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const redactedSearch = await searchCustomerSuccessRuns(db, {
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["MARKER_BOUNDARY", 'say "hello"\\world'],
|
||||
includeExcerpts: true,
|
||||
});
|
||||
expect(redactedSearch.patterns[0]!.matchedRuns).toBe(1);
|
||||
const boundaryExcerpt = redactedSearch.patterns[0]!.sampleRuns[0]!.excerpt ?? "";
|
||||
expect(boundaryExcerpt).toContain("MARKER_BOUNDARY");
|
||||
expect(boundaryExcerpt).not.toContain("sk-boundary");
|
||||
expect(boundaryExcerpt).not.toContain("0123456789");
|
||||
expect(boundaryExcerpt).not.toContain("BEGIN-SECRET");
|
||||
expect(boundaryExcerpt).not.toContain("MIDDLE-SECRET");
|
||||
// Literal pattern with quotes and backslash matches decoded JSON payload.
|
||||
expect(redactedSearch.patterns[1]!.matchedRuns).toBe(1);
|
||||
const escapedExcerpt = redactedSearch.patterns[1]!.sampleRuns[0]!.excerpt ?? "";
|
||||
expect(escapedExcerpt).toContain('say "hello"\\world');
|
||||
expect(escapedExcerpt).not.toContain("BEGIN-SECRET");
|
||||
expect(escapedExcerpt).not.toContain("END-SECRET");
|
||||
|
||||
// 2) Legacy RunLogStore fallback: decodes NDJSON chunks, preserves UTF-8 split
|
||||
// across read boundaries, and marks failed or timed-out log reads truncated.
|
||||
const [logRun, missingLogRun, slowLogRun] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values([
|
||||
{
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "legacy",
|
||||
driverKind: "codex",
|
||||
logStore: "local_file",
|
||||
logRef: "utf8-and-quotes.ndjson",
|
||||
},
|
||||
{
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "legacy",
|
||||
driverKind: "codex",
|
||||
logStore: "local_file",
|
||||
logRef: "missing.ndjson",
|
||||
},
|
||||
{
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "legacy",
|
||||
driverKind: "codex",
|
||||
logStore: "local_file",
|
||||
logRef: "slow.ndjson",
|
||||
},
|
||||
])
|
||||
.returning();
|
||||
|
||||
const ndjsonBytes = Buffer.from(
|
||||
`${JSON.stringify({ ts: "2026-11-25T00:00:00Z", stream: "stderr", chunk: 'prefix café 🚀 say "quoted"\n' })}\n` +
|
||||
`${JSON.stringify({ ts: "2026-11-25T00:00:01Z", stream: "stderr", chunk: "tail line" })}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
const makeFakeStore = (mode: "utf8" | "missing" | "slow"): RunLogStore => ({
|
||||
begin: async () => ({ store: "local_file", logRef: "unused" }),
|
||||
append: async () => 0,
|
||||
finalize: async () => ({ bytes: 0, compressed: false }),
|
||||
read: async (handle, opts) => {
|
||||
if (handle.logRef === "utf8-and-quotes.ndjson" && mode === "utf8") {
|
||||
const offset = opts?.offset ?? 0;
|
||||
// Force a tiny 45-byte page that cuts straight through multibyte UTF-8 / JSON.
|
||||
const step = Math.min(45, opts?.limitBytes ?? 45);
|
||||
const slice = ndjsonBytes.subarray(offset, offset + step);
|
||||
const nextOffset = offset + slice.length < ndjsonBytes.length ? offset + slice.length : undefined;
|
||||
return { content: slice.toString("utf8"), nextOffset };
|
||||
}
|
||||
if (handle.logRef === "missing.ndjson") {
|
||||
throw new Error("ENOENT: log missing after pod roll");
|
||||
}
|
||||
if (handle.logRef === "slow.ndjson" && mode === "slow") {
|
||||
return new Promise((_resolve, reject) => {
|
||||
opts?.signal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true });
|
||||
});
|
||||
}
|
||||
return { content: "" };
|
||||
},
|
||||
});
|
||||
|
||||
// UTF-8 split & JSON-escaped quotes match cleanly when log is readable.
|
||||
const utf8Only = await searchCustomerSuccessRuns(
|
||||
db,
|
||||
{
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ['café 🚀 say "quoted"'],
|
||||
},
|
||||
{
|
||||
logStore: {
|
||||
...makeFakeStore("utf8"),
|
||||
read: async (handle, opts) =>
|
||||
handle.logRef === "utf8-and-quotes.ndjson"
|
||||
? makeFakeStore("utf8").read(handle, opts)
|
||||
: { content: "" },
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(utf8Only.truncated).toBe(false);
|
||||
expect(utf8Only.patterns[0]!.matchedRuns).toBe(1);
|
||||
expect(utf8Only.patterns[0]!.sampleRuns[0]!.runId).toBe(logRun.id);
|
||||
|
||||
// Failed log read sets truncated: true rather than reporting a clean negative.
|
||||
const missingResult = await searchCustomerSuccessRuns(
|
||||
db,
|
||||
{
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["never-matches-anything"],
|
||||
},
|
||||
{ logStore: makeFakeStore("missing") },
|
||||
);
|
||||
expect(missingResult.truncated).toBe(true);
|
||||
expect(missingLogRun.id).toBeTruthy();
|
||||
|
||||
// Slow log read is aborted by wallBudgetMs and sets truncated: true promptly.
|
||||
const started = Date.now();
|
||||
const slowResult = await searchCustomerSuccessRuns(
|
||||
db,
|
||||
{
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["never-matches-anything"],
|
||||
},
|
||||
{ logStore: makeFakeStore("slow"), wallBudgetMs: 200 },
|
||||
);
|
||||
expect(slowResult.truncated).toBe(true);
|
||||
expect(Date.now() - started).toBeLessThan(2_000);
|
||||
expect(slowLogRun.id).toBeTruthy();
|
||||
|
||||
// 3) Truncated search (limit: 1 with >1 runs in window) MUST still load redactors
|
||||
// and redact registered secrets from fallback RunLogStore excerpts — including a
|
||||
// secret split across two paged log chunks on both left and right edges!
|
||||
const leftEdgeSecret = "sk-left-edge-secret-aaaa1111bbbb2222";
|
||||
const rightEdgeSecret = "sk-right-edge-secret-cccc3333dddd4444";
|
||||
const [newestLogRun] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values({
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "legacy",
|
||||
driverKind: "codex",
|
||||
logStore: "local_file",
|
||||
logRef: "truncated-secret.ndjson",
|
||||
createdAt: new Date(Date.now() + 60_000),
|
||||
})
|
||||
.returning();
|
||||
await redactions.register(co.id, newestLogRun.id, leftEdgeSecret);
|
||||
await redactions.register(co.id, newestLogRun.id, rightEdgeSecret);
|
||||
const secretNdjsonBytes = Buffer.from(
|
||||
`${JSON.stringify({ ts: "2026-11-25T00:00:00Z", stream: "stderr", chunk: "sk-left-edge-" })}\n` +
|
||||
`${JSON.stringify({ ts: "2026-11-25T00:00:01Z", stream: "stderr", chunk: "secret-aaaa1111bbbb2222 TRUNCATED_MARKER sk-right-edge-" })}\n` +
|
||||
`${JSON.stringify({ ts: "2026-11-25T00:00:02Z", stream: "stderr", chunk: "secret-cccc3333dddd4444 end\n" })}\n`,
|
||||
"utf8",
|
||||
);
|
||||
const truncatedRedacted = await searchCustomerSuccessRuns(
|
||||
db,
|
||||
{
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["TRUNCATED_MARKER"],
|
||||
limit: 1,
|
||||
includeExcerpts: true,
|
||||
},
|
||||
{
|
||||
logStore: {
|
||||
begin: async () => ({ store: "local_file", logRef: "unused" }),
|
||||
append: async () => 0,
|
||||
finalize: async () => ({ bytes: 0, compressed: false }),
|
||||
read: async (handle, opts) => {
|
||||
if (handle.logRef !== "truncated-secret.ndjson") return { content: "" };
|
||||
const offset = opts?.offset ?? 0;
|
||||
const step = Math.min(115, opts?.limitBytes ?? 115);
|
||||
const slice = secretNdjsonBytes.subarray(offset, offset + step);
|
||||
const nextOffset = offset + slice.length < secretNdjsonBytes.length ? offset + slice.length : undefined;
|
||||
return { content: slice.toString("utf8"), nextOffset };
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
expect(truncatedRedacted.truncated).toBe(true);
|
||||
expect(truncatedRedacted.patterns[0]!.matchedRuns).toBe(1);
|
||||
const truncExcerpt = truncatedRedacted.patterns[0]!.sampleRuns[0]!.excerpt ?? "";
|
||||
expect(truncExcerpt).toContain("TRUNCATED_MARKER");
|
||||
expect(truncExcerpt).not.toContain("sk-left-edge");
|
||||
expect(truncExcerpt).not.toContain("aaaa1111");
|
||||
expect(truncExcerpt).not.toContain("sk-right-edge");
|
||||
expect(truncExcerpt).not.toContain("cccc3333");
|
||||
|
||||
// 4) Matches after early JSON-key-only hits (e.g. searching "output" when early
|
||||
// events have key "aggregatedOutput" without "output" in their values) are found
|
||||
// consistently both with and without includeExcerpts.
|
||||
const [lateMatchRun] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values({
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "native",
|
||||
driverKind: "codex",
|
||||
createdAt: new Date(Date.now() + 120_000),
|
||||
})
|
||||
.returning();
|
||||
await db.insert(schema.heartbeatRunEvents).values([
|
||||
...Array.from({ length: 5 }, (_, idx) => ({
|
||||
companyId: co.id,
|
||||
runId: lateMatchRun.id,
|
||||
agentId: agent.id,
|
||||
seq: idx + 1,
|
||||
eventType: "item.completed",
|
||||
stream: "system",
|
||||
payload: { aggregatedOutput: `benign line ${idx}` },
|
||||
})),
|
||||
{
|
||||
companyId: co.id,
|
||||
runId: lateMatchRun.id,
|
||||
agentId: agent.id,
|
||||
seq: 6,
|
||||
eventType: "item.completed",
|
||||
stream: "system",
|
||||
payload: { aggregatedOutput: "real output match on event 6" },
|
||||
},
|
||||
]);
|
||||
const withoutExcerpts = await searchCustomerSuccessRuns(db, {
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["output"],
|
||||
limit: 1,
|
||||
includeExcerpts: false,
|
||||
});
|
||||
const withExcerpts = await searchCustomerSuccessRuns(db, {
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["output"],
|
||||
limit: 1,
|
||||
includeExcerpts: true,
|
||||
});
|
||||
expect(withoutExcerpts.patterns[0]!.matchedRuns).toBe(1);
|
||||
expect(withExcerpts.patterns[0]!.matchedRuns).toBe(1);
|
||||
expect(withExcerpts.patterns[0]!.sampleRuns[0]!.excerpt).toContain("real output match on event 6");
|
||||
|
||||
// 5) Historical Drizzle SQL statements and bound params in heartbeat_runs.error
|
||||
// are stripped via withoutSqlStatementText before searching or excerpting.
|
||||
const [sqlErrRun] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values({
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "failed",
|
||||
runtimeMode: "native",
|
||||
driverKind: "codex",
|
||||
error: "Failed query: select * from secrets where value = $1\nparams: unregistered-sql-param-secret",
|
||||
createdAt: new Date(Date.now() + 180_000),
|
||||
})
|
||||
.returning();
|
||||
const sqlSearch = await searchCustomerSuccessRuns(db, {
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["unregistered-sql-param-secret", "Database query failed"],
|
||||
limit: 1,
|
||||
includeExcerpts: true,
|
||||
});
|
||||
expect(sqlSearch.patterns[0]!.matchedRuns).toBe(0);
|
||||
expect(sqlSearch.patterns[1]!.matchedRuns).toBe(1);
|
||||
expect(sqlSearch.patterns[1]!.sampleRuns[0]!.runId).toBe(sqlErrRun.id);
|
||||
expect(sqlSearch.patterns[1]!.sampleRuns[0]!.excerpt).not.toContain("unregistered-sql-param-secret");
|
||||
|
||||
// 6) Complete registered secret values are removed FIRST before structural redaction
|
||||
// can alter any substring inside them, and structural redaction (redactEventPayload)
|
||||
// ALSO strips unregistered secret-named keys and bearer tokens.
|
||||
const [structRun] = await db
|
||||
.insert(schema.heartbeatRuns)
|
||||
.values({
|
||||
companyId: co.id,
|
||||
agentId: agent.id,
|
||||
status: "succeeded",
|
||||
runtimeMode: "native",
|
||||
driverKind: "codex",
|
||||
createdAt: new Date(Date.now() + 240_000),
|
||||
})
|
||||
.returning();
|
||||
const compositeRegisteredSecret = "prefix-keep-out Bearer inner-token-123 suffix-keep-out";
|
||||
await redactions.register(co.id, structRun.id, compositeRegisteredSecret);
|
||||
await db.insert(schema.heartbeatRunEvents).values({
|
||||
companyId: co.id,
|
||||
runId: structRun.id,
|
||||
agentId: agent.id,
|
||||
seq: 1,
|
||||
eventType: "item.completed",
|
||||
stream: "system",
|
||||
payload: {
|
||||
apiKey: "unregistered-api-key-secret-value",
|
||||
aggregatedOutput:
|
||||
`STRUCT_REDACT_MARKER ${compositeRegisteredSecret} ` +
|
||||
`authorization=Bearer unregistered-bearer-token-999`,
|
||||
},
|
||||
});
|
||||
const structSearch = await searchCustomerSuccessRuns(db, {
|
||||
operation: "runs.search",
|
||||
companyId: co.id,
|
||||
patterns: ["unregistered-api-key-secret-value", "STRUCT_REDACT_MARKER"],
|
||||
limit: 1,
|
||||
includeExcerpts: true,
|
||||
});
|
||||
expect(structSearch.patterns[0]!.matchedRuns).toBe(0);
|
||||
expect(structSearch.patterns[1]!.matchedRuns).toBe(1);
|
||||
const structExcerpt = structSearch.patterns[1]!.sampleRuns[0]!.excerpt ?? "";
|
||||
expect(structExcerpt).toContain("STRUCT_REDACT_MARKER");
|
||||
expect(structExcerpt).not.toContain("prefix-keep-out");
|
||||
expect(structExcerpt).not.toContain("suffix-keep-out");
|
||||
expect(structExcerpt).not.toContain("unregistered-bearer-token-999");
|
||||
});
|
||||
});
|
||||
@@ -775,8 +775,9 @@ describe("customer-success read authority", () => {
|
||||
})) as { items: Array<Record<string, unknown>>; nextOffset: number | null };
|
||||
expect(latest.items.map((r) => r.id)).toEqual([runs[2].id]);
|
||||
expect(latest.nextOffset).toEqual(1);
|
||||
expect(Object.keys(latest.items[0]).sort()).toEqual([...RUN_SUMMARY_COLUMNS, "durationMs"].sort());
|
||||
expect(Object.keys(latest.items[0]).sort()).toEqual([...RUN_SUMMARY_COLUMNS, "diagnostics", "durationMs"].sort());
|
||||
expect(latest.items[0].durationMs).toBeNull();
|
||||
expect(latest.items[0].diagnostics).toEqual([]);
|
||||
expect(JSON.stringify(latest).length).toBeLessThan(2_000);
|
||||
|
||||
const page = (await readCustomerSuccessResource(db, storage, {
|
||||
@@ -845,7 +846,7 @@ describe("customer-success read authority", () => {
|
||||
expect(seen.sort()).toEqual(labels.map((label) => label.id).sort());
|
||||
}
|
||||
});
|
||||
it("count, order and view are bounded and take the extended read path", () => {
|
||||
it("count, order, view, and runs.search are bounded and take their versioned read paths", () => {
|
||||
expect(inspectionReadPath(parseInspectionQuery({ operation: "list", resource: "runs", companyId }))).toEqual("/read");
|
||||
for (const value of [
|
||||
{ operation: "count", resource: "runs", companyId },
|
||||
@@ -854,14 +855,32 @@ describe("customer-success read authority", () => {
|
||||
])
|
||||
expect(inspectionReadPath(parseInspectionQuery(value))).toEqual("/read-v2");
|
||||
for (const value of [
|
||||
{ operation: "count", companyId },
|
||||
{ operation: "count", resource: "runs" },
|
||||
{ operation: "runs.search", patterns: ["paperclip_git_storage_limit"] },
|
||||
{ operation: "runs.search", companyId, patterns: ["paperclip_git_storage_limit"], includeExcerpts: true },
|
||||
])
|
||||
expect(inspectionReadPath(parseInspectionQuery(value))).toEqual("/read-v3");
|
||||
for (const value of [
|
||||
{ operation: "count", companyId },
|
||||
{ operation: "list", resource: "runs" },
|
||||
{ operation: "count", resource: "runs", companyId, resourceId: agentId },
|
||||
{ operation: "get", resource: "runs", companyId, resourceId: agentId, order: "newest" },
|
||||
{ operation: "list", resource: "runs", companyId, order: "random" },
|
||||
{ operation: "list", resource: "tasks", companyId, view: "summary" },
|
||||
{ operation: "list", resource: "runs", companyId, view: "full" },
|
||||
{ operation: "runs.log", companyId, resourceId: agentId, view: "summary" },
|
||||
{ operation: "runs.search", patterns: [] },
|
||||
{ operation: "runs.search", patterns: ["a", "b", "c", "d", "e", "f"] },
|
||||
{ operation: "runs.search", patterns: ["dup", "DUP"] },
|
||||
{ operation: "runs.search", patterns: ["paperclip_git_storage_limit"], includeExcerpts: true },
|
||||
{ operation: "runs.search", patterns: ["ok"], resource: "runs" },
|
||||
{
|
||||
operation: "runs.search",
|
||||
patterns: ["ok"],
|
||||
createdAfter: "2026-11-25T00:00:00Z",
|
||||
createdBefore: "2026-11-24T00:00:00Z",
|
||||
},
|
||||
{ operation: "list", resource: "runs", companyId, patterns: ["nope"] },
|
||||
])
|
||||
expect(() => parseInspectionQuery(value)).toThrow();
|
||||
});
|
||||
|
||||
@@ -155,6 +155,7 @@ const explicitOpenApiOperationCoverageExclusions = new Set([
|
||||
"GET /api/customer-success/v1/run-authority",
|
||||
"POST /api/customer-success/v1/read",
|
||||
"POST /api/customer-success/v1/read-v2",
|
||||
"POST /api/customer-success/v1/read-v3",
|
||||
"POST /api/customer-success/v1/run-liveness",
|
||||
// OAuth discovery and protocol endpoints have their own metadata contract;
|
||||
// browser connection-management operations remain documented in the board API.
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
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",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user