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