πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
docs(agents): add sentry-instrumentation skill (LFE-10974) (#15249)
Nikita Kabardin7a4a902d7e88
diff --git a/.agents/skills/sentry-instrumentation/SKILL.md b/.agents/skills/sentry-instrumentation/SKILL.mdnew file mode 100644index 0000000000..f75d1253fa--- /dev/null+++ b/.agents/skills/sentry-instrumentation/SKILL.md@@ -0,0 +1,177 @@+---+name: sentry-instrumentation+description: |+ Capture errors in Langfuse with Sentry deliberately, and decide whether a new+ error path should report at all. Use when (1) adding or touching any+ `captureException`, `console.error`, error boundary, `catch` block, Worker+ `onerror`, or tRPC/REST error handler in `web/**` β pause and decide capture+ before finishing; (2) adding or reviewing a Sentry `beforeSend` filter,+ denylist rule, `ignoreErrors`, `denyUrls`, or any noise-suppression change+ (MANDATORY here β the review question is "does this rule hide a real+ error?"); (3) asked to reduce Sentry noise, triage a Sentry issue, or answer+ "why is X / isn't X in Sentry"; (4) rendering user-supplied content (URLs,+ hrefs) through a framework primitive that may reject it and log an error.+---++# Sentry Instrumentation++**One idea:** an event in Sentry is a **promise that a human should act.** If+nobody would act on it, do not send it. If you send it, make it **legible** (a+real `Error` with a stack β never a string/object/SyntheticEvent) and+**routable** (an `area` tag, a message stable enough to group). Sentry is not a+log sink; the server-side observability stack is where firehose logs live.++## Decide capture when adding an error path++When adding or changing an error path in `web/**`, decide explicitly whether it+should reach Sentry β do not `captureException` (or `console.error`) reflexively.+Run the decision tree, then say in one line what you chose and why (in the plan+or PR description). The three outcomes:++| The failure isβ¦ | Do | Never |+|---|---|---|+| an **expected user-facing state** β a missing/forbidden resource, expired session, invalid user input, a malformed URL in user content | render the UX (error page / toast / plain text) | capture β it is the product working as designed |+| a **transport / offline / infra** failure β fetch failed, a 5xx on a poll, an LB blip | let the UI degrade; the server owns this signal | capture client-side β it is an amplified, lower-fidelity copy of a server truth |+| **our code failed** β an invariant broke, a parse threw, a worker failed to load | `captureException` a **real `Error`** with an `area` tag via the shared helpers | pass a raw string/object/`Event` |++**`console.error` is a capture API here.** `instrumentation-client.ts` enables+`captureConsoleIntegration({ levels: ["error"] })`, so **every `console.error`+becomes a Sentry event.** Logging an object yields an opaque `[object Object]`+fingerprint; logging non-actionable info still mints an issue. For+non-actionable logging use `console.warn`; to report a real failure, capture it+properly (below).++## The Langfuse pattern (match it exactly)++- **Report caught unknowns through the shared helpers, not raw+ `captureException`:**+ - [`captureUnknownError(context, value, extra?)`](../../../web/src/utils/captureUnknownError.ts)+ β turns any caught value into a legible `Error` (real `Error`s pass through+ with their stack; everything else is synthesized), tags `area`, and logs via+ `console.warn` so the console integration does not double-capture.+ - [`reportParserWorkerError(hook, event)`](../../../web/src/hooks/parserWorkerError.ts)+ β extracts the real fields from a Worker `ErrorEvent` (message/filename/lineno)+ instead of stringifying it to `[object ErrorEvent]`.+- **Filter predicates belong in+ [`web/src/utils/sentryFilters.ts`](../../../web/src/utils/sentryFilters.ts)**+ (documented, unit-tested), called from `beforeSend` in+ [`web/instrumentation-client.ts`](../../../web/instrumentation-client.ts) (the+ only `Sentry.init` in the codebase β `beforeSend`,+ `captureConsoleIntegration`, `denyUrls`, replay masking). Add every new filter+ as a named predicate there, never as an ad-hoc inline check. `beforeSend`+ still carries a couple of legacy inline checks (invalid-href, React-devtools)+ that predate this convention and read only the exception value β migrate those+ into named, all-field predicates; do not add more inline checks.+- **Classify tRPC errors at the seam,** not per call site: `handleTrpcError`+ ([`web/src/utils/api.ts`](../../../web/src/utils/api.ts)) is the single+ chokepoint every query/mutation error flows through β the place to drop+ expected codes and tag the rest (the seam-classification lever, PR #15243).+- **Tag `area`, keep the message static.** `captureException(err, { tags: { area },+ extra })`. Fingerprints group on the message, so put variable IDs in `extra`,+ never in the message string.++## The rules (each earned the hard way β cited to workstream PRs)++> PR references name the **lever** that established each pattern. Verify a cited+> symbol or swap against the current tree before relying on it β the code, not+> this doc, is the source of truth.++1. **An event is a promise a human acts β expected states are not events.**+ A `NOT_FOUND` / `FORBIDDEN` / `UNAUTHORIZED` the UI already renders is not a+ regression. β `TRPCClientError: Trace not found` was the #2 issue by volume+ (~30k events); PR #15243 drops those at the tRPC seam and switches the+ "Project Not Found" state (which captured on every mount via+ `ErrorPageWithSentry`) to the non-capturing `ErrorPage`.++2. **Capture a REAL `Error`, never a string / object / `SyntheticEvent` /+ `ErrorEvent`.** Those collapse to opaque `[object Object]` / `[object+ ErrorEvent]` fingerprints with no stack. β The 5EX cluster (opaque non-Error+ captures, PR #15175) and the parse-worker `[object ErrorEvent]` family (PR+ #15173) were exactly this. Route unknowns through `captureUnknownError` /+ `reportParserWorkerError`.++3. **`console.error` mints a Sentry event β pick the level deliberately.** Use+ `console.warn` for non-actionable logs (the #15173 pattern); use+ `captureException` for real failures. Never `console.error(someObject)`.++4. **Client transport failure β app bug β do not amplify server/infra state.**+ One LB 502 or a poll blip becomes thousands of browser events. β The 418+ `HTTP Client Error` saga (~44k events β 8/24h after scoping the httpClient+ integration, PR #15145) and the next-auth `CLIENT_FETCH_ERROR` /+ `Failed to fetch` families (denylist, PR #15238). The real outage is visible+ server-side; the client copy is noise.++5. **Root-cause at the source beats a filter.** Prefer eliminating the emission+ over suppressing the event. β User-content markdown URLs rendered through a+ Next.js `<Link>` logged `Invalid href β¦ passed to next/router` (~40k events)+ β note `getSafeLinkUrl` does NOT prevent this: a malformed-but-parseable URL+ (a second `https://` β repeated `//`) passes validation and `<Link>`'s router+ still rejects it. PR #15245 renders these as a native `<a>` (which never runs+ the router's href validation), removing the family at the source β no new+ filter needed. (The older inline `beforeSend` invalid-href check is redundant+ and never fired anyway β it read the wrong field, Rule 6 β so it can be+ retired.)++6. **Every `beforeSend` / denylist rule: narrow signature + written rationale ++ a NEGATIVE fixture proving a real error still passes.** This is the MANDATORY+ review gate β for any suppression change, answer "does this rule hide a real+ error?" in the PR, and add a test asserting a real 5xx / unknown code / thrown+ error is NOT dropped (the `sentryFilters.clienttest.ts` pattern from #15145 /+ #15238). β **Read the right event field:** message-type events (console+ captures, benign strings) carry their text on `event.message` /+ `event.logentry.message`, NOT `event.exception.values[0].value` β a filter+ that only reads the exception value silently never fires on them (the reason+ the original invalid-href filter never worked).++7. **PII β never put user content in a message, `extra`, or tag.** No prompt+ text, trace content, tokens, share-link secrets, user/session ids. Respect+ the replay masking already configured for HIPAA/regions in+ `instrumentation-client.ts`. A message that interpolates user data both leaks+ and shatters grouping (Rule 5).++8. **VERIFY in the environment that actually fires the error.** Router/console+ validations run only in the **real client runtime, not jsdom** β a green unit+ test does NOT prove the console error is gone. Reproduce it in a browser+ against the running app (Playwright), do an A/B, and confirm the event+ disappears. β PR #15245 was verified this way β its native `<a>` fired 0+ where the prior `<Link>` fired the error Γ12. Unit tests lock the *contract*; the+ browser proves the *noise removal*.++## Workflow++1. **Classify (tiny).** For the error path, name the outcome β expected /+ transport / our-code β and write the one-line decision. That IS the PR note.+2. **Wire it.** Expected β render UX (no capture). Transport β degrade (no+ capture). Real β `captureException` a real `Error` via the helpers, with an+ `area` tag, static message, structured `extra`, no PII.+3. **If suppressing:** add a named predicate in `sentryFilters.ts` reading the+ right event field, with a written rationale and a negative fixture (Rule 6).+ Prefer root-causing the emission instead (Rule 5).+4. **Verify** β unit test for the contract; **browser A/B** for the actual+ event removal (Rule 8).+5. **PR** with the decision note; for suppression changes, the explicit+ "does this hide a real error?" answer + the negative-fixture test.++## Anti-patterns++- Capturing an expected 404 / permission / validation / malformed-user-input+ state (Rule 1).+- `captureException(nonError)` or `console.error(object)` β opaque fingerprint+ (Rules 2, 3).+- Re-reporting transport/infra failures the server already owns (Rule 4).+- Adding a `beforeSend` filter with no rationale, no negative fixture, or one+ that reads the wrong event field (Rule 6).+- Interpolating ids/user data into the message β PII + grouping explosion+ (Rules 5, 7).+- Trusting a green jsdom test as proof the noise is gone (Rule 8).+- An ad-hoc inline `beforeSend` check instead of a named, tested predicate in+ `sentryFilters.ts`.++## References++- [references/sentry-capture-contract.md](references/sentry-capture-contract.md)+ β the capture contract in depth: the shared-helper APIs, the beforeSend /+ denylist authoring protocol (field-reading, negative fixtures), fingerprinting+ and `area` tagging, the known noise families, and the shipped-PR case studies+ (#15145 / #15173 / #15174 / #15175 / #15238 / #15243 / #15245). Read when+ authoring a suppression rule, hardening a capture path, or triaging a family.diff --git a/.agents/skills/sentry-instrumentation/references/sentry-capture-contract.md b/.agents/skills/sentry-instrumentation/references/sentry-capture-contract.mdnew file mode 100644index 0000000000..5b42704430--- /dev/null+++ b/.agents/skills/sentry-instrumentation/references/sentry-capture-contract.md@@ -0,0 +1,127 @@+# Sentry capture contract β depth reference++Load when authoring a `beforeSend`/denylist rule, hardening a capture path, or+triaging a noise family. Read the [SKILL.md](../SKILL.md) first β this file is+the detail behind its rules.++## Contents++- [Where Sentry is wired](#where-sentry-is-wired)+- [The shared capture helpers](#the-shared-capture-helpers)+- [beforeSend / denylist authoring protocol](#beforesend--denylist-authoring-protocol)+- [Fingerprinting, tagging, messages](#fingerprinting-tagging-messages)+- [Known noise families](#known-noise-families)+- [Workstream levers (case studies)](#workstream-levers-case-studies)++## Where Sentry is wired++- **The only `Sentry.init`** is [`web/instrumentation-client.ts`](../../../../web/instrumentation-client.ts)+ β client-side only. It configures `beforeSend`, `captureConsoleIntegration({ levels: ["error"] })`,+ `httpClientIntegration()`, `replayIntegration(...)` (masking gated on region/HIPAA),+ and `denyUrls` (browser-extension origins).+- **The worker and web server have no Sentry SDK** β backend signal lives in the+ server-side observability/APM stack, not Sentry. Do not assume a backend error+ reaches Sentry; it does not. (Treat "Sentry = frontend-only" until a decision+ says otherwise.)+- **Filter predicates** live in [`web/src/utils/sentryFilters.ts`](../../../../web/src/utils/sentryFilters.ts)+ with unit tests in `sentryFilters.clienttest.ts`; `beforeSend` calls them.+ `beforeSend` also still carries two legacy inline checks (invalid-href,+ React-devtools) that predate this convention and read only+ `event.exception.values[0].value` β a known gap to migrate into named,+ all-field predicates. Add new filters only as predicates here, never inline.+- **The tRPC seam** is `handleTrpcError` in [`web/src/utils/api.ts`](../../../../web/src/utils/api.ts):+ every query/mutation error flows through it β the single place to classify.+ PR #15243 drops expected `data.code`s (`NOT_FOUND` / `FORBIDDEN` /+ `UNAUTHORIZED`) there with a breadcrumb and tags the rest+ (`trpc.code` / `trpc.path`).++## The shared capture helpers++Prefer these over a raw `captureException`:++```ts+// A caught value of unknown shape (catch block, rejected promise, event handler).+captureUnknownError("io-parse", value, { traceId }); // real Error passes through; else synthesized. tags:{area}, warns (no double-capture)++// A Web Worker onerror ErrorEvent (script failed to load / threw during init).+reportParserWorkerError("useJsonParse", event); // extracts message/filename/lineno; tags:{area:"io-parse-worker"}+```++Both log via `console.warn` (not `console.error`) on purpose β `console.error`+would be re-captured by `captureConsoleIntegration` as a second, opaque event.++If you must capture directly: pass a real `Error`, add `{ tags: { area }, extra }`,+keep the message static, and log any companion console line at `warn`.++## beforeSend / denylist authoring protocol++A suppression rule is a loaded gun aimed at your own signal. Every rule:++1. **Is a named predicate in `sentryFilters.ts`** (e.g. `isNoisyHttpClientPollEvent`),+ never an inline check in `beforeSend`.+2. **Keys on an unambiguous signature** β the Sentry-set exception `mechanism.type`,+ a whole-message match, or a `startsWith`-anchored prefix. Never a loose+ `includes` that could match a real error.+3. **Reads the right event field.** Exception events carry text on+ `event.exception.values[0].value`; **message events (console captures, benign+ strings, `[next-auth]` logs, `Invalid href β¦`) carry it on `event.message` or+ `event.logentry.message`.** A predicate must coalesce all three+ (`exception value ?? event.message ?? event.logentry?.message`) or it silently+ never fires on message events β the exact bug that left the original+ invalid-href filter dead.+4. **Has a written rationale** in a comment: why this signature cannot represent+ a real, actionable error, and where the real signal still lives (usually+ server-side).+5. **Has a NEGATIVE fixture** in `sentryFilters.clienttest.ts` proving a real+ error still passes β a 5xx / unknown code / genuine thrown Error must return+ `false` from the predicate.++Prefer **root-causing the emission** over a filter whenever the source is a+small, identifiable set of call sites (see Rule 5 / the invalid-href case).++## Fingerprinting, tagging, messages++- **Static message β correct grouping.** Sentry groups by message; an+ interpolated id (`Trace ${id} not found`) mints a new fingerprint per id.+ Keep the message constant; put variability in `extra`.+- **`area` tag** on every real capture (`tags: { area: "io-parse-worker" }`) so+ issues route/group by surface. The tRPC seam adds `trpc.code` / `trpc.path`.+- **Explicit `fingerprint`** only when a message legitimately must vary and you+ still want one group β set it on the scope; do not rely on the default.++## Known noise families++The recurring shapes and their correct disposition:++- **Expected tRPC codes** β `Trace not found` (NOT_FOUND), `not a member`+ (FORBIDDEN), expired session (UNAUTHORIZED). β dropped at the seam (#15243).+- **Transport / next-auth** β `Failed to fetch`, `[next-auth] CLIENT_FETCH_ERROR`,+ poll 5xx. β server owns the signal; scoped/denylisted (#15145, #15238).+- **Opaque non-Error captures** β `[object Object]`, `[object ErrorEvent]`,+ "Object captured as exception". β capture a real Error via the helpers+ (#15173, #15175).+- **User-content URL validation** β `Invalid href β¦ passed to next/router`. β+ render user URLs as native `<a>`, not a framework `<Link>` (#15245).+- **Perf detectors / third-party** β N+1, HTTP-overhead `info` issues, browser+ extensions, crawlers. β Sentry project settings (inbound filters, detectors),+ not code.+- **Stale-deploy** β chunk 404s, `importScripts` failures, version-skew. β a+ reload-on-new-version prompt + release-aware handling (open work).++## Workstream levers (case studies)++Each row names the PR that established the pattern; verify a cited symbol/swap+against the current tree before relying on it.++| PR | Family | Lever |+|---|---|---|+| #15145 | 418 httpClient poll 5xx (~44kβ8/24h) | `isNoisyHttpClientPollEvent` (mechanism + path) |+| #15173 | parse-worker `[object ErrorEvent]` | `reportParserWorkerError` (real Error) |+| #15174 | JSON-viewer meta-root offsets (456) | fingerprint/render fix |+| #15175 | opaque non-Error captures (5EX) | `captureUnknownError` (real Error) |+| #15238 | transport / next-auth / benign (~1.9k/24h) | `isDenylistedNoiseEvent` in `sentryFilters.ts` β reads all event fields, negative fixtures |+| #15243 | expected tRPC codes (54F #2, ~30k) | `handleTrpcError` classify + breadcrumb + tags |+| #15245 | `Invalid href` (5DZ/5EA/5ER, ~40k) | native `<a>` at the source |++Each is a worked example of one rule: prefer real Errors, prefer root-cause over+filter, read the right field, keep a negative fixture, verify in the browser.diff --git a/web/AGENTS.md b/web/AGENTS.mdindex 0a5dea6345..a2beacd072 100644--- a/web/AGENTS.md+++ b/web/AGENTS.md@@ -73,6 +73,8 @@ Use root [AGENTS.md](../AGENTS.md) for monorepo-level rules.[`web/.agents/skills/vercel-react-best-practices/SKILL.md`](.agents/skills/vercel-react-best-practices/SKILL.md)- PostHog product analytics β when and how to instrument user actions:[`../.agents/skills/posthog-instrumentation/SKILL.md`](../.agents/skills/posthog-instrumentation/SKILL.md)+- Sentry error capture β whether and how an error path should report:+ [`../.agents/skills/sentry-instrumentation/SKILL.md`](../.agents/skills/sentry-instrumentation/SKILL.md)Read these package-local skills before substantial frontend refactors when thetask involves component composition, reusable component APIs, rendering@@ -83,7 +85,11 @@ from loaded data, read the frontend-large-feature-architecture skill first βmost effects that derive or sync state should not exist. When adding ameaningful user action (button, handler, form, mutation, feature surface),read the PostHog instrumentation skill and decide explicitly whether the-action should emit an analytics event.+action should emit an analytics event. When adding or touching an error path β+a `captureException` or `console.error` call, an error boundary, a `catch`+block, a Worker `onerror`, or a Sentry `beforeSend`/denylist filter β read the+Sentry instrumentation skill first and decide whether it should capture at all+(and, for any suppression change, answer "does this rule hide a real error?").## Web Conventions