diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index 1e1e17a1a0ec0..b95c43255a2bc 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -44,6 +44,7 @@ import { makeCursorAdapterV2, nestedToolCallFromEnvelope, } from "./adapter.ts"; +import { CursorRulesWalkStop } from "./ancestorRules.ts"; import * as CursorAgentSdk from "./CursorAgentSdk.ts"; import { loadCursorSdk } from "./sdk.ts"; import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts"; @@ -688,7 +689,9 @@ describe("CursorAdapterV2", () => { it.effect("sends T3 instructions to each Cursor conversation that lacks them", () => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; - const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" }); + const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-device-" }); + const workspace = `${parent}/workspace`; + yield* fileSystem.makeDirectory(workspace); const sentMessages: Array = []; const instanceId = ProviderInstanceId.make("cursor"); const threadId = ThreadId.make("cursor-device-thread"); @@ -710,46 +713,59 @@ describe("CursorAdapterV2", () => { interactionMode: "default", cwd: workspace, }); - const adapter = yield* makeCursorAdapterV2({ - instanceId, - environment: { HOME: workspace }, - }).pipe( - Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { - assertComplete: Effect.void, - open: () => - Effect.succeed({ - agentId: "native-cursor-device", - listMessages: Effect.succeed([]), - close: Effect.void, - send: (input) => - Effect.sync(() => { - sentMessages.push( - typeof input.message === "string" ? input.message : input.message.text, - ); - const runId = `native-cursor-run-${sentMessages.length}`; - return { - agentId: "native-cursor-device", - runId, - wait: Effect.succeed({ - id: runId, - requestId: `native-request-${sentMessages.length}`, - status: "finished" as const, - model: { id: "composer-2.5" }, - durationMs: 1, - }), - cancel: Effect.void, - }; - }), - }), - }), - Effect.provide(TestProviderHost.layer({ cwd: workspace })), - ); - const runtime = yield* adapter.openSession({ - threadId, - providerSessionId: ProviderSessionId.make("cursor-device-session"), - modelSelection, - runtimePolicy, + const home = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-home-" }); + const writeRule = Effect.fnUntraced(function* (body: string) { + yield* fileSystem.makeDirectory(`${parent}/.cursor/rules`, { recursive: true }); + yield* fileSystem.writeFileString( + `${parent}/.cursor/rules/global.mdc`, + `---\nalwaysApply: true\n---\n${body}`, + ); + }); + yield* writeRule("RULE-MARKER-HAIKU"); + const openRuntime = Effect.gen(function* () { + const adapter = yield* makeCursorAdapterV2({ + instanceId, + environment: { HOME: home }, + }).pipe( + Effect.provideService(CursorRulesWalkStop, parent), + Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, { + assertComplete: Effect.void, + open: () => + Effect.succeed({ + agentId: "native-cursor-device", + listMessages: Effect.succeed([]), + close: Effect.void, + send: (input) => + Effect.sync(() => { + sentMessages.push( + typeof input.message === "string" ? input.message : input.message.text, + ); + const runId = `native-cursor-run-${sentMessages.length}`; + return { + agentId: "native-cursor-device", + runId, + wait: Effect.succeed({ + id: runId, + requestId: `native-request-${sentMessages.length}`, + status: "finished" as const, + model: { id: "composer-2.5" }, + durationMs: 1, + }), + cancel: Effect.void, + }; + }), + }), + }), + Effect.provide(TestProviderHost.layer({ cwd: workspace })), + ); + return yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("cursor-device-session"), + modelSelection, + runtimePolicy, + }); }); + let runtime = yield* openRuntime; const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, @@ -811,24 +827,58 @@ describe("CursorAdapterV2", () => { return { orchestration: sent.includes("## T3 Code orchestration"), devices: sent.includes("## T3 Code devices"), + rules: sent.includes(""), }; }); - const told = (orchestration: boolean, devices: boolean) => ({ orchestration, devices }); + const told = (orchestration: boolean, devices: boolean, rules = false) => ({ + orchestration, + devices, + rules, + }); yield* setDeviceAccess(true); - assert.deepEqual(yield* send(), told(false, true)); + assert.deepEqual(yield* send(), told(false, true, true), "first turn this process sees"); + assert.deepEqual(yield* send(), told(false, false), "unchanged rules are not re-sent"); + yield* writeRule("RULE-MARKER-SONNET"); + assert.deepEqual(yield* send(), told(false, false, true), "changed rules are re-sent"); + assert.include(sentMessages.at(-1)!, "RULE-MARKER-SONNET"); + assert.notInclude(sentMessages.at(-1)!, "RULE-MARKER-HAIKU"); + assert.deepEqual(yield* send(), told(false, false)); + yield* fileSystem.remove(`${parent}/.cursor/rules/global.mdc`); + assert.deepEqual(yield* send(), told(false, false, true), "removed rules are retracted"); + assert.include(sentMessages.at(-1)!, "The user removed the Cursor rules"); assert.deepEqual(yield* send(), told(false, false)); + yield* writeRule("RULE-MARKER-SONNET"); + assert.deepEqual(yield* send(), told(false, false, true), "restored rules are re-sent"); yield* send(true); assert.deepEqual( yield* send(), - told(true, true), + told(true, true, true), "compaction drops what the conversation was told", ); + const afterCompaction = sentMessages.at(-1)!; + const orchestrationAt = afterCompaction.indexOf("## T3 Code orchestration"); + const rulesAt = afterCompaction.indexOf(""); + const messageAt = afterCompaction.indexOf("Open the app."); + assert.include(afterCompaction, "RULE-MARKER-SONNET"); + assert.isAtLeast(orchestrationAt, 0); + assert.isAtLeast(rulesAt, 0); + assert.isAtLeast(messageAt, 0); + assert.isBelow(orchestrationAt, rulesAt); + assert.isBelow(rulesAt, messageAt); yield* setDeviceAccess(false); assert.deepEqual(yield* send(), told(false, false)); yield* setDeviceAccess(true); assert.deepEqual(yield* send(), told(false, true), "device access turned on later"); assert.deepEqual(yield* send(), told(false, false)); + // A restarted process has no memory of what the conversation was told. + runtime = yield* openRuntime; + assert.deepEqual( + yield* send(), + told(false, true, true), + "rules are re-sent after a restart, orchestration is not", + ); + assert.deepEqual(yield* send(), told(false, false)); }).pipe( Effect.scoped, Effect.provide( diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index 1e160be188f08..8cdf704ea572e 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -56,6 +56,11 @@ import { hasCursorSkillMention, rewriteCursorSkillMentions, } from "./skills.ts"; +import { + CURSOR_RULES_REMOVED_NOTICE, + CursorRulesWalkStop, + readCursorRulesAboveWorkspace, +} from "./ancestorRules.ts"; import { cursorWorkspaceMcpServers } from "./workspaceMcpServers.ts"; import { t3OrchestrationPrompt } from "@t3tools/provider-core/server/orchestrationInstructions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; @@ -988,6 +993,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const platform = yield* HostProcess.Platform; const host = yield* ProviderHost.ProviderHost; const mcpSessions = yield* McpProviderSessions.McpProviderSessions; + const rulesWalkStop = yield* CursorRulesWalkStop; const adapterOptions = options; const apiKey = adapterOptions.environment.CURSOR_API_KEY?.trim() || undefined; @@ -1018,6 +1024,8 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( readonly agent: string; readonly orchestration: boolean; readonly device: boolean; + /** The rules text the conversation was last sent, if T3 knows it. */ + readonly rules: string | undefined; } | null>(null); // Cursor drops a cancelled run from the conversation, so the next message carries its prompt. const interruptedPrompt = yield* Ref.make<{ @@ -2367,23 +2375,36 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, mcpServers: Record | undefined, hasDeviceTools: boolean, - delivered: { readonly orchestration: boolean; readonly device: boolean }, + delivered: { + readonly orchestration: boolean; + readonly device: boolean; + readonly rules: string | undefined; + }, interrupted: string | undefined, ) { const rawText = turnInput.message.text; if (rawText.trim() === "/compress" && turnInput.message.attachments.length === 0) { - return { message: "/compress", prompt: undefined }; + return { message: "/compress", prompt: undefined, rules: undefined }; } + const currentRules = yield* readCursorRulesAboveWorkspace( + turnInput.runtimePolicy.cwd ?? process.cwd(), + rulesWalkStop, + ).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + ); + const rules = + currentRules === delivered.rules + ? undefined + : (currentRules ?? CURSOR_RULES_REMOVED_NOTICE); + const resolved = yield* providerMessageTextWithAttachmentPaths({ + text: yield* resolveCursorSkillText(rawText, turnInput.runtimePolicy.cwd ?? undefined), + attachments: turnInput.message.attachments, + resolveAttachmentPath: host.resolveAttachmentPath, + resolveExtractedTextPath: host.resolveExtractedTextPath, + }); const newText = t3OrchestrationPrompt({ - prompt: yield* providerMessageTextWithAttachmentPaths({ - text: yield* resolveCursorSkillText( - rawText, - turnInput.runtimePolicy.cwd ?? undefined, - ), - attachments: turnInput.message.attachments, - resolveAttachmentPath: host.resolveAttachmentPath, - resolveExtractedTextPath: host.resolveExtractedTextPath, - }), + prompt: rules === undefined ? resolved : `${rules}\n\n${resolved}`, hasT3Mcp: mcpServers !== undefined, hasDeviceTools, orchestrationDelivered: delivered.orchestration, @@ -2432,6 +2453,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( return { message: images.length === 0 ? text : ({ text, images } satisfies SDKUserMessage), prompt: userText, + rules: currentRules, }; }); @@ -2459,13 +2481,14 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( const hasDeviceTools = mcpServers !== undefined && mcpSession?.capabilities?.has("device") === true; const known = yield* Ref.get(told); - // A conversation this process has not sent to was told on its first run. + // A conversation this process has not sent to was told the orchestration text on its + // first run; its rules may have changed since, so they are sent again. const delivered = known?.agent === agent.nativeThreadId ? known - : { orchestration: turnInput.runOrdinal > 1, device: false }; + : { orchestration: turnInput.runOrdinal > 1, device: false, rules: undefined }; const interrupted = yield* Ref.get(interruptedPrompt); - const { message, prompt } = yield* resolveUserMessage( + const { message, prompt, rules } = yield* resolveUserMessage( turnInput, mcpServers, hasDeviceTools, @@ -2506,6 +2529,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( agent: agent.nativeThreadId, orchestration: !compacted && (delivered.orchestration || mcpServers !== undefined), device: !compacted && hasDeviceTools, + rules: compacted ? undefined : rules, }); if (!compacted) { yield* Ref.set(interruptedPrompt, null); diff --git a/packages/provider-cursor/src/server/ancestorRules.test.ts b/packages/provider-cursor/src/server/ancestorRules.test.ts new file mode 100644 index 0000000000000..c70831877ff00 --- /dev/null +++ b/packages/provider-cursor/src/server/ancestorRules.test.ts @@ -0,0 +1,262 @@ +import * as NodeOS from "node:os"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +import * as HostProcess from "@t3tools/shared/HostProcess"; +import { symlinksSupported } from "@t3tools/shared/testing/symlinks"; + +import { readCursorRulesAboveWorkspace } from "./ancestorRules.ts"; + +const always = (body: string) => `---\nalwaysApply: true\n---\n${body}\n`; + +// The walk stops at `top`, so the host's real ancestors never reach the output. +const fixture = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const top = yield* fileSystem.makeTempDirectoryScoped({ + directory: NodeOS.tmpdir(), + prefix: "cursor-ancestor-rules-", + }); + const write = Effect.fnUntraced(function* (file: string, contents: string | Uint8Array) { + const target = path.join(top, file); + yield* fileSystem.makeDirectory(path.dirname(target), { recursive: true }); + if (typeof contents === "string") yield* fileSystem.writeFileString(target, contents); + else yield* fileSystem.writeFile(target, contents); + return target; + }); + const workspace = path.join(top, "mid", "ws"); + yield* fileSystem.makeDirectory(workspace, { recursive: true }); + const readRoot = (root: string) => + Effect.map(readCursorRulesAboveWorkspace(root, top), (rules) => rules ?? ""); + const read = readRoot(workspace); + return { fileSystem, path, top, workspace, write, readRoot, read }; +}); + +const indexOfMarker = (output: string, marker: string) => { + const index = output.indexOf(marker); + assert.isAtLeast(index, 0, `${marker} is missing`); + return index; +}; + +describe("readCursorRulesAboveWorkspace", () => { + it.effect("orders levels closest first and files within a level like the SDK", () => + Effect.gen(function* () { + const { write, read } = yield* fixture; + yield* write(".cursor/rules/sub/a.mdc", always("MARK-TOP-SUB-A")); + yield* write(".cursor/rules/b.mdc", always("MARK-TOP-B")); + yield* write("CLAUDE.md", "MARK-TOP-CLAUDE"); + yield* write("CLAUDE.local.md", "MARK-TOP-CLAUDE-LOCAL"); + yield* write("AGENTS.md", "MARK-TOP-AGENTS"); + yield* write("mid/.cursor/rules/z.mdc", always("MARK-MID-Z")); + yield* write("mid/AGENTS.md", "MARK-MID-AGENTS"); + + const output = yield* read; + const order = [ + "MARK-MID-Z", + "MARK-MID-AGENTS", + "MARK-TOP-B", + "MARK-TOP-SUB-A", + "MARK-TOP-CLAUDE\n", + "MARK-TOP-CLAUDE-LOCAL", + "MARK-TOP-AGENTS", + ].map((marker) => indexOfMarker(output, marker)); + assert.deepEqual( + order, + order.toSorted((left, right) => left - right), + ); + assert.isTrue(output.startsWith("\n")); + assert.isTrue(output.endsWith("")); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.skipIf(!symlinksSupported)( + "skips files inside the workspace, including through symlinks", + () => + Effect.gen(function* () { + const { fileSystem, path, top, workspace, write, readRoot, read } = yield* fixture; + yield* write("mid/ws/.cursor/rules/in.mdc", always("MARK-IN-WORKSPACE")); + yield* write("mid/ws/AGENTS.md", "MARK-WORKSPACE-AGENTS"); + const target = yield* write( + "mid/ws/outside-target.mdc", + always("MARK-LINKED-INTO-WORKSPACE"), + ); + yield* write(".cursor/rules/keep.mdc", always("MARK-KEPT")); + yield* fileSystem.symlink(target, path.join(top, ".cursor/rules/link.mdc")); + const linkedRoot = path.join(top, "root-link"); + yield* fileSystem.symlink(workspace, linkedRoot); + + for (const output of [yield* read, yield* readRoot(linkedRoot)]) { + indexOfMarker(output, "MARK-KEPT"); + assert.notInclude(output, "MARK-IN-WORKSPACE"); + assert.notInclude(output, "MARK-WORKSPACE-AGENTS"); + assert.notInclude(output, "MARK-LINKED-INTO-WORKSPACE"); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("inlines always rules and only lists requestable ones", () => + Effect.gen(function* () { + const { write, read } = yield* fixture; + const rules = ".cursor/rules/"; + const description = yield* write( + `${rules}desc.mdc`, + '---\ndescription: "Use for API work"\n---\nBODY-DESC', + ); + const globString = yield* write( + `${rules}globs.mdc`, + "---\nglobs: *.ts,*.tsx\n---\nBODY-GLOBS", + ); + const globList = yield* write( + `${rules}list.mdc`, + "---\nglobs:\n - src/**/*.rs\n - '*.toml'\n---\nBODY-LIST", + ); + const colon = yield* write( + `${rules}colon.mdc`, + "---\ndescription: Use when: x\n---\nBODY-COLON", + ); + const upper = yield* write(`${rules}upper.mdc`, "---\nalwaysApply: True\n---\nBODY-UPPER"); + const quoted = yield* write( + `${rules}quoted.mdc`, + '---\nalwaysApply: "true"\ndescription: Quoted flag\n---\nBODY-QUOTED', + ); + const quotedList = yield* write( + `${rules}quoted-list.mdc`, + '---\nglobs:\n - "*.ts"\n - src/**\n---\nBODY-QLIST', + ); + yield* write(`${rules}indented.mdc`, "---\n alwaysApply: true\n---\nBODY-INDENTED"); + yield* write(`${rules}manual.mdc`, "---\nalwaysApply: false\n---\nBODY-MANUAL"); + yield* write(`${rules}plain.mdc`, "BODY-NOFRONTMATTER"); + yield* write(`${rules}note.md`, "---\nalwaysApply: true\n---\nBODY-MARKDOWN"); + yield* write(`${rules}always.mdc`, always("BODY-ALWAYS")); + + const output = yield* read; + indexOfMarker(output, "BODY-ALWAYS"); + indexOfMarker(output, "BODY-INDENTED"); + assert.include(output, `- ${quoted}: Quoted flag`); + assert.include(output, `- ${quotedList} (applies to files matching *.ts, src/**)`); + assert.notInclude(output, upper); + assert.include(output, `- ${description}: Use for API work`); + assert.include(output, `- ${globString} (applies to files matching *.ts, *.tsx)`); + assert.include(output, `- ${globList} (applies to files matching src/**/*.rs, *.toml)`); + assert.include(output, `- ${colon}: Use when: x`); + for (const skipped of [ + "BODY-DESC", + "BODY-GLOBS", + "BODY-LIST", + "BODY-COLON", + "BODY-MANUAL", + "BODY-NOFRONTMATTER", + "BODY-MARKDOWN", + "BODY-QUOTED", + "BODY-QLIST", + "BODY-UPPER", + "manual.mdc", + "plain.mdc", + "note.md", + ]) { + assert.notInclude(output, skipped); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("loads BOM and CRLF rules as an LF body without frontmatter", () => + Effect.gen(function* () { + const { write, read } = yield* fixture; + yield* write( + ".cursor/rules/crlf.mdc", + "---\r\nalwaysApply: true\r\n---\r\nBODY-CRLF\r\nsecond line\r\n", + ); + const output = yield* read; + assert.include(output, "BODY-CRLF\nsecond line\n"); + assert.notInclude(output, "\r"); + assert.notInclude(output, ""); + assert.notInclude(output, "alwaysApply"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("reads a rule whole when the filesystem returns short reads", () => + Effect.gen(function* () { + const { fileSystem, write, read } = yield* fixture; + yield* write("AGENTS.md", "MARK-START then more text after the first chunk MARK-END"); + const shortReads: FileSystem.FileSystem = { + ...fileSystem, + open: (file, options) => + Effect.map( + fileSystem.open(file, options), + (handle) => + new Proxy(handle, { + get: (target, key, receiver) => + key === "readAlloc" + ? (size: number) => target.readAlloc(Math.min(size, 7)) + : Reflect.get(target, key, receiver), + }), + ), + }; + const output = yield* read.pipe(Effect.provideService(FileSystem.FileSystem, shortReads)); + assert.isBelow(indexOfMarker(output, "MARK-START"), indexOfMarker(output, "MARK-END")); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("truncates oversized rules at a UTF-8 boundary instead of skipping them", () => + Effect.gen(function* () { + const { write, read } = yield* fixture; + const encoder = new TextEncoder(); + // 102399 ASCII bytes, so the 102400-byte limit lands inside the first 3-byte "€". + const big = (head: string) => + encoder.encode( + `${head}${"a".repeat(102_399 - head.length)}${"€".repeat(20_000)}MARK-AFTER`, + ); + const markdown = big("MARK-BEFORE-MD"); + const mdc = encoder.encode( + `${always("MARK-BEFORE-MDC")}${"b".repeat(102_400)}MARK-AFTER-MDC`, + ); + yield* write("AGENTS.md", markdown); + yield* write(".cursor/rules/big.mdc", mdc); + + const output = yield* read; + indexOfMarker(output, "MARK-BEFORE-MD"); + indexOfMarker(output, "MARK-BEFORE-MDC"); + const notice = (name: string, size: number) => + `[truncated: ${name} is ${Math.round(size / 1024)} KB; only the first 100 KB is included]`; + indexOfMarker(output, notice("AGENTS.md", markdown.length)); + indexOfMarker(output, notice("big.mdc", mdc.length)); + assert.notInclude(output, "�"); + assert.notInclude(output, "MARK-AFTER"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect.skipIf(!symlinksSupported)("keeps one copy of duplicate markdown rules", () => + Effect.gen(function* () { + const { fileSystem, path, top, write, read } = yield* fixture; + const agents = yield* write("AGENTS.md", "MARK-SHARED-TOP"); + yield* fileSystem.symlink(agents, path.join(top, "CLAUDE.md")); + yield* write("mid/AGENTS.md", "MARK-SHARED-TOP"); + yield* write("mid/CLAUDE.md", "MARK-MID-ONLY"); + + const output = yield* read; + assert.include(output, ``); + assert.notInclude(output, ``); + assert.notInclude(output, ``); + assert.strictEqual(output.split("MARK-SHARED-TOP").length - 1, 1); + indexOfMarker(output, "MARK-MID-ONLY"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + // Root and Windows can read a 0o000 file. + it.effect.skipIf(process.getuid?.() === 0 || HostProcess.Platform.defaultValue() === "win32")( + "skips unreadable files without failing", + () => + Effect.gen(function* () { + const { fileSystem, write, read } = yield* fixture; + const locked = yield* write("mid/AGENTS.md", "MARK-LOCKED"); + yield* write("CLAUDE.md", "MARK-READABLE"); + yield* fileSystem.chmod(locked, 0o000); + const output = yield* read; + indexOfMarker(output, "MARK-READABLE"); + assert.notInclude(output, "MARK-LOCKED"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); +}); diff --git a/packages/provider-cursor/src/server/ancestorRules.ts b/packages/provider-cursor/src/server/ancestorRules.ts new file mode 100644 index 0000000000000..6ef79cf033d0a --- /dev/null +++ b/packages/provider-cursor/src/server/ancestorRules.ts @@ -0,0 +1,298 @@ +// The Cursor SDK walks from the workspace up to / for rules, then keeps only those inside the +// workspace, so ~/.cursor/rules and parent AGENTS.md / CLAUDE.md never reach the model. +// This restores exactly that dropped part of the walk, mirroring the SDK's LocalCursorRulesService. + +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; +import * as Path from "effect/Path"; + +// Cursor truncates (rather than skips) markdown rules past this many UTF-8 bytes. +const MAX_RULE_BYTES = 102_400; +const MAX_DESCRIPTION_CHARS = 1536; +const MAX_RULES_DIRECTORY_DEPTH = 10; +const MAX_RULES_DIRECTORY_ENTRIES = 1000; +const MAX_RULE_FILES = 100; +// Within one directory the SDK reads these after .cursor/rules, in this order. +const MARKDOWN_RULE_FILES = ["CLAUDE.md", "CLAUDE.local.md", "AGENTS.md"] as const; + +/** Tests only: the last directory the walk reads, so fixtures ignore the host's real ancestors. */ +export const CursorRulesWalkStop = Context.Reference( + "@t3tools/provider-cursor/CursorRulesWalkStop", + { defaultValue: () => undefined }, +); + +type CursorRule = + | { readonly kind: "always"; readonly path: string; readonly body: string } + | { readonly kind: "globs"; readonly path: string; readonly globs: ReadonlyArray } + | { readonly kind: "described"; readonly path: string; readonly description: string }; + +const isQuoted = (value: string) => + (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")); + +/** Cursor's frontmatter value: bare true/false are booleans, surrounding quotes are stripped. */ +function cursorValue(raw: string): string | boolean { + const value = raw.trim(); + if (value === "true") return true; + if (value === "false") return false; + return isQuoted(value) ? value.slice(1, -1) : value; +} + +/** + * Port of the SDK's `.mdc` parser (not YAML), quirks included: the block ends at the next `---` + * anywhere, and indented `- item` lines fill only `globs:` or a `metadata:` child left empty. + * It skips the SDK's comma-splitting of `metadata.environments`-style keys, which rules never read. + */ +function parseCursorRuleFile(contents: string): + | { + readonly frontmatter: Record>; + readonly body: string; + } + | undefined { + const text = contents.trimStart(); + if (!text.startsWith("---")) return undefined; + const parts = text.split("---").filter(Boolean); + if (parts.length < 2) return undefined; + const frontmatter: Record> = {}; + let parent: string | undefined; + let listKey: string | undefined; + for (const rawLine of (parts[0] ?? "").trim().split("\n")) { + const line = rawLine.replace(/\r$/, ""); + const item = /^\s+-\s+(.*)$/.exec(line); + if (item && listKey !== undefined) { + const value = (item[1] ?? "").trim(); + const list = frontmatter[listKey]; + if (Array.isArray(list)) list.push(isQuoted(value) ? value.slice(1, -1) : value); + continue; + } + if (parent !== undefined && (line.startsWith(" ") || line.startsWith("\t"))) { + const entry = line.trim(); + const separator = entry.indexOf(":"); + if (separator === -1) continue; + const key = `${parent}.${entry.slice(0, separator).trim()}`; + const value = entry.slice(separator + 1).trim(); + frontmatter[key] = value === "" ? [] : cursorValue(value); + listKey = value === "" ? key : undefined; + continue; + } + parent = undefined; + listKey = undefined; + const separator = line.indexOf(":"); + if (separator === -1) continue; + const key = line.slice(0, separator).trim(); + const value = line.slice(separator + 1).trim(); + if (key === "metadata" && value === "") { + parent = key; + } else if (key === "globs" && value === "") { + frontmatter.globs = []; + listKey = key; + } else { + frontmatter[key] = cursorValue(value); + } + } + return { frontmatter, body: parts.slice(1).join("---").trim() }; +} + +/** Cursor splits a globs string on commas outside `{...}`. */ +function cursorGlobs(value: unknown): ReadonlyArray { + if (Array.isArray(value)) { + return value + .filter((glob) => typeof glob === "string") + .map((glob) => glob.trim()) + .filter(Boolean); + } + if (typeof value !== "string") return []; + const globs: Array = []; + let depth = 0; + let start = 0; + for (let index = 0; index < value.length; index += 1) { + const char = value[index]; + if (char === "{") depth += 1; + else if (char === "}" && depth > 0) depth -= 1; + else if (char === "," && depth === 0) { + globs.push(value.slice(start, index)); + start = index + 1; + } + } + const rest = value.slice(start); + globs.push(...(depth > 0 ? rest.split(",") : [rest])); + return globs.map((glob) => glob.trim()).filter(Boolean); +} + +/** Classifies an .mdc rule as the SDK's toCursorRule does; manual rules return `undefined`. */ +function classifyMdcRule(path: string, contents: string): CursorRule | undefined { + // Without a frontmatter block the SDK does not load an .mdc file at all. + const parsed = parseCursorRuleFile(contents); + if (parsed === undefined) return undefined; + const data = parsed.frontmatter; + if (data.alwaysApply === true) return { kind: "always", path, body: parsed.body }; + const globs = cursorGlobs(data.globs); + if (globs.length > 0) return { kind: "globs", path, globs }; + const description = typeof data.description === "string" ? data.description.trim() : ""; + if (description.length > 0) { + return { kind: "described", path, description: description.slice(0, MAX_DESCRIPTION_CHARS) }; + } + return undefined; +} + +const decoder = new TextDecoder(); + +export const readCursorRulesAboveWorkspace = Effect.fn("readCursorRulesAboveWorkspace")(function* ( + workspaceRoot: string, + stopAt?: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const isInside = (child: string, parent: string) => { + const relative = path.relative(parent, child); + return ( + relative === "" || + (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) + ); + }; + const realPath = (file: string) => + fileSystem.realPath(file).pipe(Effect.map(path.normalize), Effect.option); + const realRoot = Option.getOrElse(yield* realPath(workspaceRoot), () => + path.resolve(workspaceRoot), + ); + + /** At most 100 KB plus Cursor's truncation notice; `undefined` when unreadable. */ + const readRuleText = Effect.fn("readCursorRulesAboveWorkspace.readRuleText")( + function* (file: string) { + const info = yield* fileSystem.stat(file); + if (info.type !== "File") return undefined; + const size = Number(info.size); + const handle = yield* fileSystem.open(file); + // One read may return fewer bytes than asked (e.g. network filesystems). + const chunks: Array = []; + let remaining = Math.min(size, MAX_RULE_BYTES + 1); + while (remaining > 0) { + const chunk = yield* handle.readAlloc(remaining); + if (Option.isNone(chunk)) break; + chunks.push(chunk.value); + remaining -= chunk.value.length; + } + const bytes = Buffer.concat(chunks); + if (size <= MAX_RULE_BYTES) return decoder.decode(bytes).replace(/^\uFEFF/, ""); + let end = MAX_RULE_BYTES; + while (end > 0 && ((bytes[end] ?? 0) & 0xc0) === 0x80) end -= 1; + const notice = `[truncated: ${path.basename(file)} is ${Math.round(size / 1024)} KB; only the first 100 KB is included]`; + return `${decoder.decode(bytes.subarray(0, end)).replace(/^\uFEFF/, "")}\n\n${notice}`; + }, + Effect.scoped, + Effect.orElseSucceed(() => undefined), + ); + + /** `.mdc` files below a `.cursor/rules` directory, sorted by relative path; symlinks followed. */ + const listMdcFiles = Effect.fn("readCursorRulesAboveWorkspace.listMdcFiles")(function* ( + rulesDirectory: string, + ) { + const files: Array = []; + let remainingEntries = MAX_RULES_DIRECTORY_ENTRIES; + const visit = Effect.fnUntraced(function* ( + directory: string, + depth: number, + ): Effect.fn.Return { + const names = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => [])); + for (const name of names.toSorted()) { + if (remainingEntries <= 0) return; + remainingEntries -= 1; + const entry = path.join(directory, name); + const info = yield* fileSystem.stat(entry).pipe(Effect.option); + if (Option.isNone(info)) continue; + if (info.value.type === "Directory") { + if (depth < MAX_RULES_DIRECTORY_DEPTH) yield* visit(entry, depth + 1); + } else if (info.value.type === "File" && name.endsWith(".mdc")) { + files.push(entry); + } + } + }); + yield* visit(rulesDirectory, 0); + return files.toSorted((left, right) => + path.relative(rulesDirectory, left).localeCompare(path.relative(rulesDirectory, right)), + ); + }); + + // The SDK walks each level closest-first: .cursor/rules, then CLAUDE.md, CLAUDE.local.md, AGENTS.md. + const candidates: Array<{ readonly file: string; readonly markdown: boolean }> = []; + const lastDirectory = stopAt === undefined ? undefined : path.resolve(stopAt); + let directory = path.resolve(workspaceRoot); + while (path.dirname(directory) !== directory && directory !== lastDirectory) { + directory = path.dirname(directory); + for (const file of yield* listMdcFiles(path.join(directory, ".cursor", "rules"))) { + candidates.push({ file, markdown: false }); + } + for (const name of MARKDOWN_RULE_FILES) { + candidates.push({ file: path.join(directory, name), markdown: true }); + } + } + + const loaded: Array<{ readonly rule: CursorRule; readonly real?: string }> = []; + for (const { file, markdown } of candidates) { + if (loaded.length >= MAX_RULE_FILES) break; + const real = yield* realPath(file); + // The SDK already loads (and keeps) everything that resolves into the workspace. + if (Option.isNone(real) || isInside(real.value, realRoot)) continue; + const text = yield* readRuleText(file); + if (text === undefined) continue; + const rule = markdown + ? { kind: "always" as const, path: file, body: text.trim() } + : classifyMdcRule(file, text); + if (rule === undefined || (rule.kind === "always" && rule.body.length === 0)) continue; + loaded.push(markdown ? { rule, real: real.value } : { rule }); + } + return renderCursorRules(dropDuplicateMarkdownRules(loaded, path)); +}); + +/** + * Like the SDK, keeps one copy of markdown rules that share a file or trimmed content, preferring + * the shallowest directory and AGENTS.md within one, while keeping the walk order. + */ +function dropDuplicateMarkdownRules( + loaded: ReadonlyArray<{ readonly rule: CursorRule; readonly real?: string }>, + path: Path.Path, +): ReadonlyArray { + const depth = (file: string) => file.split(/[\\/]+/).filter(Boolean).length; + const isAgents = (file: string) => path.basename(file) === "AGENTS.md"; + const markdown = loaded + .filter((entry) => entry.real !== undefined) + .toSorted( + (left, right) => + depth(path.dirname(left.rule.path)) - depth(path.dirname(right.rule.path)) || + Number(isAgents(right.rule.path)) - Number(isAgents(left.rule.path)), + ); + const identities = new Set(); + const dropped = new Set(); + for (const { rule, real } of markdown) { + const keys = [`file:${real}`, `text:${rule.kind === "always" ? rule.body : ""}`]; + if (keys.some((key) => identities.has(key))) dropped.add(rule); + else for (const key of keys) identities.add(key); + } + return loaded.flatMap(({ rule }) => (dropped.has(rule) ? [] : [rule])); +} + +/** Sent once when a conversation was given rules that no longer exist. */ +export const CURSOR_RULES_REMOVED_NOTICE = + "\nThe user removed the Cursor rules from the folders above this workspace. Stop following any earlier block.\n"; + +function renderCursorRules(rules: ReadonlyArray): string | undefined { + const sections: Array = []; + const requestable: Array = []; + for (const rule of rules) { + if (rule.kind === "always") { + sections.push(`\n${rule.body.replace(/\r\n/g, "\n")}\n`); + } else if (rule.kind === "globs") { + requestable.push(`- ${rule.path} (applies to files matching ${rule.globs.join(", ")})`); + } else { + requestable.push(`- ${rule.path}: ${rule.description}`); + } + } + if (sections.length === 0 && requestable.length === 0) return undefined; + if (requestable.length > 0) { + sections.push( + `Read these rules with your file tools when they apply:\n${requestable.join("\n")}`, + ); + } + return `\nThe user's Cursor rules from the folders above this workspace, such as ~/.cursor/rules and ~/AGENTS.md. Follow them alongside the workspace's own rules. They replace any earlier block.\n\n${sections.join("\n\n")}\n`; +}