Skip to content

Commit a5cb2d1

Browse files
isaacsclaude
andcommitted
chore: Replace AGENTS.md rules with lints and tests
Add the `sdk/valid-span-origin` lint rule. It checks span origins against the trace origin format: string literals written to an origin attribute, and string literals assigned to a constant whose name ends in `ORIGIN`. Add `scripts/agent-rules.test.mjs`. It checks that no new dev-packages test sets `traceLifecycle`, and that every `exports` subpath with a worker entry puts `workerd` before `browser`. Cloudflare bundlers set `workerd`, `worker` and `browser`, and the first matching key wins. The test leaves the place of `worker` to each package: webpack `target: 'webworker'` builds for browser Web Workers also set `worker` and `browser`, so `@sentry/react-router` keeps `worker` last on purpose (#24866). Remove the AGENTS.md text these checks now enforce, text that restates code, and the Coding Standards and Testing lines that showed no effect in an ablation eval. `REVIEW-RULES.md` no longer points the review at the removed Testing section, and now holds the `stringifyForCodeInjection` rule itself, so reviews keep checking it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 25bec5f commit a5cb2d1

8 files changed

Lines changed: 387 additions & 43 deletions

File tree

‎.oxlintrc.base.json‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,8 @@
7777
"files": ["**/src/**/*.ts", "**/src/**/*.tsx"],
7878
"rules": {
7979
"sdk/require-timer-unref": "error",
80-
"sdk/no-unfiltered-url-attributes": "error"
80+
"sdk/no-unfiltered-url-attributes": "error",
81+
"sdk/valid-span-origin": "error"
8182
}
8283
},
8384
{

‎AGENTS.md‎

Lines changed: 4 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -71,50 +71,20 @@ Uses **Git Flow** (see `docs/gitflow.md`).
7171

7272
## Architecture
7373

74-
- Types live in `packages/core/`. The `@sentry/types` package is gone.
75-
- An AI provider integration spans two places, both in
76-
`packages/server-utils/`: the gen-AI instrumentation logic in
77-
`src/ai/{provider}/`, and the integration that wires it up in
78-
`src/integrations/{provider}.ts`, registered in `getTracingIntegrations()`.
79-
Runtime packages (`node`, `cloudflare`, ...) re-export from
80-
`@sentry/server-utils` rather than defining their own.
81-
8274
- `Sentry.init()` follows one rule for repeated calls: the first call wins. See
8375
`docs/repeated-init.md` before you add or change an `init()`.
8476

85-
- In the `exports` of a framework SDK, put the `workerd` and `worker` keys before `browser`. Cloudflare bundlers also
86-
set the `browser` condition, and the first key that matches wins.
87-
88-
- Span origins must follow the [trace origin spec](https://develop.sentry.dev/sdk/telemetry/traces/trace-origin/):
89-
`<type>.<category>.<integration_name>.<integration_part>`, at most four parts, no skipped
90-
parts, only `[a-zA-Z0-9_]` within a part. `category` is the span op category
91-
(`auto.queue.kafkajs.producer`, not `auto.kafkajs.producer`). Don't encode tooling like
92-
`otel` or `orchestrion` in the origin.
77+
- In a span origin, the second part is the span op category (`auto.queue.kafkajs.producer`, not
78+
`auto.kafkajs.producer`). `sdk/valid-span-origin` checks the rest of the format.
9379

9480
## Linting & Formatting
9581

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

10285
## Coding Standards
10386

104-
- Follow existing conventions — check neighboring files
105-
- 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.
106-
- 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.
107-
- Only use libraries already in the codebase
108-
- Never expose secrets or keys
109-
- When modifying files, cover all occurrences (including `src/` and `test/`)
11087
- **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.
111-
- Do not use `expect(someSpy.mock.calls[0]?.[0])` or similar constructs to check what a spy was called with.
112-
Instead use `expect(someSpy).toHaveBeenCalledWith(...)` or derivatives for a more readable and less brittle test assertion.
113-
114-
## Testing
115-
116-
- **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.
117-
- 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'`.
11888

11989
## Lazy Loading Is a Last Resort
12090

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

131101
- [Span Attributes](https://develop.sentry.dev/sdk/telemetry/attributes.md)
132102
- [Scopes (global, isolation, current)](https://develop.sentry.dev/sdk/telemetry/scopes.md)
133-
134-
## Skills
135-
136-
Task-specific instructions live in `.claude/skills/`. Each skill lists its
137-
own trigger, so consult that directory rather than this file.

‎REVIEW-RULES.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,7 @@ Change a rule when the review gets it wrong two times for the same reason. Add a
66

77
## Rules in `AGENTS.md`
88

9-
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.
10-
11-
- For the `stringifyForCodeInjection` rule, log messages and boolean `define` values are fine.
9+
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.
1210

1311
## SDK source in `packages/`
1412

@@ -39,6 +37,8 @@ These sections of the root `AGENTS.md` are checks: "Architecture", "Coding Stand
3937
- 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.
4038
- 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`).
4139

40+
- 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.
41+
4242
**Breaking changes**
4343

4444
- 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.

‎packages/eslint-plugin-sdk/src/index.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,6 @@ module.exports = {
2424
'require-timer-unref': require('./rules/require-timer-unref'),
2525
'no-unsafe-html-writes': require('./rules/no-unsafe-html-writes'),
2626
'require-define-integration': require('./rules/require-define-integration'),
27+
'valid-span-origin': require('./rules/valid-span-origin'),
2728
},
2829
};
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
'use strict';
2+
3+
/**
4+
* Checks literal `sentry.origin` values against the trace origin spec:
5+
* https://develop.sentry.dev/sdk/telemetry/traces/trace-origin/
6+
*
7+
* It checks string literals written to an origin attribute, and string
8+
* literals assigned to a constant whose name ends in `ORIGIN`. Origins
9+
* built with a template literal or imported from elsewhere are not
10+
* checked. Whether the `category` part is the span op category
11+
* (`auto.queue.kafkajs.producer`, not `auto.kafkajs.producer`) needs a
12+
* human.
13+
*/
14+
15+
const ORIGIN_KEYS = new Set(['SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN', 'SENTRY_ORIGIN', 'sentry.origin']);
16+
const ORIGIN_FORMAT = /^(auto|manual)(\.[a-zA-Z0-9_]+){0,3}$/;
17+
const TOOLING_PARTS = new Set(['otel', 'orchestrion']);
18+
const ORIGIN_CONSTANT = /(^|_)ORIGIN$/;
19+
20+
function getKeyName(node, computed) {
21+
if (computed && node.type === 'Identifier') {
22+
return node.name;
23+
}
24+
if (node.type === 'Literal' && typeof node.value === 'string') {
25+
return node.value;
26+
}
27+
return undefined;
28+
}
29+
30+
module.exports = {
31+
meta: {
32+
type: 'problem',
33+
docs: {
34+
description: 'Enforce the trace origin format for literal `sentry.origin` values.',
35+
},
36+
schema: [],
37+
messages: {
38+
badFormat:
39+
"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/",
40+
toolingPart:
41+
"Span origin '{{origin}}' names tooling ('{{part}}'). The origin identifies the integration, not how it is built.",
42+
},
43+
},
44+
create(context) {
45+
function check(valueNode) {
46+
if (!valueNode || valueNode.type !== 'Literal' || typeof valueNode.value !== 'string') {
47+
return;
48+
}
49+
const origin = valueNode.value;
50+
if (!ORIGIN_FORMAT.test(origin)) {
51+
context.report({ node: valueNode, messageId: 'badFormat', data: { origin } });
52+
return;
53+
}
54+
const part = origin.split('.').find(p => TOOLING_PARTS.has(p));
55+
if (part) {
56+
context.report({ node: valueNode, messageId: 'toolingPart', data: { origin, part } });
57+
}
58+
}
59+
60+
return {
61+
// const ORIGIN = 'auto.cache.cloudflare.kv';
62+
VariableDeclarator(node) {
63+
if (node.id.type === 'Identifier' && ORIGIN_CONSTANT.test(node.id.name) && !ORIGIN_KEYS.has(node.id.name)) {
64+
check(node.init);
65+
}
66+
},
67+
Property(node) {
68+
if (ORIGIN_KEYS.has(getKeyName(node.key, node.computed))) {
69+
check(node.value);
70+
}
71+
},
72+
// span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, '...')
73+
CallExpression(node) {
74+
const callee = node.callee;
75+
if (
76+
callee.type === 'MemberExpression' &&
77+
callee.property.type === 'Identifier' &&
78+
callee.property.name === 'setAttribute' &&
79+
node.arguments.length >= 2 &&
80+
ORIGIN_KEYS.has(getKeyName(node.arguments[0], true))
81+
) {
82+
check(node.arguments[1]);
83+
}
84+
},
85+
};
86+
},
87+
};
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import { RuleTester } from 'eslint';
2+
import { describe, test } from 'vitest';
3+
// @ts-expect-error untyped module
4+
import rule from '../../../src/rules/valid-span-origin';
5+
6+
describe('valid-span-origin', () => {
7+
test('ruleTester', () => {
8+
const ruleTester = new RuleTester({
9+
parserOptions: {
10+
ecmaVersion: 2020,
11+
},
12+
});
13+
14+
ruleTester.run('valid-span-origin', rule, {
15+
valid: [
16+
{ code: "({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.queue.kafkajs.producer' });" },
17+
{ code: "({ [SENTRY_ORIGIN]: 'auto.http.node' });" },
18+
{ code: "({ 'sentry.origin': 'manual' });" },
19+
{ code: "span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, 'auto.db.pg');" },
20+
{ code: '({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin });' },
21+
{ code: "({ origin: 'not.checked' });" },
22+
{ code: "span.setAttribute('other', 'a-b');" },
23+
{ code: "const ORIGIN = 'auto.cache.cloudflare.kv';" },
24+
{ code: "const OPENAI_ORIGIN = 'auto.ai.openai';" },
25+
{ code: "const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';" },
26+
{ code: "const ORIGINAL_ENTRY_QUERY = '?sentry-cloudflare-original';" },
27+
{ code: 'const ORIGIN = `auto.${op}.angular`;' },
28+
],
29+
invalid: [
30+
{
31+
code: "({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.node.server.extra' });",
32+
errors: [{ messageId: 'badFormat' }],
33+
},
34+
{
35+
code: "({ [SENTRY_ORIGIN]: 'auto.http.my-lib' });",
36+
errors: [{ messageId: 'badFormat' }],
37+
},
38+
{
39+
code: "({ 'sentry.origin': 'node.http' });",
40+
errors: [{ messageId: 'badFormat' }],
41+
},
42+
{
43+
code: "span.setAttribute('sentry.origin', 'auto.http..node');",
44+
errors: [{ messageId: 'badFormat' }],
45+
},
46+
{
47+
code: "const ORIGIN = 'auto.cache.my-lib';",
48+
errors: [{ messageId: 'badFormat' }],
49+
},
50+
{
51+
code: "const MONGO_ORIGIN = 'auto.db.otel.mongo';",
52+
errors: [{ messageId: 'toolingPart', data: { origin: 'auto.db.otel.mongo', part: 'otel' } }],
53+
},
54+
{
55+
code: "({ [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.otel.mongo' });",
56+
errors: [{ messageId: 'toolingPart', data: { origin: 'auto.db.otel.mongo', part: 'otel' } }],
57+
},
58+
],
59+
});
60+
});
61+
});

‎scripts/agent-rules.test.mjs‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { execFileSync } from 'node:child_process';
2+
import { readdirSync, readFileSync, existsSync } from 'node:fs';
3+
import { join } from 'node:path';
4+
import { describe, expect, it } from 'vitest';
5+
6+
const ROOT = join(import.meta.dirname, '..');
7+
8+
// Cloudflare bundlers set `workerd`, `worker` and `browser`, and the first
9+
// matching key wins. A subpath with a worker entry needs `workerd` before
10+
// `browser`, or Cloudflare gets the browser entry. Where `worker` goes is a
11+
// per-package choice: webpack `target: 'webworker'` builds for browser Web
12+
// Workers set `worker` and `browser` too.
13+
function findMissingWorkerd(name, exportsField) {
14+
const found = [];
15+
for (const [subpath, conditions] of Object.entries(exportsField)) {
16+
if (!conditions || typeof conditions !== 'object') continue;
17+
const keys = Object.keys(conditions);
18+
const browser = keys.indexOf('browser');
19+
if (browser === -1 || !keys.some(key => key === 'worker' || key === 'workerd')) continue;
20+
const workerd = keys.indexOf('workerd');
21+
if (workerd === -1 || workerd > browser) {
22+
found.push(`${name} ${subpath}`);
23+
}
24+
}
25+
return found;
26+
}
27+
28+
describe('package exports', () => {
29+
it('put `workerd` before `browser` in subpaths with a worker entry', () => {
30+
const found = [];
31+
for (const dir of readdirSync(join(ROOT, 'packages'))) {
32+
const file = join(ROOT, 'packages', dir, 'package.json');
33+
if (!existsSync(file)) continue;
34+
const pkg = JSON.parse(readFileSync(file, 'utf8'));
35+
if (pkg.exports && typeof pkg.exports === 'object') {
36+
found.push(...findMissingWorkerd(pkg.name, pkg.exports));
37+
}
38+
}
39+
expect(found).toEqual([]);
40+
});
41+
});
42+
43+
describe('dev-packages tests', () => {
44+
// New tests must exercise the default, span streaming. Do not add files
45+
// to the baseline; remove them when they stop setting `traceLifecycle`.
46+
it('do not set `traceLifecycle` outside the baseline', () => {
47+
const baseline = new Set(JSON.parse(readFileSync(join(ROOT, 'scripts/trace-lifecycle-baseline.json'), 'utf8')));
48+
const files = execFileSync('git', ['grep', '--untracked', '-l', 'traceLifecycle', '--', 'dev-packages'], {
49+
cwd: ROOT,
50+
encoding: 'utf8',
51+
})
52+
.trim()
53+
.split('\n');
54+
expect(files.filter(file => !baseline.has(file))).toEqual([]);
55+
});
56+
});

0 commit comments

Comments
 (0)