Skip to content

Commit ec37cf8

Browse files
royangerclaude
andcommitted
feat(*): write Clerk agent rules to AGENTS.md in development
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b0728e8 commit ec37cf8

10 files changed

Lines changed: 306 additions & 0 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@clerk/astro': minor
3+
'@clerk/expo': minor
4+
'@clerk/nextjs': minor
5+
'@clerk/nuxt': minor
6+
'@clerk/tanstack-react-start': minor
7+
---
8+
9+
When your app runs in development under an AI coding agent (such as Claude Code, Cursor, or GitHub Copilot), Clerk now adds a Clerk section to the project's root `AGENTS.md`, creating the file if needed, plus a `CLAUDE.md` that imports it when none exists. The section tells the agent to read `node_modules/@clerk/<sdk>/AGENTS.md` before writing auth code and points it to the Clerk MCP server. Nothing is written in production or CI. The section is written by the Astro and Nuxt dev servers, the Expo config plugin, the first `auth()` call in Next.js, and TanStack React Start's `clerkMiddleware()`.

‎packages/astro/src/integration/create-integration.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1+
import * as fs from 'node:fs';
2+
import * as path from 'node:path';
3+
import { fileURLToPath } from 'node:url';
4+
5+
import { writeClerkAgentRules } from '@clerk/shared/agentRules';
16
import type { ClerkOptions } from '@clerk/shared/types';
7+
import { isAgentEnvironment, isAutomatedEnvironment } from '@clerk/shared/utils';
28
import type { AstroIntegration } from 'astro';
39
import { envField } from 'astro/config';
410

@@ -11,6 +17,8 @@ const buildEnvVarFromOption = (valueToBeStored: unknown, envName: keyof Internal
1117
return valueToBeStored ? { [`import.meta.env.${envName}`]: JSON.stringify(valueToBeStored) } : {};
1218
};
1319

