Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .oxlintrc.base.json
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,8 @@
"files": ["**/src/**/*.ts", "**/src/**/*.tsx"],
"rules": {
"sdk/require-timer-unref": "error",
"sdk/no-unfiltered-url-attributes": "error"
"sdk/no-unfiltered-url-attributes": "error",
"sdk/valid-span-origin": "error"
}
},
{
Expand Down
43 changes: 4 additions & 39 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,50 +71,20 @@ Uses **Git Flow** (see `docs/gitflow.md`).

## Architecture

- Types live in `packages/core/`. The `@sentry/types` package is gone.
- An AI provider integration spans two places, both in
`packages/server-utils/`: the gen-AI instrumentation logic in
`src/ai/{provider}/`, and the integration that wires it up in
`src/integrations/{provider}.ts`, registered in `getTracingIntegrations()`.
Runtime packages (`node`, `cloudflare`, ...) re-export from
`@sentry/server-utils` rather than defining their own.

- `Sentry.init()` follows one rule for repeated calls: the first call wins. See
`docs/repeated-init.md` before you add or change an `init()`.

- In the `exports` of a framework SDK, put the `workerd` and `worker` keys before `browser`. Cloudflare bundlers also
set the `browser` condition, and the first key that matches wins.

- Span origins must follow the [trace origin spec](https://develop.sentry.dev/sdk/telemetry/traces/trace-origin/):
`<type>.<category>.<integration_name>.<integration_part>`, at most four parts, no skipped
parts, only `[a-zA-Z0-9_]` within a part. `category` is the span op category
(`auto.queue.kafkajs.producer`, not `auto.kafkajs.producer`). Don't encode tooling like
`otel` or `orchestrion` in the origin.
- In a span origin, the second part is the span op category (`auto.queue.kafkajs.producer`, not
`auto.kafkajs.producer`). `sdk/valid-span-origin` checks the rest of the format.

## Linting & Formatting

- This project uses **Oxlint** and **Oxfmt** — NOT ESLint or Prettier
- Never run `eslint`, `npx eslint`, or any ESLint CLI — use `pnpm run lint` (Oxlint) instead
- Never run `prettier` — use `pnpm run format` (Oxfmt) instead
- ESLint packages in the repo are legacy/e2e test app dependencies — ignore them
- Do not create, modify, or suggest `.eslintrc`, `eslint.config.*`, or `.prettierrc` files
Use `pnpm run lint` (Oxlint) and `pnpm run format` (Oxfmt). Never run ESLint or Prettier, and never add their config
files. ESLint packages in the repo belong to legacy and E2E test apps.

## Coding Standards

- Follow existing conventions — check neighboring files
- Reach for existing utils before writing a new one. Most shared helpers live in `@sentry/core` (`packages/core/src/utils/`), with browser helpers in `packages/browser-utils/`. Search first (LSP `workspaceSymbol` or grep) for common needs (type guards in `is.ts`, object/array helpers, `normalize`, `dsn`, `merge`, string/url helpers). Reuse or extend the existing util rather than adding a near-duplicate; only introduce a new util when nothing fits.
- When `JSON.stringify` output goes into generated code (bundler plugins, loaders, virtual modules, `define`), use `stringifyForCodeInjection` from `@sentry/core` instead. It escapes `<`, `>`, U+2028 and U+2029, so the code stays safe when inlined in a `<script>` element.
- Only use libraries already in the codebase
- Never expose secrets or keys
- When modifying files, cover all occurrences (including `src/` and `test/`)
- **Write few comments; default to none.** Comments explain **why**, never **what** — never add a comment that restates what the code does or narrates the change being made. Only add one when the reasoning isn't clear from the code itself, or to flag a tradeoff or something that would otherwise look surprising to a reader. When in doubt, leave it out.
- Do not use `expect(someSpy.mock.calls[0]?.[0])` or similar constructs to check what a spy was called with.
Instead use `expect(someSpy).toHaveBeenCalledWith(...)` or derivatives for a more readable and less brittle test assertion.

## Testing

- **Do not set `traceLifecycle` in new tests** (node-integration-tests, e2e). Leave it unset so the test exercises the default — span streaming (`stream`). Many existing suites pin `traceLifecycle: 'static'` (or toggle it via `process.env.STREAMED`); do not copy that into new tests.
- Under span streaming there is no `transaction` envelope with nested `spans`. Assert the transaction via the streamed span container: `.expect({ span: (container) => { ... } })`, finding the root with `container.items.find(i => i.is_segment)` and child spans with `container.items.filter(...)`. Add `.unordered()` so the span container and error events can arrive in any order and unrelated envelopes (client reports, etc.) are ignored. Errors are still separate `event` envelopes (`.expect({ event })`). A streamed span's error status is `'error'`, not the classic transaction's `'internal_error'`.

## Lazy Loading Is a Last Resort

Expand All @@ -130,8 +100,3 @@ Before even proposing lazy loading:

- [Span Attributes](https://develop.sentry.dev/sdk/telemetry/attributes.md)
- [Scopes (global, isolation, current)](https://develop.sentry.dev/sdk/telemetry/scopes.md)

## Skills

Task-specific instructions live in `.claude/skills/`. Each skill lists its
own trigger, so consult that directory rather than this file.
6 changes: 3 additions & 3 deletions REVIEW-RULES.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@ Change a rule when the review gets it wrong two times for the same reason. Add a

## Rules in `AGENTS.md`

These sections of the root `AGENTS.md` are checks: "Architecture", "Coding Standards", "Testing", and "Lazy Loading Is a Last Resort". The other sections are for authors only.

- For the `stringifyForCodeInjection` rule, log messages and boolean `define` values are fine.
These sections of the root `AGENTS.md` are checks: "Architecture", "Coding Standards", and "Lazy Loading Is a Last Resort". The other sections are for authors only.

## SDK source in `packages/`

Expand Down Expand Up @@ -39,6 +37,8 @@ These sections of the root `AGENTS.md` are checks: "Architecture", "Coding Stand
- Flag a new package, or a new `exports` entry under `packages/`, that can load on a server runtime when its package has no entry in `CASES` or `BUILD_TIME_CASES` in `dev-packages/bundler-tests/tests/runtime-entries.test.ts`. Browser-only packages are fine.
- Flag a new option on an incoming HTTP request integration (Node `httpIntegration`, Deno `denoHttpIntegration` and `denoServeIntegration`, Bun `bunHttpServerIntegration` and `bunServerIntegration`, Cloudflare `httpServerIntegration`) that applies to more than one runtime and is not in `ServerRequestOptions` (`packages/core/src/integrations/http/server-request-options.ts`).

- Flag `JSON.stringify` output that goes into generated code (bundler plugins, loaders, virtual modules, `define` values). Use `stringifyForCodeInjection` from `@sentry/core`: it escapes `<`, `>`, U+2028 and U+2029, so the code stays safe inside a `<script>` element. Log messages and boolean `define` values are fine.

**Breaking changes**

- A removed public export or a changed default needs an entry in `MIGRATION.md`. A deprecated export needs `@deprecated` in its JSDoc. `CHANGELOG.md` is written at release time, so do not ask for an entry.
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin-sdk/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,6 @@ module.exports = {
'require-timer-unref': require('./rules/require-timer-unref'),
'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'),
'require-define-integration': require('./rules/require-define-integration'),
'valid-span-origin': require('./rules/valid-span-origin'),
},
};
87 changes: 87 additions & 0 deletions packages/eslint-plugin-sdk/src/rules/valid-span-origin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
'use strict';

/**
* Checks literal `sentry.origin` values against the trace origin spec:
* https://develop.sentry.dev/sdk/telemetry/traces/trace-origin/
*
* It checks string literals written to an origin attribute, and string
* literals assigned to a constant whose name ends in `ORIGIN`. Origins
* built with a template literal or imported from elsewhere are not
* checked. Whether the `category` part is the span op category
* (`auto.queue.kafkajs.producer`, not `auto.kafkajs.producer`) needs a
* human.
*/

const ORIGIN_KEYS = new Set(['SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN', 'SENTRY_ORIGIN', 'sentry.origin']);
const ORIGIN_FORMAT = /^(auto|manual)(\.[a-zA-Z0-9_]+){0,3}$/;
const TOOLING_PARTS = new Set(['otel', 'orchestrion']);
const ORIGIN_CONSTANT = /(^|_)ORIGIN$/;

function getKeyName(node, computed) {
if (computed && node.type === 'Identifier') {
return node.name;
}
if (node.type === 'Literal' && typeof node.value === 'string') {
return node.value;
}
return undefined;
}

module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Enforce the trace origin format for literal `sentry.origin` values.',
},
schema: [],
messages: {
badFormat:
"Span origin '{{origin}}' must be '<type>.<category>.<integration_name>.<integration_part>': type 'auto' or 'manual', at most four parts, only [a-zA-Z0-9_] in a part. See https://develop.sentry.dev/sdk/telemetry/traces/trace-origin/",
toolingPart:
"Span origin '{{origin}}' names tooling ('{{part}}'). The origin identifies the integration, not how it is built.",
},
},
create(context) {
function check(valueNode) {
if (!valueNode || valueNode.type !== 'Literal' || typeof valueNode.value !== 'string') {
Comment thread
isaacs marked this conversation as resolved.
Resolved
return;
}
const origin = valueNode.value;
if (!ORIGIN_FORMAT.test(origin)) {
context.report({ node: valueNode, messageId: 'badFormat', data: { origin } });
return;
}
const part = origin.split('.').find(p => TOOLING_PARTS.has(p));
if (part) {
context.report({ node: valueNode, messageId: 'toolingPart', data: { origin, part } });
}
}

Check notice on line 58 in packages/eslint-plugin-sdk/src/rules/valid-span-origin.js

View check run for this annotation

@sentry/warden / warden: code-review

TS assertions let malformed ORIGIN constants bypass format checking

A malformed origin such as `const BAD_ORIGIN = 'auto.ai.bad-name' as const` is skipped by the new lint rule, allowing an invalid span origin to ship without the promised validation.

return {
// const ORIGIN = 'auto.cache.cloudflare.kv';
VariableDeclarator(node) {
if (node.id.type === 'Identifier' && ORIGIN_CONSTANT.test(node.id.name) && !ORIGIN_KEYS.has(node.id.name)) {
check(node.init);
}
},
Property(node) {
if (ORIGIN_KEYS.has(getKeyName(node.key, node.computed))) {
check(node.value);
}
},
// span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, '...')
CallExpression(node) {
const callee = node.callee;
if (
callee.type === 'MemberExpression' &&
callee.property.type === 'Identifier' &&
callee.property.name === 'setAttribute' &&
node.arguments.length >= 2 &&
ORIGIN_KEYS.has(getKeyName(node.arguments[0], true))
) {
check(node.arguments[1]);
}
},
};
},
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { RuleTester } from 'eslint';
import { describe, test } from 'vitest';
// @ts-expect-error untyped module
import rule from '../../../src/rules/valid-span-origin';

