The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
feat(sentry): link run errors to task and run pages (#16803)
Dotta51c81d012997
diff --git a/doc/observability.md b/doc/observability.mdindex 3bfa51657d..7666121fc7 100644--- a/doc/observability.md+++ b/doc/observability.md@@ -531,9 +531,10 @@ environment variables: `SENTRY_DSN_FRONTEND` for the browser and`SENTRY_DSN_BACKEND` for the server. Each variable is optional. Aspecific variable always wins for its own component; a legacy variable,`SENTRY_DSN`, supplies a component that has no specific value set. An-empty string counts as absent for all three variables. SDK configuration uses-built-in Sentry options only. It adds no `beforeSend` hook. The run-failure-reporter selects reportable outcomes before calling the SDK, as described below.+empty string counts as absent for all three variables. The server's `beforeSend`+hook adds normal task and run navigation links to events with saved run context.+The run-failure reporter selects reportable outcomes before calling the SDK,+as described below.The server is inactive when the backend DSN resolves to `null`; then itimports no Sentry package. The browser is inactive when the front-end DSN@@ -649,12 +650,15 @@ loaded bundle, even if the server has since deployed another version.### Privacy settings-The feature uses built-in Sentry options only.+Both runtimes use Sentry's privacy options. The server also adds saved-run+navigation links through a bounded `beforeSend` hook.- `sendDefaultPii` is `false`, on both runtimes.- `tracesSampleRate` is `0`, on both runtimes. Paperclip sends noperformance trace and no profile.-- There is no `beforeSend` hook and no custom filter, on either runtime.+- The server hook reads only saved run and company metadata for navigation.+ It copies no request data and preserves the event if the lookup fails.+ The browser adds no `beforeSend` hook. Neither runtime adds a custom filter.### Server request data@@ -728,6 +732,21 @@ The event never includes an API key or an access token. These references grantno access. A bot must authenticate to the correct instance and pass its existingcompany, run-output, and private-task access checks.+Server events associated with a saved run also include `task_url` and `run_url`+tags for the normal company-prefixed board pages, plus `task_identifier` when+available. The `paperclip` context contains the same navigation links as+`taskUrl` and `runPageUrl`; the existing `runUrl` remains an API reference.+This enrichment applies to run failures, adapter Stop timeouts, and server errors+with authenticated run context. It resolves the saved company, agent, and task+instead of copying request URLs, queries, or bodies. Taskless runs receive only a+run link. Missing or unsafe `PAPERCLIP_PUBLIC_URL` values omit these links.+The optional indexed metadata lookup has a one-second reporting deadline and a+limit of eight unfinished reads. A failed or slow lookup preserves the original+event without navigation links.+URLs longer than Sentry's 200-character tag limit remain in context only.+Links require the viewer's normal Paperclip access and apply to newly captured+events; existing Sentry events are not rewritten.+The bot should use the exact run ID to read `GET /api/heartbeat-runs/{runId}`,`GET /api/heartbeat-runs/{runId}/events`, and`GET /api/heartbeat-runs/{runId}/log`. These retain the saved result, run context,diff --git a/server/src/__tests__/error-handler.test.ts b/server/src/__tests__/error-handler.test.tsindex 8ef380af6f..c75952fc84 100644--- a/server/src/__tests__/error-handler.test.ts+++ b/server/src/__tests__/error-handler.test.ts@@ -51,6 +51,15 @@ describe("errorHandler", () => {telemetryMocks.trackErrorHandlerCrash.mockReset();});+ it("passes only authenticated run identity to Sentry for a run-related server error", () => {+ const req = makeReq();+ req.actor = { type: "agent", runId: "run", companyId: "company", agentId: "agent" };+ const error = new Error("run request failed");+ errorHandler(error, req, makeRes(), vi.fn());+ expect(captureExceptionMock).toHaveBeenCalledWith(error, { runId: "run", companyId: "company", agentId: "agent" });+ expect(JSON.stringify(captureExceptionMock.mock.calls)).not.toContain('"a":1');+ });+it("attaches the original Error to res.err for 500s", () => {const req = makeReq();const res = makeRes() as any;diff --git a/server/src/__tests__/run-failure-sentry-real-sdk.test.ts b/server/src/__tests__/run-failure-sentry-real-sdk.test.tsindex a4f4c22d95..c42cd1267a 100644--- a/server/src/__tests__/run-failure-sentry-real-sdk.test.ts+++ b/server/src/__tests__/run-failure-sentry-real-sdk.test.ts@@ -363,11 +363,10 @@ describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK",...Sentry,init: (options: Record<string, unknown>) => Sentry.init({...options,- transport: () => ({ send: async () => ({}), flush: async () => true }),- beforeSend: (event: Record<string, unknown>) => {- events.push(event);- return event;- },+ transport: () => ({ send: async (envelope: [unknown, Array<[{ type: string }, Record<string, unknown>]>]) => {+ for (const [header, payload] of envelope[1]) if (header.type === "event") events.push(payload);+ return {};+ }, flush: async () => true }),}),}));vi.resetModules();@@ -386,6 +385,13 @@ describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK",exitCode: 1,signal: null,};+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example.com");+ const { setSentryRunLinkResolver } = await import("../sentry-links.js");+ setSentryRunLinkResolver(async ({ runId }) => ({+ companyId: first.companyId, companyPrefix: "TEAM", agentId: first.agentId,+ taskId: runId === first.runId ? first.taskId : "33333333-3333-4333-8333-333333333333",+ taskIdentifier: runId === first.runId ? "TEAM-42" : "TEAM-43",+ }));const second = {...first,taskId: "33333333-3333-4333-8333-333333333333",@@ -422,9 +428,14 @@ describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK",signal: "private-signal-payload",});captureException(new Error("unrelated filesystem error"));+ captureException(new Error("run-related request error"), {+ runId: first.runId, companyId: first.companyId, agentId: first.agentId,+ });+ const { AdapterStopTimeoutError } = await import("../services/adapter-stop-timeout.js");+ captureException(new AdapterStopTimeoutError(60_000, { runId: first.runId }));await Sentry.flush(2000);- expect(events).toHaveLength(5);+ expect(events).toHaveLength(7);const captured = (message: string) => events.find((event) =>(event.exception as { values: Array<{ value: string }> }).values.some((value) => value.value === message),);@@ -445,6 +456,14 @@ describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK",expect(JSON.stringify(events)).not.toContain("private-signal-payload");const firstCapture = captured(first.errorMessage)!;expect(firstCapture).toHaveProperty("contexts.paperclip.runPath", `/api/heartbeat-runs/${first.runId}`);+ expect(firstCapture).toMatchObject({ tags: {+ task_url: "https://paperclip.example.com/TEAM/issues/TEAM-42",+ run_url: `https://paperclip.example.com/TEAM/agents/${first.agentId}/runs/${first.runId}`,+ }, contexts: { paperclip: { taskUrl: "https://paperclip.example.com/TEAM/issues/TEAM-42" } } });+ expect(captured(second.errorMessage)).toHaveProperty("tags.task_url", "https://paperclip.example.com/TEAM/issues/TEAM-43");+ expect(captured("run-related request error")).toHaveProperty("tags.task_url", "https://paperclip.example.com/TEAM/issues/TEAM-42");+ expect(events.find(event => (event.tags as Record<string, unknown>)?.error_code === "adapter_stop_unconfirmed"))+ .toHaveProperty("tags.task_url", "https://paperclip.example.com/TEAM/issues/TEAM-42");const exceptions = (firstCapture.exception as { values: Array<Record<string, unknown>> }).values;expect(exceptions).toHaveLength(2);expect(JSON.stringify(exceptions)).toContain("originalAdapter");@@ -467,7 +486,7 @@ describe.skipIf(!sentryPackage)("run failure context with the real Sentry SDK",expect(event).not.toHaveProperty(`contexts.${context}`);}expect(event).not.toHaveProperty("fingerprint");- for (const tag of ["run_id", "task_id", "error_code", "agent_adapter", "run_status"]) {+ for (const tag of ["run_id", "task_id", "error_code", "agent_adapter", "run_status", "task_url", "run_url", "task_identifier"]) {expect(event).not.toHaveProperty(`tags.${tag}`);}}diff --git a/server/src/__tests__/sentry-links.test.ts b/server/src/__tests__/sentry-links.test.tsnew file mode 100644index 0000000000..561842b9b3--- /dev/null+++ b/server/src/__tests__/sentry-links.test.ts@@ -0,0 +1,114 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { addSentryRunLinks, setSentryRunLinkResolver } from "../sentry-links.js";++const runId = "22222222-2222-4222-8222-222222222222";+const companyId = "55555555-5555-4555-8555-555555555555";+const agentId = "66666666-6666-4666-8666-666666666666";+const taskId = "11111111-1111-4111-8111-111111111111";+const identity = { companyId, companyPrefix: "TEAM", agentId, taskId, taskIdentifier: "TEAM-42" };++afterEach(() => {+ setSentryRunLinkResolver(null);+ vi.unstubAllEnvs();+ vi.useRealTimers();+});++describe("Sentry navigation links", () => {+ it("adds normal UI URLs to run failures and Stop errors without changing API references or unrelated events", async () => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example.com");+ const resolve = vi.fn(async () => identity);+ setSentryRunLinkResolver(resolve);+ const event = { tags: { run_id: runId, company_id: companyId }, contexts: { paperclip: { runUrl: "/api/original" } }, fingerprint: ["failure"] };+ const linked = await addSentryRunLinks(event);+ const runUrl = `https://paperclip.example.com/TEAM/agents/${agentId}/runs/${runId}`;+ expect(linked).toMatchObject({ tags: { task_url: "https://paperclip.example.com/TEAM/issues/TEAM-42", run_url: runUrl, task_identifier: "TEAM-42" },+ contexts: { paperclip: { runUrl: "/api/original", runPageUrl: runUrl, taskUrl: "https://paperclip.example.com/TEAM/issues/TEAM-42" } }, fingerprint: ["failure"] });+ expect(resolve).toHaveBeenCalledWith({ runId, companyId });+ expect(await addSentryRunLinks({ contexts: { adapter_stop: { runId } } })).toMatchObject({ tags: { run_url: runUrl } });+ const unrelated = { tags: { error_code: "unrelated" } };+ expect(await addSentryRunLinks(unrelated)).toEqual(unrelated);+ expect(resolve).toHaveBeenCalledTimes(2);+ });++ it("falls back to the task UUID and omits task links for taskless runs", async () => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "http://localhost:3100");+ setSentryRunLinkResolver(async () => ({ ...identity, taskIdentifier: null }));+ expect(await addSentryRunLinks({ tags: { run_id: runId } })).toMatchObject({ tags: { task_url: `http://localhost:3100/TEAM/issues/${taskId}` } });+ setSentryRunLinkResolver(async () => ({ ...identity, taskId: null, taskIdentifier: null }));+ const result = await addSentryRunLinks({ tags: { run_id: runId } });+ expect(result.tags).toHaveProperty("run_url");+ expect(result.tags).not.toHaveProperty("task_url");+ expect(result.tags).not.toHaveProperty("task_identifier");+ });++ it.each([17, 210])("keeps navigation for a saved %i-character company prefix within tag limits", async length => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example.com");+ const companyPrefix = "A".repeat(length);+ const taskIdentifier = `${companyPrefix}-42`;+ setSentryRunLinkResolver(async () => ({ ...identity, companyPrefix, taskIdentifier }));+ const linked = await addSentryRunLinks({ tags: { run_id: runId } });+ const taskUrl = `https://paperclip.example.com/${companyPrefix}/issues/${taskIdentifier}`;+ expect(linked).toHaveProperty("contexts.paperclip.taskUrl", taskUrl);+ expect(linked).toHaveProperty("contexts.paperclip.runPageUrl");+ if (length === 17) {+ expect(linked.tags).toHaveProperty("task_identifier", taskIdentifier);+ expect(linked.tags).toHaveProperty("task_url", taskUrl);+ } else {+ expect(linked.tags).not.toHaveProperty("task_identifier");+ expect(linked.tags).not.toHaveProperty("task_url");+ expect(linked.tags).not.toHaveProperty("run_url");+ }+ });++ it.each(["https://user:[email protected]", "https://example.com?secret=token", "https://example.com/#private", "https://example.com/private", "ftp://example.com", "invalid", ""])("omits unsafe instance origins without a database lookup: %s", async origin => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", origin);+ const resolve = vi.fn(async () => identity);+ setSentryRunLinkResolver(resolve);+ const event = { tags: { run_id: runId } };+ expect(await addSentryRunLinks(event)).toEqual(event);+ expect(resolve).not.toHaveBeenCalled();+ });++ it("does not widen a malformed company identity or put long URLs in tags", async () => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", `https://${"a".repeat(60)}.${"b".repeat(60)}.example.com`);+ const resolve = vi.fn(async () => identity);+ setSentryRunLinkResolver(resolve);+ await addSentryRunLinks({ tags: { run_id: runId, company_id: "private-invalid" } });+ expect(resolve).not.toHaveBeenCalled();+ const linked = await addSentryRunLinks({ tags: { run_id: runId } });+ expect(linked.tags).not.toHaveProperty("run_url");+ expect(linked).toHaveProperty("contexts.paperclip.runPageUrl");+ });++ it("preserves the error on lookup rejection and bounds a stalled lookup", async () => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example.com");+ const event = { tags: { run_id: runId } };+ setSentryRunLinkResolver(async () => { throw new Error("database unavailable"); });+ expect(await addSentryRunLinks(event)).toEqual(event);+ vi.useFakeTimers();+ let finish!: (value: typeof identity) => void;+ setSentryRunLinkResolver(() => new Promise(resolve => { finish = resolve; }));+ const pending = addSentryRunLinks(event);+ await vi.advanceTimersByTimeAsync(1_000);+ expect(await pending).toEqual(event);+ finish(identity);+ await Promise.resolve();+ expect(event.tags).not.toHaveProperty("task_url");+ });++ it("limits abandoned database lookups while continuing to send subsequent errors", async () => {+ vi.stubEnv("PAPERCLIP_PUBLIC_URL", "https://paperclip.example.com");+ vi.useFakeTimers();+ const releases: Array<(value: typeof identity) => void> = [];+ const resolve = vi.fn(() => new Promise<typeof identity>(done => releases.push(done)));+ setSentryRunLinkResolver(resolve);+ const pending = Array.from({ length: 8 }, () => addSentryRunLinks({ tags: { run_id: runId } }));+ await vi.advanceTimersByTimeAsync(1_000);+ await Promise.all(pending);+ const ninth = { tags: { run_id: runId } };+ expect(await addSentryRunLinks(ninth)).toEqual(ninth);+ expect(resolve).toHaveBeenCalledTimes(8);+ releases.forEach(release => release(identity));+ await Promise.resolve();+ });+});diff --git a/server/src/index.ts b/server/src/index.tsindex 409b35da93..6d33c9742a 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -23,6 +23,8 @@ import { chatCompletionDeliveryService } from "./services/chat-completion-delive// HTTP server, so trace coverage does not depend on incidental timing.import { instrumentationReady, shutdownInstrumentation } from "./instrumentation.js";import { sentryReady, shutdownSentry, captureException } from "./sentry.js";+import { setSentryRunLinkResolver } from "./sentry-links.js";+import { createSentryRunLinkResolver } from "./services/sentry-run-links.js";import { waitForPendingRunFailureReports } from "./services/run-failure-report.js";import { verifyStoppedNativeSessionForReplacement } from "./services/native-runtime/native-session-executor.js";import { embeddedPostgresOwnerPort } from "./embedded-postgres-owner.js";@@ -660,10 +662,12 @@ async function startServerWithDatabaseTeardown(// (after the application services, before the embedded provider stops) and// by the fail-loud startup path, so no exit leaves pooled backends behind.const closeDatabaseClients = async () => {+ setSentryRunLinkResolver(null);const clients = pluginMigrationDb === db ? [db] : [db, pluginMigrationDb];await Promise.all(clients.map((client) => endDatabaseClient(client, 5)));};startupDatabase.close = closeDatabaseClients;+ setSentryRunLinkResolver(createSentryRunLinkResolver(db));// A claimed warm-pool stack may restart while its provider environment still// names the pool host. Restore the signed, durable identity before Betterdiff --git a/server/src/middleware/error-handler.ts b/server/src/middleware/error-handler.tsindex 4300267c88..b4022b67c2 100644--- a/server/src/middleware/error-handler.ts+++ b/server/src/middleware/error-handler.ts@@ -88,10 +88,14 @@ function sanitizeSecretSensitiveResponse(}/** Report a server-side crash to every error sink. */-function reportCrash(error: Error, reportToSentry = true): void {+function reportCrash(error: Error, req: Request, reportToSentry = true): void {const tc = getTelemetryClient();if (tc) trackErrorHandlerCrash(tc, { errorCode: error.name });- if (reportToSentry) captureException(error);+ if (reportToSentry) {+ if (req.actor?.type === "agent" && req.actor.runId && req.actor.companyId && req.actor.agentId) {+ captureException(error, { runId: req.actor.runId, companyId: req.actor.companyId, agentId: req.actor.agentId });+ } else captureException(error);+ }}/** Set by the orderly shutdown just before it ends the database pools. */@@ -186,7 +190,7 @@ export function errorHandler(},reportableError,);- reportCrash(reportableError, !isExpectedMcpConnectionFailure(err));+ reportCrash(reportableError, req, !isExpectedMcpConnectionFailure(err));}const secretSensitiveServerError =err.status >= 500 &&@@ -305,7 +309,7 @@ export function errorHandler(reportableError,);- reportCrash(reportableError);+ reportCrash(reportableError, req);res.status(500).json({error: "Internal server error",diff --git a/server/src/sentry-links.ts b/server/src/sentry-links.tsnew file mode 100644index 0000000000..8920d060b8--- /dev/null+++ b/server/src/sentry-links.ts@@ -0,0 +1,85 @@+export interface SentryRunReference {+ runId: string;+ companyId?: string;+ agentId?: string;+}++export interface SentryRunLinks {+ companyId: string;+ companyPrefix: string;+ agentId: string;+ taskId: string | null;+ taskIdentifier: string | null;+}++export type SentryRunLinkResolver = (reference: SentryRunReference) => Promise<SentryRunLinks | null>;++interface LinkableEvent {+ tags?: Record<string, string | number | boolean | bigint | symbol | null | undefined>;+ contexts?: Record<string, Record<string, unknown> | null | undefined>;+}++let resolveRunLinks: SentryRunLinkResolver | null = null;+const pendingLookups = new Set<Promise<SentryRunLinks | null>>();+const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;++/** The database is supplied after startup; no run identity lives on an SDK scope. */+export function setSentryRunLinkResolver(resolver: SentryRunLinkResolver | null) {+ resolveRunLinks = resolver;+}++/** Enrich only events already associated with a run. Never read a request URL or body. */+export async function addSentryRunLinks<T extends LinkableEvent>(event: T): Promise<T> {+ const runId = event.tags?.run_id ?? event.contexts?.adapter_stop?.runId;+ const resolver = resolveRunLinks;+ if (!resolver || typeof runId !== "string" || !UUID.test(runId)) return event;+ let base: URL;+ try {+ base = new URL(process.env.PAPERCLIP_PUBLIC_URL ?? "");+ if (!["http:", "https:"].includes(base.protocol) || base.username || base.password ||+ base.search || base.hash || base.pathname !== "/") return event;+ } catch { return event; }++ const companyId = event.tags?.company_id;+ const agentId = event.tags?.agent_id;+ // A malformed supplied identity must not widen a lookup to another company.+ if (companyId != null && (typeof companyId !== "string" || !UUID.test(companyId))) return event;+ if (agentId != null && (typeof agentId !== "string" || !UUID.test(agentId))) return event;+ // A deadline cannot cancel a pooled database read. Bound unfinished reads so+ // repeated errors during an outage cannot build an unbounded lookup queue.+ if (pendingLookups.size >= 8) return event;+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const lookup = resolver({ runId, ...(companyId ? { companyId } : {}), ...(agentId ? { agentId } : {}) });+ pendingLookups.add(lookup);+ void lookup.then(() => pendingLookups.delete(lookup), () => pendingLookups.delete(lookup));+ // Optional navigation metadata must not hold an error report behind a slow+ // database. The indexed lookup may finish later; it cannot mutate this event.+ const links = await Promise.race([+ lookup,+ new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), 1_000); }),+ ]);+ if (!links || !/^[A-Z][A-Z0-9]*$/.test(links.companyPrefix) || !UUID.test(links.agentId) ||+ (companyId && links.companyId !== companyId) || (agentId && links.agentId !== agentId)) return event;+ const prefix = `/${links.companyPrefix}`;+ const runUrl = new URL(`${prefix}/agents/${links.agentId}/runs/${runId}`, base).href;+ const identifier = links.taskIdentifier;+ const taskKey = identifier && new RegExp(`^${links.companyPrefix}-[1-9][0-9]*$`).test(identifier)+ ? identifier : links.taskId && UUID.test(links.taskId) ? links.taskId : null;+ const taskUrl = taskKey ? new URL(`${prefix}/issues/${taskKey}`, base).href : null;+ // Sentry tag values are bounded to 200 characters. Keep a full long-host URL+ // in context instead of emitting a truncated, unusable navigation tag.+ event.tags = { ...event.tags,+ ...(runUrl.length <= 200 ? { run_url: runUrl } : {}),+ ...(taskUrl && taskUrl.length <= 200 ? { task_url: taskUrl } : {}),+ ...(identifier && identifier.length <= 200 && taskKey === identifier ? { task_identifier: identifier } : {}),+ };+ event.contexts = { ...event.contexts, paperclip: {+ ...event.contexts?.paperclip,+ runPageUrl: runUrl,+ ...(taskUrl ? { taskUrl } : {}),+ } };+ } catch { /* Link enrichment must not discard the original error. */ }+ finally { if (timer) clearTimeout(timer); }+ return event;+}diff --git a/server/src/sentry.ts b/server/src/sentry.tsindex fa414645ff..09870d9814 100644--- a/server/src/sentry.ts+++ b/server/src/sentry.ts@@ -63,6 +63,7 @@ import { readBuildCommit } from "./build-commit.js";import { checkExactPeerVersions } from "./peer-version-check.js";import { resolveSentryDsns } from "./sentry-dsn.js";import { readRunFailureReportingMode } from "./sentry-run-failure-policy.js";+import { addSentryRunLinks, type SentryRunReference } from "./sentry-links.js";const { backend: dsn, legacyFallbackUsed } = resolveSentryDsns();@@ -106,15 +107,20 @@ export const sentryReady: Promise<void> = dsn ? bootstrapSentry(dsn) : Promise.r* never opens (the backend DSN resolves to `null`), or when bootstrap* failed. Never throws — observability must not change control flow.*/-export function captureException(error: unknown): void {+export function captureException(error: unknown, reference?: SentryRunReference): void {if (!sentryHandle) return;try {+ const tags = reference ? {+ run_id: reference.runId,+ ...(reference.companyId ? { company_id: reference.companyId } : {}),+ ...(reference.agentId ? { agent_id: reference.agentId } : {}),+ } : {};if (error instanceof AdapterStopTimeoutError) {// Event-local, fixed-shape context: no ambient scope or raw error fields.const exception = new Error(error.message);exception.stack = error.stack;sentryHandle.captureException(exception, {- tags: { error_code: "adapter_stop_unconfirmed" },+ tags: { ...tags, error_code: "adapter_stop_unconfirmed" },contexts: { adapter_stop: { ...error.diagnostics } },fingerprint: ["{{ default }}"],});@@ -122,10 +128,12 @@ export function captureException(error: unknown): void {const exception = new Error(error.message);exception.stack = error.stack;sentryHandle.captureException(exception, {- tags: { error_code: "cloud_portfolio_failure" },+ tags: { ...tags, error_code: "cloud_portfolio_failure" },contexts: { cloud_portfolio: { ...CloudPortfolioError.diagnosticsFor(error) } },fingerprint: ["{{ default }}"],});+ } else if (reference) {+ sentryHandle.captureException(error, { tags, contexts: {}, fingerprint: ["{{ default }}"] });} else {sentryHandle.captureException(error);}@@ -323,6 +331,7 @@ export interface SentryInitOptions {sendDefaultPii: boolean;serverName: string;integrations: (defaults: Array<{ name: string }>) => Array<{ name: string }>;+ beforeSend: typeof addSentryRunLinks;}/**@@ -341,6 +350,7 @@ export function buildSentryInitOptions(skipOpenTelemetrySetup: true,tracesSampleRate: 0,sendDefaultPii: false,+ beforeSend: addSentryRunLinks,serverName: process.env.SENTRY_NAME || os.hostname(),integrations: (defaults: Array<{ name: string }>) => {const kept = defaults.filter(diff --git a/server/src/services/__tests__/sentry-run-links.test.ts b/server/src/services/__tests__/sentry-run-links.test.tsnew file mode 100644index 0000000000..2b3c52b5f9--- /dev/null+++ b/server/src/services/__tests__/sentry-run-links.test.ts@@ -0,0 +1,76 @@+import { randomUUID } from "node:crypto";+import { eq, inArray } from "drizzle-orm";+import { expect, it } from "vitest";+import {+ agents,+ applyPendingMigrations,+ closeRegisteredClients,+ companies,+ createDb,+ EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,+ heartbeatRuns,+ issues,+} from "@paperclipai/db";+import {+ getEmbeddedPostgresTestSupport,+ startEmbeddedPostgresTestDatabase,+} from "../../__tests__/helpers/embedded-postgres.js";+import { createSentryRunLinkResolver } from "../sentry-run-links.js";++const testDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL;+const support = testDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();++it.skipIf(!support.supported)("resolves saved task links and rejects foreign company, agent, and task identities", async () => {+ const tempDb = testDatabaseUrl ? null : await startEmbeddedPostgresTestDatabase("paperclip-sentry-links-");+ const databaseUrl = testDatabaseUrl ?? tempDb!.connectionString;+ const db = createDb(databaseUrl);+ const companyIds: string[] = [];+ try {+ if (testDatabaseUrl) await applyPendingMigrations(testDatabaseUrl);+ const companyPrefix = `T${randomUUID().replaceAll("-", "").toUpperCase()}`;+ const taskIdentifier = `${companyPrefix}-42`;+ const [company] = await db.insert(companies).values({ name: "Fixture", issuePrefix: companyPrefix }).returning();+ const companyId = company!.id;+ companyIds.push(companyId);+ const [agent] = await db.insert(agents).values({+ companyId, name: "Fixture", role: "engineer", adapterType: "codex_local",+ }).returning();+ const agentId = agent!.id;+ const [task] = await db.insert(issues).values({ companyId, title: "Fixture task", identifier: taskIdentifier }).returning();+ const [run] = await db.insert(heartbeatRuns).values({+ companyId, agentId, invocationSource: "assignment", status: "failed", issueId: task!.id,+ }).returning();+ const resolve = createSentryRunLinkResolver(db);+ expect(await resolve({ runId: run!.id, companyId, agentId })).toMatchObject({+ companyId, agentId, companyPrefix, taskId: task!.id, taskIdentifier,+ });+ expect(await resolve({ runId: run!.id, companyId: randomUUID() })).toBeNull();+ expect(await resolve({ runId: run!.id, agentId: randomUUID() })).toBeNull();+ const otherPrefix = `O${randomUUID().replaceAll("-", "").toUpperCase()}`;+ const [other] = await db.insert(companies).values({ name: "Other", issuePrefix: otherPrefix }).returning();+ companyIds.push(other!.id);+ const [otherTask] = await db.insert(issues).values({+ companyId: other!.id, title: "Other task", identifier: `${otherPrefix}-1`,+ }).returning();+ const [taskless] = await db.insert(heartbeatRuns).values({+ companyId, agentId, invocationSource: "assignment", status: "failed",+ }).returning();+ expect(await resolve({ runId: taskless!.id })).toMatchObject({ taskId: null, taskIdentifier: null });+ await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: otherTask!.id } }).where(eq(heartbeatRuns.id, taskless!.id));+ expect(await resolve({ runId: taskless!.id })).toMatchObject({ taskId: null, taskIdentifier: null });+ await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: task!.id } }).where(eq(heartbeatRuns.id, taskless!.id));+ expect(await resolve({ runId: taskless!.id })).toMatchObject({ taskId: task!.id, taskIdentifier });+ } finally {+ try {+ if (testDatabaseUrl && companyIds.length) {+ await db.delete(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds));+ await db.delete(issues).where(inArray(issues.companyId, companyIds));+ await db.delete(agents).where(inArray(agents.companyId, companyIds));+ await db.delete(companies).where(inArray(companies.id, companyIds));+ }+ } finally {+ if (testDatabaseUrl) await closeRegisteredClients(testDatabaseUrl);+ await tempDb?.cleanup();+ }+ }+}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);diff --git a/server/src/services/sentry-run-links.ts b/server/src/services/sentry-run-links.tsnew file mode 100644index 0000000000..00f4c41f6b--- /dev/null+++ b/server/src/services/sentry-run-links.ts@@ -0,0 +1,30 @@+import { and, eq, sql } from "drizzle-orm";+import { companies, heartbeatRuns, issues, type Db } from "@paperclipai/db";+import type { SentryRunLinkResolver } from "../sentry-links.js";++/** Two indexed, company-bound metadata reads; no prompt, output, or credentials. */+export function createSentryRunLinkResolver(db: Db): SentryRunLinkResolver {+ return async ({ runId, companyId, agentId }) => {+ const [run] = await db.select({+ companyId: heartbeatRuns.companyId,+ agentId: heartbeatRuns.agentId,+ issueId: heartbeatRuns.issueId,+ nativeIssueId: heartbeatRuns.nativeIssueId,+ contextIssueId: sql<string | null>`${heartbeatRuns.contextSnapshot}->>'issueId'`,+ }).from(heartbeatRuns).where(and(+ eq(heartbeatRuns.id, runId),+ companyId ? eq(heartbeatRuns.companyId, companyId) : undefined,+ agentId ? eq(heartbeatRuns.agentId, agentId) : undefined,+ )).limit(1);+ if (!run) return null;+ const candidate = run.issueId ?? run.nativeIssueId ?? run.contextIssueId;+ const taskId = candidate && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(candidate) ? candidate : null;+ const [metadata] = await db.select({ companyPrefix: companies.issuePrefix, taskId: issues.id, taskIdentifier: issues.identifier })+ .from(companies).leftJoin(issues, and(+ eq(issues.companyId, companies.id),+ taskId ? eq(issues.id, taskId) : sql`false`,+ )).where(eq(companies.id, run.companyId)).limit(1);+ if (!metadata) return null;+ return { ...run, ...metadata };+ };+}