20+
let didWriteAgentRules = false;
21+
1422
type HotloadAstroClerkIntegrationParams = AstroClerkIntegrationParams & {
1523
enableEnvSchema?: boolean;
1624
};
@@ -31,6 +39,15 @@ function createIntegration<Params extends HotloadAstroClerkIntegrationParams>()
3139
name: '@clerk/astro/integration',
3240
hooks: {
3341
'astro:config:setup': ({ config, injectScript, updateConfig, logger, command }) => {
42+
if (command === 'dev' && !didWriteAgentRules && !isAutomatedEnvironment() && isAgentEnvironment()) {
43+
didWriteAgentRules = true;
44+
try {
45+
writeClerkAgentRules({ cwd: fileURLToPath(config.root), fs, path, sdks: ['astro'] });
46+
} catch {
47+
// Writing agent hints must never break a dev server.
48+
}
49+
}
50+
3451
if (['server', 'hybrid'].includes(config.output) && !config.adapter) {
3552
logger.error('Missing adapter, please update your Astro config to use one.');
3653
}

‎packages/expo/app.plugin.js‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,66 @@
88
*/
99
const { AndroidConfig, withAndroidManifest, withEntitlementsPlist, withInfoPlist } = require('@expo/config-plugins');
1010

11+
const fs = require('fs');
12+
const path = require('path');
13+
1114
const CLERK_EXPO_NATIVE = '@clerk/expo-native-components';
1215
const CLERK_EXPO_NATIVE_OPTIONS = ['keychainService', 'theme'];
16+
let didWriteAgentRules = false;
17+
18+
const isTruthyEnvValue = value => typeof value === 'string' && !!value && !['0', 'false', 'off', 'no'].includes(value);
19+
20+
const isAgentEnvironment = () =>
21+
[
22+
'CLAUDECODE',
23+
'CURSOR_AGENT',
24+
'CURSOR_CLI',
25+
'CURSOR_EXTENSION_HOST_ROLE',
26+
'CURSOR_TRACE_ID',
27+
'GITHUB_COPILOT_AGENT',
28+
'GITHUB_COPILOT_CHAT',
29+
'AGENT',
30+
'AGENTS',
31+
].some(name => isTruthyEnvValue(process.env[name]));
32+
33+
const isAutomatedEnvironment = () =>
34+
[
35+
'CI',
36+
'CONTINUOUS_INTEGRATION',
37+
'GITHUB_ACTIONS',
38+
'GITLAB_CI',
39+
'CIRCLECI',
40+
'TRAVIS',
41+
'BUILDKITE',
42+
'BITBUCKET_BUILD_NUMBER',
43+
'APPVEYOR',
44+
'CODEBUILD_BUILD_ID',
45+
'TF_BUILD',
46+
'TEAMCITY_VERSION',
47+
'JENKINS_URL',
48+
'HUDSON_URL',
49+
'BAMBOO_BUILDKEY',
50+
'CF_PAGES',
51+
].some(name => isTruthyEnvValue(process.env[name]));
52+
53+
const maybeWriteAgentRules = config => {
54+
if (didWriteAgentRules || isAutomatedEnvironment() || !isAgentEnvironment()) {
55+
return;
56+
}
57+
58+
const projectRoot = config?._internal?.projectRoot || process.cwd();
59+
if (!fs.existsSync(path.join(projectRoot, 'package.json'))) {
60+
return;
61+
}
62+
63+
didWriteAgentRules = true;
64+
65+
try {
66+
require('@clerk/shared/agentRules').writeClerkAgentRules({ cwd: projectRoot, fs, path, sdks: ['expo'] });
67+
} catch {
68+
// Writing agent hints must never break Expo config evaluation.
69+
}
70+
};
1371

1472
const addHostedAuthIntentFilter = (mainActivity, packageName) => {
1573
const callbackHost = `${packageName}.hosted-callback`;
@@ -138,6 +196,8 @@ const withClerkExpoNativeComponents = (config, props = {}, resolvePlugin = resol
138196
};
139197

140198
const withClerkExpo = (config, props = {}) => {
199+
maybeWriteAgentRules(config);
200+
141201
const { appleSignIn = true } = props;
142202
if (appleSignIn !== false) {
143203
config = withClerkAppleSignIn(config);

‎packages/nextjs/src/app-router/server/auth.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ export const auth: AuthFn = (async (options?: AuthOptions) => {
8383
require('server-only');
8484

8585
try {
86+
await import('../../server/agent-rules-node.js').then(m => m.writeAgentRulesOnce()).catch(() => undefined);
87+
8688
const request = await buildRequestLike();
8789

8890
const stepsBasedOnSrcDirectory = async () => {
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import { writeClerkAgentRules } from '@clerk/shared/agentRules';
2+
import { isAgentEnvironment, isAutomatedEnvironment } from '@clerk/shared/utils';
3+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4+
5+
vi.mock('@clerk/shared/agentRules', () => ({ writeClerkAgentRules: vi.fn() }));
6+
vi.mock('@clerk/shared/utils', async importOriginal => ({
7+
...(await importOriginal<typeof import('@clerk/shared/utils')>()),
8+
isAgentEnvironment: vi.fn(),
9+
isAutomatedEnvironment: vi.fn(),
10+
}));
11+
vi.mock('../fs/utils', () => ({
12+
nodeCwdOrThrow: () => () => '/app',
13+
nodeFsOrThrow: () => ({}),
14+
nodePathOrThrow: () => ({}),
15+
}));
16+
17+
const loadWriteAgentRulesOnce = async () => (await import('../agent-rules-node.js')).writeAgentRulesOnce;
18+
19+
describe('writeAgentRulesOnce', () => {
20+
beforeEach(() => {
21+
vi.resetModules();
22+
vi.mocked(writeClerkAgentRules).mockReset();
23+
vi.mocked(isAgentEnvironment).mockReturnValue(true);
24+
vi.mocked(isAutomatedEnvironment).mockReturnValue(false);
25+
vi.stubEnv('NODE_ENV', 'development');
26+
});
27+
28+
afterEach(() => {
29+
vi.unstubAllEnvs();
30+
});
31+
32+
it('writes the Next.js rules once per process', async () => {
33+
const writeAgentRulesOnce = await loadWriteAgentRulesOnce();
34+
35+
writeAgentRulesOnce();
36+
writeAgentRulesOnce();
37+
38+
expect(writeClerkAgentRules).toHaveBeenCalledTimes(1);
39+
expect(writeClerkAgentRules).toHaveBeenCalledWith(expect.objectContaining({ cwd: '/app', sdks: ['nextjs'] }));
40+
});
41+
42+
it('skips outside an agent environment', async () => {
43+
vi.mocked(isAgentEnvironment).mockReturnValue(false);
44+
45+
(await loadWriteAgentRulesOnce())();
46+
47+
expect(writeClerkAgentRules).not.toHaveBeenCalled();
48+
});
49+
50+
it('skips in CI', async () => {
51+
vi.mocked(isAutomatedEnvironment).mockReturnValue(true);
52+
53+
(await loadWriteAgentRulesOnce())();
54+
55+
expect(writeClerkAgentRules).not.toHaveBeenCalled();
56+
});
57+
58+
it('skips in production', async () => {
59+
vi.stubEnv('NODE_ENV', 'production');
60+
61+
(await loadWriteAgentRulesOnce())();
62+
63+
expect(writeClerkAgentRules).not.toHaveBeenCalled();
64+
});
65+
66+
it('does not throw when writing fails', async () => {
67+
vi.mocked(writeClerkAgentRules).mockImplementation(() => {
68+
throw new Error('EACCES');
69+
});
70+
71+
expect(await loadWriteAgentRulesOnce()).not.toThrow();
72+
});
73+
});
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { writeClerkAgentRules } from '@clerk/shared/agentRules';
2+
import { isAgentEnvironment, isAutomatedEnvironment, isProductionEnvironment } from '@clerk/shared/utils';
3+
4+
import { nodeCwdOrThrow, nodeFsOrThrow, nodePathOrThrow } from './fs/utils';
5+
6+
let didWrite = false;
7+
8+
export function writeAgentRulesOnce() {
9+
if (didWrite || isProductionEnvironment() || isAutomatedEnvironment() || !isAgentEnvironment()) {
10+
return;
11+
}
12+
13+
didWrite = true;
14+
15+
try {
16+
writeClerkAgentRules({
17+
cwd: nodeCwdOrThrow()(),
18+
fs: nodeFsOrThrow(),
19+
path: nodePathOrThrow(),
20+
sdks: ['nextjs'],
21+
});
22+
} catch {
23+
// Writing agent hints must never break a dev server.
24+
}
25+
}

‎packages/nuxt/src/module.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
1+
import * as fs from 'node:fs';
2+
import * as path from 'node:path';
3+
4+
import { writeClerkAgentRules } from '@clerk/shared/agentRules';
15
import type { InternalClerkScriptProps, Without } from '@clerk/shared/types';
6+
import { isAgentEnvironment, isAutomatedEnvironment } from '@clerk/shared/utils';
27
import type { PluginOptions } from '@clerk/vue';
38
import {
49
addComponent,
@@ -35,6 +40,8 @@ export type ModuleOptions = Without<PluginOptions, 'routerPush' | 'routerReplace
3540
skipServerMiddleware?: boolean;
3641
};
3742

43+
let didWriteAgentRules = false;
44+
3845
export default defineNuxtModule<ModuleOptions>({
3946
meta: {
4047
name: PACKAGE_NAME,
@@ -45,6 +52,15 @@ export default defineNuxtModule<ModuleOptions>({
4552
},
4653
},
4754
setup(options, nuxt) {
55+
if (nuxt.options.dev && !didWriteAgentRules && !isAutomatedEnvironment() && isAgentEnvironment()) {
56+
didWriteAgentRules = true;
57+
try {
58+
writeClerkAgentRules({ cwd: nuxt.options.rootDir, fs, path, sdks: ['nuxt'] });
59+
} catch {
60+
// Writing agent hints must never break a dev server.
61+
}
62+
}
63+
4864
// These values must be set (even as undefined) to allow runtime config to work properly.
4965
// In Nuxt, having these keys defined (even as undefined) allows them to be overridden
5066
// by environment variables following the pattern NUXT_PUBLIC_CLERK_* (e.g. NUXT_PUBLIC_CLERK_PUBLISHABLE_KEY).
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
import { writeClerkAgentRules } from '@clerk/shared/agentRules';
2+
import { isAgentEnvironment, isAutomatedEnvironment } from '@clerk/shared/utils';
3+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
4+
5+
vi.mock('@clerk/shared/agentRules', () => ({ writeClerkAgentRules: vi.fn() }));
6+
vi.mock('@clerk/shared/utils', async importOriginal => ({
7+
...(await importOriginal<typeof import('@clerk/shared/utils')>()),
8+
isAgentEnvironment: vi.fn(),
9+
isAutomatedEnvironment: vi.fn(),
10+
}));
11+
12+
const loadWriteAgentRulesOnce = async () => (await import('../agentRules')).writeAgentRulesOnce;
13+
14+
describe('writeAgentRulesOnce', () => {
15+
beforeEach(() => {
16+
vi.resetModules();
17+
vi.mocked(writeClerkAgentRules).mockReset();
18+
vi.mocked(isAgentEnvironment).mockReturnValue(true);
19+
vi.mocked(isAutomatedEnvironment).mockReturnValue(false);
20+
vi.stubEnv('NODE_ENV', 'development');
21+
});
22+
23+
afterEach(() => {
24+
vi.unstubAllEnvs();
25+
});
26+
27+
it('writes the TanStack React Start rules once per process', async () => {
28+
const writeAgentRulesOnce = await loadWriteAgentRulesOnce();
29+
30+
writeAgentRulesOnce();
31+
writeAgentRulesOnce();
32+
33+
expect(writeClerkAgentRules).toHaveBeenCalledTimes(1);
34+
expect(writeClerkAgentRules).toHaveBeenCalledWith(
35+
expect.objectContaining({ cwd: expect.any(String), sdks: ['tanstack-react-start'] }),
36+
);
37+
});
38+
39+
it('skips outside an agent environment', async () => {
40+
vi.mocked(isAgentEnvironment).mockReturnValue(false);
41+
42+
(await loadWriteAgentRulesOnce())();
43+
44+
expect(writeClerkAgentRules).not.toHaveBeenCalled();
45+
});
46+
47+
it('skips in CI', async () => {
48+
vi.mocked(isAutomatedEnvironment).mockReturnValue(true);
49+
50+
(await loadWriteAgentRulesOnce())();
51+
52+
expect(writeClerkAgentRules).not.toHaveBeenCalled();
53+
});
54+
55+
it('skips in production', async () => {
56+
vi.stubEnv('NODE_ENV', 'production');
57+
58+
(await loadWriteAgentRulesOnce())();
59+
60+
expect(writeClerkAgentRules).not.toHaveBeenCalled();
61+
});
62+
63+
it('does not throw when writing fails', async () => {
64+
vi.mocked(writeClerkAgentRules).mockImplementation(() => {
65+
throw new Error('EACCES');
66+
});
67+
68+
expect(await loadWriteAgentRulesOnce()).not.toThrow();
69+
});
70+
});
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import type { FileSystemAdapter, PathAdapter } from '@clerk/shared/agentRules';
2+
import { writeClerkAgentRules } from '@clerk/shared/agentRules';
3+
import { isAgentEnvironment, isAutomatedEnvironment, isProductionEnvironment } from '@clerk/shared/utils';
4+
5+
type NodeProcess = {
6+
cwd: () => string;
7+
getBuiltinModule?: (id: string) => unknown;
8+
};
9+
10+
let didWrite = false;
11+
12+
export function writeAgentRulesOnce() {
13+
if (didWrite || isProductionEnvironment() || isAutomatedEnvironment() || !isAgentEnvironment()) {
14+
return;
15+
}
16+
17+
didWrite = true;
18+
19+
const nodeProcess = (globalThis as { process?: NodeProcess }).process;
20+
const fs = nodeProcess?.getBuiltinModule?.('node:fs') as FileSystemAdapter | undefined;
21+
const path = nodeProcess?.getBuiltinModule?.('node:path') as PathAdapter | undefined;
22+
if (!nodeProcess || !fs || !path) {
23+
return;
24+
}
25+
26+
try {
27+
writeClerkAgentRules({ cwd: nodeProcess.cwd(), fs, path, sdks: ['tanstack-react-start'] });
28+
} catch {
29+
return;
30+
}
31+
}

‎packages/tanstack-react-start/src/server/clerkMiddleware.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import type { PendingSessionOptions } from '@clerk/shared/types';
66
import type { AnyRequestMiddleware } from '@tanstack/react-start';
77
import { createMiddleware } from '@tanstack/react-start';
88

9+
import { writeAgentRulesOnce } from './agentRules';
910
import { clerkClient } from './clerkClient';
1011
import { loadOptions } from './loadOptions';
1112
import type { ClerkMiddlewareOptions, ClerkMiddlewareOptionsCallback } from './types';
@@ -15,6 +16,8 @@ export const clerkMiddleware = (
1516
options?: ClerkMiddlewareOptions | ClerkMiddlewareOptionsCallback,
1617
): AnyRequestMiddleware => {
1718
return createMiddleware().server(async ({ request, next }) => {
19+
writeAgentRulesOnce();
20+
1821
const clerkRequest = createClerkRequest(patchRequest(request));
1922

2023
// Resolve options: if function, call it with context object; otherwise use as-is

0 commit comments

Comments
 (0)