describe('valid-span-origin', () => {
test('ruleTester', () => {
const ruleTester = new RuleTester({
parserOptions: {
ecmaVersion: 2020,
},
});

ruleTester.run('valid-span-origin', rule, {
valid: [
{ code: "({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.queue.kafkajs.producer' });" },
{ code: "({ [SENTRY_ORIGIN]: 'auto.http.node' });" },
{ code: "({ 'sentry.origin': 'manual' });" },
{ code: "span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.pg');" },
{ code: '({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin });' },
{ code: "({ origin: 'not.checked' });" },
{ code: "span.setAttribute('other', 'a-b');" },
{ code: "const ORIGIN = 'auto.cache.cloudflare.kv';" },
{ code: "const OPENAI_ORIGIN = 'auto.ai.openai';" },
{ code: "const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';" },
{ code: "const ORIGINAL_ENTRY_QUERY = '?sentry-cloudflare-original';" },
{ code: 'const ORIGIN = `auto.${op}.angular`;' },
],
invalid: [
{
code: "({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.node.server.extra' });",
errors: [{ messageId: 'badFormat' }],
},
{
code: "({ [SENTRY_ORIGIN]: 'auto.http.my-lib' });",
errors: [{ messageId: 'badFormat' }],
},
{
code: "({ 'sentry.origin': 'node.http' });",
errors: [{ messageId: 'badFormat' }],
},
{
code: "span.setAttribute('sentry.origin', 'auto.http..node');",
errors: [{ messageId: 'badFormat' }],
},
{
code: "const ORIGIN = 'auto.cache.my-lib';",
errors: [{ messageId: 'badFormat' }],
},
{
code: "const MONGO_ORIGIN = 'auto.db.otel.mongo';",
errors: [{ messageId: 'toolingPart', data: { origin: 'auto.db.otel.mongo', part: 'otel' } }],
},
{
code: "({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.otel.mongo' });",
errors: [{ messageId: 'toolingPart', data: { origin: 'auto.db.otel.mongo', part: 'otel' } }],
},
],
});
});
});
56 changes: 56 additions & 0 deletions scripts/agent-rules.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { execFileSync } from 'node:child_process';
import { readdirSync, readFileSync, existsSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';

const ROOT = join(import.meta.dirname, '..');

// Cloudflare bundlers set `workerd`, `worker` and `browser`, and the first
// matching key wins. A subpath with a worker entry needs `workerd` before
// `browser`, or Cloudflare gets the browser entry. Where `worker` goes is a
// per-package choice: webpack `target: 'webworker'` builds for browser Web
// Workers set `worker` and `browser` too.
function findMissingWorkerd(name, exportsField) {
const found = [];
for (const [subpath, conditions] of Object.entries(exportsField)) {
if (!conditions || typeof conditions !== 'object') continue;
const keys = Object.keys(conditions);
const browser = keys.indexOf('browser');
if (browser === -1 || !keys.some(key => key === 'worker' || key === 'workerd')) continue;
const workerd = keys.indexOf('workerd');
if (workerd === -1 || workerd > browser) {
found.push(`${name} ${subpath}`);
}
}
return found;
}

describe('package exports', () => {
it('put `workerd` before `browser` in subpaths with a worker entry', () => {
const found = [];
for (const dir of readdirSync(join(ROOT, 'packages'))) {
const file = join(ROOT, 'packages', dir, 'package.json');
if (!existsSync(file)) continue;
const pkg = JSON.parse(readFileSync(file, 'utf8'));
if (pkg.exports && typeof pkg.exports === 'object') {
found.push(...findMissingWorkerd(pkg.name, pkg.exports));
}
}
expect(found).toEqual([]);
});
});

describe('dev-packages tests', () => {
// New tests must exercise the default, span streaming. Do not add files
// to the baseline; remove them when they stop setting `traceLifecycle`.
it('do not set `traceLifecycle` outside the baseline', () => {
const baseline = new Set(JSON.parse(readFileSync(join(ROOT, 'scripts/trace-lifecycle-baseline.json'), 'utf8')));
const files = execFileSync('git', ['grep', '--untracked', '-l', 'traceLifecycle', '--', 'dev-packages'], {
cwd: ROOT,
encoding: 'utf8',
})
.trim()
.split('\n');
expect(files.filter(file => !baseline.has(file))).toEqual([]);
});
});
Loading
Loading