From 8807c8c616fba383e581c7b27bbe5c1b41b50ada Mon Sep 17 00:00:00 2001 From: Max Davidson Date: Thu, 12 Nov 2026 22:35:17 +0100 Subject: [PATCH 1/3] fix(cursor): Cursor threads follow the rules above the workspace, like Cursor does The Cursor SDK walks from the workspace up to / reading .cursor/rules, AGENTS.md, CLAUDE.md and CLAUDE.local.md, then keeps only files inside the workspace. So ~/.cursor/rules and parent AGENTS.md / CLAUDE.md never reached T3 Cursor threads, though the Cursor app and CLI apply them. T3 now restores exactly the part the SDK drops: for each directory strictly above each workspace root, in the SDK's order (closest first; .cursor/rules, then CLAUDE.md, CLAUDE.local.md, AGENTS.md), skipping anything whose real path is inside a workspace root. .mdc frontmatter is read with a port of the SDK's own line parser, and rules are classified as Cursor does: always-apply rules and the markdown files are inlined; glob and description rules are listed by path for the agent to open; manual rules and .mdc files without frontmatter are skipped. Files past 100 KB are truncated with Cursor's notice. Duplicate markdown files keep one copy, like the SDK. The rules travel next to the T3 orchestration text. T3 remembers the text it sent and sends again on a conversation's first turn, after compaction, when it doesn't know what was sent (such as after a restart), when the rules change, and with a short notice when they are removed. Co-Authored-By: Claude Opus 5.5 --- .../src/server/adapter.test.ts | 136 +++++--- .../provider-cursor/src/server/adapter.ts | 52 ++- .../src/server/ancestorRules.test.ts | 300 +++++++++++++++++ .../src/server/ancestorRules.ts | 304 ++++++++++++++++++ 4 files changed, 735 insertions(+), 57 deletions(-) create mode 100644 packages/provider-cursor/src/server/ancestorRules.test.ts create mode 100644 packages/provider-cursor/src/server/ancestorRules.ts diff --git a/packages/provider-cursor/src/server/adapter.test.ts b/packages/provider-cursor/src/server/adapter.test.ts index e0f31cd8fb4a9..fc46c28562db8 100644 --- a/packages/provider-cursor/src/server/adapter.test.ts +++ b/packages/provider-cursor/src/server/adapter.test.ts @@ -40,6 +40,7 @@ import { makeCursorAdapterV2, nestedToolCallFromEnvelope, } from "./adapter.ts"; +import { CursorRulesWalkStop } from "./ancestorRules.ts"; import * as CursorAgentSdk from "./CursorAgentSdk.ts"; import { loadCursorSdk } from "./sdk.ts"; @@ -683,7 +684,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"); @@ -705,46 +708,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, @@ -806,24 +822,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 243cf7341d405..dd5f6ac350486 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -55,6 +55,11 @@ import { hasCursorSkillMention, rewriteCursorSkillMentions, } from "./skills.ts"; +import { + CURSOR_RULES_REMOVED_NOTICE, + CursorRulesWalkStop, + readCursorRulesAboveWorkspace, +} from "./ancestorRules.ts"; import { t3OrchestrationPrompt } from "@t3tools/provider-core/server/orchestrationInstructions"; import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; @@ -985,6 +990,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; @@ -1015,6 +1021,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<{ @@ -2348,23 +2356,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, @@ -2413,6 +2434,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( return { message: images.length === 0 ? text : ({ text, images } satisfies SDKUserMessage), prompt: userText, + rules: currentRules, }; }); @@ -2440,13 +2462,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, @@ -2480,6 +2503,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..dd0979e9edd6b --- /dev/null +++ b/packages/provider-cursor/src/server/ancestorRules.test.ts @@ -0,0 +1,300 @@ +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 readRoots = (roots: ReadonlyArray) => readCursorRulesAboveWorkspace(roots, top); + const readRaw = readRoots([workspace]); + const read = Effect.map(readRaw, (rules) => rules ?? ""); + return { fileSystem, path, top, workspace, write, readRoots, readRaw, 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, readRoots, 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* readRoots([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.skipIf(!symlinksSupported)( + "reads each root's ancestors once and skips files inside either root", + () => + Effect.gen(function* () { + const { fileSystem, path, top, write, readRoots } = yield* fixture; + const ws1 = path.join(top, "a", "ws1"); + const ws2 = path.join(top, "b", "ws2"); + yield* fileSystem.makeDirectory(ws1, { recursive: true }); + yield* fileSystem.makeDirectory(ws2, { recursive: true }); + yield* write("a/AGENTS.md", "MARK-A"); + yield* write("b/AGENTS.md", "MARK-B"); + yield* write("AGENTS.md", "MARK-TOP"); + yield* write("a/ws1/AGENTS.md", "MARK-IN-WS1"); + yield* write("b/ws2/AGENTS.md", "MARK-IN-WS2"); + const target = yield* write("b/ws2/linked.mdc", always("MARK-LINKED-INTO-WS2")); + yield* write("a/.cursor/rules/real.mdc", always("MARK-A-RULE")); + yield* fileSystem.symlink(target, path.join(top, "a/.cursor/rules/link.mdc")); + + const output = (yield* readRoots([ws1, ws2])) ?? ""; + const order = ["MARK-A-RULE", "MARK-A", "MARK-TOP", "MARK-B"].map((marker) => + indexOfMarker(output, `${marker}\n`), + ); + assert.deepEqual( + order, + order.toSorted((left, right) => left - right), + ); + assert.strictEqual(output.split("MARK-TOP").length - 1, 1); + for (const skipped of ["MARK-IN-WS1", "MARK-IN-WS2", "MARK-LINKED-INTO-WS2"]) { + assert.notInclude(output, skipped); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), + ); + + it.effect("skips empty rule bodies", () => + Effect.gen(function* () { + const { write, readRaw } = yield* fixture; + yield* write(".cursor/rules/empty.mdc", always("")); + yield* write("CLAUDE.md", " \n"); + assert.isUndefined(yield* readRaw); + yield* write("AGENTS.md", "MARK-AGENTS"); + const output = (yield* readRaw) ?? ""; + assert.strictEqual(output.split(" + Effect.gen(function* () { + const { path, top, write, read } = yield* fixture; + for (let index = 0; index <= 100; index += 1) { + yield* write(`.cursor/rules/rule-${String(index).padStart(3, "0")}.mdc`, always("BODY")); + } + const output = yield* read; + const rulePath = (index: number) => + path.join(top, ".cursor/rules", `rule-${String(index).padStart(3, "0")}.mdc`); + assert.strictEqual(output.split("`); + assert.notInclude(output, rulePath(100)); + }).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("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..dc9b5b8d91e76 --- /dev/null +++ b/packages/provider-cursor/src/server/ancestorRules.ts @@ -0,0 +1,304 @@ +// 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* ( + workspaceRoots: ReadonlyArray, + 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 realRoots = yield* Effect.forEach(workspaceRoots, (root) => + realPath(root).pipe(Effect.map(Option.getOrElse(() => path.resolve(root)))), + ); + + /** 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); + const bytes = Option.getOrElse( + yield* handle.readAlloc(Math.min(size, MAX_RULE_BYTES + 1)), + () => new Uint8Array(), + ); + 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 seen = new Set(); + const lastDirectory = stopAt === undefined ? undefined : path.resolve(stopAt); + for (const root of workspaceRoots) { + let directory = path.resolve(root); + while (path.dirname(directory) !== directory && directory !== lastDirectory) { + directory = path.dirname(directory); + const levelFiles = [ + ...(yield* listMdcFiles(path.join(directory, ".cursor", "rules"))).map((file) => ({ + file, + markdown: false, + })), + ...MARKDOWN_RULE_FILES.map((name) => ({ + file: path.join(directory, name), + markdown: true, + })), + ]; + for (const candidate of levelFiles) { + if (seen.has(candidate.file)) continue; + seen.add(candidate.file); + candidates.push(candidate); + } + } + } + + 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 a workspace root. + if (Option.isNone(real) || realRoots.some((root) => isInside(real.value, root))) 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`; +} From 82e74b70d2ed2560db891369a76202d70e062256 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 22:05:26 +0000 Subject: [PATCH 2/3] refactor(cursor): read ancestor rules for the one workspace root the adapter passes The adapter only ever passes the turn's cwd, so drop the multi-root walk and its dedupe, and the tests for the 100-file cap and empty bodies. AI-assisted; verified with the tests and tools listed above. --- .../provider-cursor/src/server/adapter.ts | 2 +- .../src/server/ancestorRules.test.ts | 73 ++----------------- .../src/server/ancestorRules.ts | 38 ++++------ 3 files changed, 20 insertions(+), 93 deletions(-) diff --git a/packages/provider-cursor/src/server/adapter.ts b/packages/provider-cursor/src/server/adapter.ts index dd5f6ac350486..9a8e4aa391f9f 100644 --- a/packages/provider-cursor/src/server/adapter.ts +++ b/packages/provider-cursor/src/server/adapter.ts @@ -2368,7 +2368,7 @@ export const makeCursorAdapterV2 = Effect.fn("makeCursorAdapterV2")(function* ( return { message: "/compress", prompt: undefined, rules: undefined }; } const currentRules = yield* readCursorRulesAboveWorkspace( - [turnInput.runtimePolicy.cwd ?? process.cwd()], + turnInput.runtimePolicy.cwd ?? process.cwd(), rulesWalkStop, ).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), diff --git a/packages/provider-cursor/src/server/ancestorRules.test.ts b/packages/provider-cursor/src/server/ancestorRules.test.ts index dd0979e9edd6b..d88c5ad9dc390 100644 --- a/packages/provider-cursor/src/server/ancestorRules.test.ts +++ b/packages/provider-cursor/src/server/ancestorRules.test.ts @@ -29,10 +29,10 @@ const fixture = Effect.gen(function* () { }); const workspace = path.join(top, "mid", "ws"); yield* fileSystem.makeDirectory(workspace, { recursive: true }); - const readRoots = (roots: ReadonlyArray) => readCursorRulesAboveWorkspace(roots, top); - const readRaw = readRoots([workspace]); - const read = Effect.map(readRaw, (rules) => rules ?? ""); - return { fileSystem, path, top, workspace, write, readRoots, readRaw, read }; + 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) => { @@ -76,7 +76,7 @@ describe("readCursorRulesAboveWorkspace", () => { "skips files inside the workspace, including through symlinks", () => Effect.gen(function* () { - const { fileSystem, path, top, workspace, write, readRoots, read } = yield* fixture; + 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( @@ -88,7 +88,7 @@ describe("readCursorRulesAboveWorkspace", () => { const linkedRoot = path.join(top, "root-link"); yield* fileSystem.symlink(workspace, linkedRoot); - for (const output of [yield* read, (yield* readRoots([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"); @@ -162,67 +162,6 @@ describe("readCursorRulesAboveWorkspace", () => { }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); - it.effect.skipIf(!symlinksSupported)( - "reads each root's ancestors once and skips files inside either root", - () => - Effect.gen(function* () { - const { fileSystem, path, top, write, readRoots } = yield* fixture; - const ws1 = path.join(top, "a", "ws1"); - const ws2 = path.join(top, "b", "ws2"); - yield* fileSystem.makeDirectory(ws1, { recursive: true }); - yield* fileSystem.makeDirectory(ws2, { recursive: true }); - yield* write("a/AGENTS.md", "MARK-A"); - yield* write("b/AGENTS.md", "MARK-B"); - yield* write("AGENTS.md", "MARK-TOP"); - yield* write("a/ws1/AGENTS.md", "MARK-IN-WS1"); - yield* write("b/ws2/AGENTS.md", "MARK-IN-WS2"); - const target = yield* write("b/ws2/linked.mdc", always("MARK-LINKED-INTO-WS2")); - yield* write("a/.cursor/rules/real.mdc", always("MARK-A-RULE")); - yield* fileSystem.symlink(target, path.join(top, "a/.cursor/rules/link.mdc")); - - const output = (yield* readRoots([ws1, ws2])) ?? ""; - const order = ["MARK-A-RULE", "MARK-A", "MARK-TOP", "MARK-B"].map((marker) => - indexOfMarker(output, `${marker}\n`), - ); - assert.deepEqual( - order, - order.toSorted((left, right) => left - right), - ); - assert.strictEqual(output.split("MARK-TOP").length - 1, 1); - for (const skipped of ["MARK-IN-WS1", "MARK-IN-WS2", "MARK-LINKED-INTO-WS2"]) { - assert.notInclude(output, skipped); - } - }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), - ); - - it.effect("skips empty rule bodies", () => - Effect.gen(function* () { - const { write, readRaw } = yield* fixture; - yield* write(".cursor/rules/empty.mdc", always("")); - yield* write("CLAUDE.md", " \n"); - assert.isUndefined(yield* readRaw); - yield* write("AGENTS.md", "MARK-AGENTS"); - const output = (yield* readRaw) ?? ""; - assert.strictEqual(output.split(" - Effect.gen(function* () { - const { path, top, write, read } = yield* fixture; - for (let index = 0; index <= 100; index += 1) { - yield* write(`.cursor/rules/rule-${String(index).padStart(3, "0")}.mdc`, always("BODY")); - } - const output = yield* read; - const rulePath = (index: number) => - path.join(top, ".cursor/rules", `rule-${String(index).padStart(3, "0")}.mdc`); - assert.strictEqual(output.split("`); - assert.notInclude(output, rulePath(100)); - }).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; diff --git a/packages/provider-cursor/src/server/ancestorRules.ts b/packages/provider-cursor/src/server/ancestorRules.ts index dc9b5b8d91e76..c588b89ed0d8d 100644 --- a/packages/provider-cursor/src/server/ancestorRules.ts +++ b/packages/provider-cursor/src/server/ancestorRules.ts @@ -139,7 +139,7 @@ function classifyMdcRule(path: string, contents: string): CursorRule | undefined const decoder = new TextDecoder(); export const readCursorRulesAboveWorkspace = Effect.fn("readCursorRulesAboveWorkspace")(function* ( - workspaceRoots: ReadonlyArray, + workspaceRoot: string, stopAt?: string, ) { const fileSystem = yield* FileSystem.FileSystem; @@ -153,8 +153,8 @@ export const readCursorRulesAboveWorkspace = Effect.fn("readCursorRulesAboveWork }; const realPath = (file: string) => fileSystem.realPath(file).pipe(Effect.map(path.normalize), Effect.option); - const realRoots = yield* Effect.forEach(workspaceRoots, (root) => - realPath(root).pipe(Effect.map(Option.getOrElse(() => path.resolve(root)))), + const realRoot = Option.getOrElse(yield* realPath(workspaceRoot), () => + path.resolve(workspaceRoot), ); /** At most 100 KB plus Cursor's truncation notice; `undefined` when unreadable. */ @@ -210,27 +210,15 @@ export const readCursorRulesAboveWorkspace = Effect.fn("readCursorRulesAboveWork // 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 seen = new Set(); const lastDirectory = stopAt === undefined ? undefined : path.resolve(stopAt); - for (const root of workspaceRoots) { - let directory = path.resolve(root); - while (path.dirname(directory) !== directory && directory !== lastDirectory) { - directory = path.dirname(directory); - const levelFiles = [ - ...(yield* listMdcFiles(path.join(directory, ".cursor", "rules"))).map((file) => ({ - file, - markdown: false, - })), - ...MARKDOWN_RULE_FILES.map((name) => ({ - file: path.join(directory, name), - markdown: true, - })), - ]; - for (const candidate of levelFiles) { - if (seen.has(candidate.file)) continue; - seen.add(candidate.file); - candidates.push(candidate); - } + 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 }); } } @@ -238,8 +226,8 @@ export const readCursorRulesAboveWorkspace = Effect.fn("readCursorRulesAboveWork 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 a workspace root. - if (Option.isNone(real) || realRoots.some((root) => isInside(real.value, root))) continue; + // 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 From 447fb7408e0b74f9fae585ce367100d7b836a6e2 Mon Sep 17 00:00:00 2001 From: Max Davidson Date: Fri, 13 Nov 2026 14:37:00 +0100 Subject: [PATCH 3/3] fix(cursor): ancestor rules survive short filesystem reads A single read can return fewer bytes than requested (for example on network filesystems), which silently cut a rule short or dropped an .mdc rule whose frontmatter was split. Rule files are now read until EOF or the 100 KB budget. Co-Authored-By: Claude Opus 5.5 --- .../src/server/ancestorRules.test.ts | 23 +++++++++++++++++++ .../src/server/ancestorRules.ts | 14 +++++++---- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/packages/provider-cursor/src/server/ancestorRules.test.ts b/packages/provider-cursor/src/server/ancestorRules.test.ts index d88c5ad9dc390..c70831877ff00 100644 --- a/packages/provider-cursor/src/server/ancestorRules.test.ts +++ b/packages/provider-cursor/src/server/ancestorRules.test.ts @@ -177,6 +177,29 @@ describe("readCursorRulesAboveWorkspace", () => { }).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; diff --git a/packages/provider-cursor/src/server/ancestorRules.ts b/packages/provider-cursor/src/server/ancestorRules.ts index c588b89ed0d8d..6ef79cf033d0a 100644 --- a/packages/provider-cursor/src/server/ancestorRules.ts +++ b/packages/provider-cursor/src/server/ancestorRules.ts @@ -164,10 +164,16 @@ export const readCursorRulesAboveWorkspace = Effect.fn("readCursorRulesAboveWork if (info.type !== "File") return undefined; const size = Number(info.size); const handle = yield* fileSystem.open(file); - const bytes = Option.getOrElse( - yield* handle.readAlloc(Math.min(size, MAX_RULE_BYTES + 1)), - () => new Uint8Array(), - ); + // 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;