Cursor Agent repeatedly generates Python code that violates the same explicit, deterministic repository hard rules

Where does the bug appear (feature/product)?

Cursor IDE

Describe the Bug

Where does the bug appear (feature/product)?

Editor, Tab & Chat — Cursor IDE Agent


Describe the Bug

Cursor Agent repeatedly generates Python code that violates the same explicit, deterministic repository hard rules, even though those rules are provided before any code changes and the Agent is explicitly instructed to validate them before continuing.

This is not an occasional lint failure.

In my regular usage, the following four violations appear in more than 95% of Agent implementation responses:

[MODULE_SIZE] module physical LOC
[MODULE_SIZE] module logical LOC
PLR2004 Magic value used in comparison
TC001 Move application import into a type-checking block

These rules are already explicitly documented in repository instructions such as AGENTS.md / architecture guardrails, and the implementation prompts explicitly tell Agent to read and follow those rules before modifying anything.

The prompts also explicitly require Agent to validate the implementation using Ruff, Pylint, Mypy, Pytest, Behave, pre-commit and the repository’s quality-check workflow before considering the work complete.

Despite this, the same violations are introduced over and over.

The most problematic behavior is that this does not only happen between separate prompts.

Agent enters repeated self-repair cycles inside the same request:

Agent receives explicit hard rules
        ↓
Agent implements code
        ↓
Ruff / structural audit rejects the patch
        ↓
Agent acknowledges that the violation should not have happened
        ↓
Agent repairs it
        ↓
another quality gate finds another avoidable issue
        ↓
Agent repairs that
        ↓
structural audit finds MODULE_SIZE
        ↓
Agent refactors again
        ↓
more validation / more Agent work

For example, during the attached run Agent explicitly said:

“Tenés razón: esos dos hallazgos son incumplimientos concretos y no debieron llegar al siguiente slice.”

(“You’re right: those two findings are concrete violations and should not have reached the next slice.”)

Agent then repaired the reported Ruff problems.

Still within the same original request:

  1. Behave failed to execute because Agent had introduced an incorrect import for a shared helper.
  2. Agent repaired that.
  3. Tests were run again.
  4. The repository structural audit then detected module-size violations.
  5. Agent started another refactoring pass to repair those violations.

The Agent itself acknowledged:

“La auditoría estructural bloqueó correctamente dos problemas: el método diferencial supera por 3 LOC el hard cap y el servicio legacy de reprogramación creció sobre su ratchet.”

So Agent clearly understands the rule once an external gate reports it.

The problem is that the same classes of violations are then introduced again in subsequent implementation work.

This happens repeatedly with:

MODULE_SIZE physical LOC
MODULE_SIZE logical LOC
PLR2004
TC001

The resulting pattern is therefore not simply:

AI made a mistake
→ user reports it
→ AI fixes it

It is:

rule exists before generation
→ Agent violates it
→ deterministic gate catches it
→ Agent explicitly acknowledges the violation
→ Agent repairs it
→ Agent later introduces the same class of violation again

This significantly affects autonomous Agent workflows.

Every preventable violation results in additional semantic Agent work and additional usage/credits even though the violated constraint was explicitly known before the initial generation.

I am not reporting that Agent must produce perfect code or that functional tests should never fail.

I am reporting the extremely high recurrence of the same deterministic, explicitly supplied static/architectural constraints.


Steps to Reproduce

  1. Use a Python repository with strict repository-level hard rules.

  2. Enable Ruff rules including at least:

PLR2004
TC001
  1. Add deterministic module-size hard limits, including both:
module physical LOC
module logical LOC
  1. Document these rules explicitly in repository instructions such as AGENTS.md and architecture guardrails.

  2. In the Agent prompt, explicitly require the Agent to read those instructions before changing anything.

For example, my prompts include instructions equivalent to:

Before changing anything, read and strictly follow:

AGENTS.md
ARCHITECTURE_GUARDRAILS.md
DOMAIN_MAP.md
TESTING.md
AI_CONTEXT.md
ARCHITECTURE.md
REPO_MAP.md
ARCHITECTURE_DECISIONS.md
CODEBASE_ENTRYPOINTS.md
ORDER_LIFECYCLE.md
STYLE.md

They additionally require, before finishing:

Always verify:

pylint
pytest
behave
ruff
mypy
PEP 8
PEP 257
PEP 484

Run pre-commit on the host.

Use Docker for:
ruff
pylint
mypy
pytest
behave

Run the repository quality-check workflow before completion.
  1. Ask Agent to implement a normal non-trivial Python change.

  2. Run the repository gates over the generated patch.

  3. In my usage, more than 95% of implementation responses contain one or more of:

[MODULE_SIZE] module physical LOC
[MODULE_SIZE] module logical LOC
PLR2004 Magic value used in comparison
TC001 Move application import into a type-checking block
  1. Allow Agent to repair the findings.

  2. Observe Agent explicitly acknowledging that the violation should not have been introduced.

  3. Continue the same request or another implementation slice.

  4. Observe the same violation classes being introduced again.

This is reproducible across many implementation tasks, not one isolated response.


Expected Behavior

When deterministic constraints are explicitly provided before implementation, Agent should incorporate them into implementation planning and first-pass code generation.

MODULE_SIZE — physical and logical LOC

Before adding code to an existing module, Agent should account for the repository’s configured physical and logical LOC limits.

If a module is already close to its hard limit, Agent should design the implementation accordingly during the first pass, for example by extracting the new responsibility into an appropriate module.

The expected workflow is:

inspect module
→ consider remaining LOC budget
→ plan responsibility placement
→ implement within hard rules

Not:

append implementation to existing module
→ violate MODULE_SIZE
→ external audit rejects it
→ Agent acknowledges violation
→ Agent refactors

Both physical and logical module-size limits are deterministic and can be evaluated before or immediately after code generation.

PLR2004

If Ruff PLR2004 is enabled and explicitly required, Agent should avoid introducing magic values in comparisons and should create semantically appropriate constants where required.

This violation appears repeatedly in newly generated code despite the rule already being known.

TC001

If Ruff TC001 is enabled and explicitly required, Agent should correctly identify application imports that are only needed for type checking and structure them appropriately.

This also appears repeatedly in newly generated code despite being part of the repository’s required Ruff contract.

Self-validation

If Agent claims it followed the repository quality contract, the generated patch should not routinely violate those exact rules.

Occasional failures are understandable.

A greater-than-95% recurrence rate for the same four known constraints is not expected behavior.

Repeated repair behavior

Once Agent:

  1. receives the rule before generation,
  2. violates it,
  3. receives deterministic gate output identifying the violation,
  4. explicitly acknowledges that it should not have happened,
  5. and repairs it,

I would expect substantially higher compliance with that same rule during subsequent work.

Instead, I repeatedly observe the same violation classes being reintroduced.


Screenshots / Screen Recordings

I am attaching two screenshots from an actual Agent run.

The screenshots show Agent:

  1. explicitly acknowledging that the reported violations were real and should not have reached the next implementation slice;
  2. fixing those violations;
  3. running Ruff again;
  4. encountering a Behave failure caused by an incorrect helper import introduced during implementation;
  5. fixing that;
  6. running additional tests;
  7. subsequently hitting structural MODULE_SIZE violations;
  8. starting yet another refactoring pass, all within the same original request.

I can additionally provide:

  • complete Agent conversation logs;
  • the original effective prompts;
  • repository hard-rule definitions;
  • diffs produced before each repair;
  • Ruff output;
  • [MODULE_SIZE] audit output;
  • pre-commit output;
  • repeated independent occurrences;
  • additional Request IDs if needed.

Operating System

Linux

Linux x64
Kernel: 6.8.0-138-generic

Ubuntu 24.04.


Version Information

Cursor IDE:

Version: 3.17.19
VS Code Extension API: 1.128.0
Commit: ae3a2b7231dd56194447fe4570dfdc61640b1e90
Date: 2026-08-24T06:42:14.583Z
Layout: IDE
Build Type: Stable
Release Track: Default
Electron: 40.10.3
Chromium: 144.0.7559.236
Node.js: 24.15.0
V8: 14.4.258.32-electron.0
xterm.js: 6.1.0-beta.291
OS: Linux x64 6.8.0-138-generic

For AI issues: which model did you use?

Auto

The behavior is not limited to a single implementation task; it has been repeatedly observed across Agent work.


For AI issues: add Request ID with privacy disabled

Request ID: c8051450-2e83-4f95-aeaa-957a2f277262

I can provide additional Request IDs from independent occurrences if useful.


Additional Information

The distinction between ordinary implementation errors and the failures reported here is important.

A business-logic test failure can reveal behavior that required implementation and execution to discover.

The four recurring violations in this report are different:

[MODULE_SIZE] module physical LOC
[MODULE_SIZE] module logical LOC
PLR2004
TC001

They are static or architectural constraints that:

  • are explicitly defined before implementation;
  • are deterministic;
  • are repeatedly supplied to Agent;
  • can be evaluated without discovering new runtime business behavior;
  • are detected by automated repository gates;
  • and repeatedly require semantic repair after the initial implementation.

In particular, PLR2004 and TC001 are not automatically fixed by Ruff in this workflow, and MODULE_SIZE necessarily requires a semantic architectural/refactoring decision.

Therefore these recurring failures create additional Agent work rather than being removable by a simple formatter pass.

Why this matters for usage-based Agent workflows

In an autonomous workflow, a request may become:

initial implementation
→ static violation
→ Agent repair
→ another violation
→ Agent repair
→ structural violation
→ Agent refactor
→ more validation

All of this can happen during a single original user request.

This makes request cost materially dependent on Agent repeatedly repairing violations of constraints that were already present before code generation.

Again, I am not claiming Agent should never make mistakes.

The issue is that the same known constraints are violated with extremely high frequency and continue recurring even after Agent has explicitly acknowledged and repaired those exact classes of failures.

Questions / areas that may help investigate

I would appreciate the Cursor team investigating:

  1. Are repository instructions such as AGENTS.md actually present with sufficient priority in the effective Agent context throughout a long implementation request?

  2. Can Agent lose or de-prioritize repository hard rules after several tool calls / implementation slices inside one request?

  3. Why does explicit acknowledgement and repair of a deterministic rule not materially improve compliance with the same rule later in the same Agent workflow?

  4. Does Agent perform any lint/static-quality planning or review of its generated patch before proceeding to the next implementation slice?

  5. For module-size limits, does Agent consider the current module size before deciding to append new responsibilities to an existing module?

  6. Why are Ruff PLR2004 and TC001 repeatedly introduced when Ruff compliance is explicitly required before implementation and completion?

  7. Could deterministic quality failures be checked earlier in the Agent loop, before Agent proceeds with additional implementation work?

  8. Is there a known issue with instruction persistence/context priority during long Agent sessions?

I can provide full logs and diffs if an engineer wants a reproducible trace.


Does this stop you from using Cursor?

Sometimes - I can sometimes use Cursor.

Cursor remains usable, but this issue significantly reduces the reliability and cost-effectiveness of autonomous Agent workflows because non-trivial requests repeatedly enter avoidable self-repair cycles.

Hi there!

We detected that this may be a bug report, so we’ve moved your post to the Bug Reports category.

To help us investigate and fix this faster, could you edit your original post to include the details from the template below?

Bug Report Template - Click to expand

Where does the bug appear (feature/product)?

  • Editor, Tab & Chat (autocomplete, Composer, in-editor agent)
  • Terminal & commands
  • Models, pricing & API keys (availability, Auto/Max, BYOK/Bedrock)
  • MCP & tools
  • Cloud Agents & Automations (cursor.com/agents, scheduled/event)
  • BugBot & Code Review
  • Cursor CLI
  • Cursor Mobile
  • Remote (SSH / Dev Containers / WSL)
  • Account, billing & login
  • Something else…

Describe the Bug
A clear and concise description of what the bug is.


Steps to Reproduce
How can you reproduce this bug? We have a much better chance at fixing issues if we can reproduce them!


Expected Behavior
What is meant to happen here that isn’t working correctly?


Screenshots / Screen Recordings
If applicable, attach images or videos (.jpg, .png, .gif, .mp4, .mov)


Operating System

  • Windows 10/11
  • MacOS
  • Linux

Version Information

  • For Cursor IDE: Menu → About Cursor → Copy
  • For Cursor CLI: Run agent about in your terminal
IDE:
Version: 2.xx.x
VSCode Version: 1.105.1
Commit: ......

CLI:
CLI Version 2026.01.17-d239e66

For AI issues: which model did you use?
Model name (e.g., Sonnet 4, Tab…)


For AI issues: add Request ID with privacy disabled
Request ID: f9a7046a-279b-47e5-ab48-6e8dc12daba1
For Background Agent issues, also post the ID: bc-…


Additional Information
Add any other context about the problem here.


Does this stop you from using Cursor?

  • Yes - Cursor is unusable
  • Sometimes - I can sometimes use Cursor
  • No - Cursor works, but with this issue

The more details you provide, the easier it is for us to reproduce and fix the issue. Thanks!

Hey, thanks for the very detailed report and the request ID. With this level of detail, it’s a lot easier to investigate.

I checked the run you linked. On the infrastructure side everything worked normally, the turn finished without errors, and the rules from AGENTS.md really were in context, the agent even acknowledges them in the transcript. So this is not a rules loading issue. The issue is how the rules get applied. Rules and AGENTS.md are injected into the model prompt as strong guidance, but they are not fail-closed gates. The model is asked to follow them, but compliance is probabilistic and can degrade in long sessions with lots of tool calls, like the repair loops you described.

What actually helps in this scenario:

  1. The session was running on Auto, which often switches to faster models. For strict deterministic constraints like your LOC caps and Ruff contract, pin a stronger reasoning model manually. First-pass compliance usually improves a lot.

  2. For constraints that must not be violated, take a look at Hooks: Hooks | Cursor Docs. A hook on afterFileEdit can run your Ruff and module-size audit after every file edit and block the patch deterministically. That means violations are caught at generation time, not at the end of a slice. This is enforcement, not guidance, which is what you want for deterministic rules like PLR2004, TC001, and [MODULE_SIZE].

  3. Keep must-obey constraints short and put them in Always Apply (or in AGENTS.md), instead of spreading them across a bunch of long docs. Long rules dilute the model’s attention. For bigger tasks, it also helps to start a fresh session for each slice.

We’re tracking first-pass compliance with explicit constraints and working on improvements, so I’ve shared your report with the team as a solid detailed example. If there’s an update, I’ll reply here. Any extra request IDs and logs you offered would also help, feel free to add them to the thread.

It was running on auto since I run out of credits frequently because of this bug, cursor violates everything and hsas to reprocess again and again, wasting a lot of time and all the resources. AGENTS.md grew because I had to add many rules that the agent should know, like basic coding standards, but no matter what I put it keeps violating most of the rules and giving almost all responses with errors and bad code.

Hey, thanks for clarifying the details about Auto and AGENTS.md. That’s important.

About the bloated AGENTS.md, it can work against you. Every always-injected rule gets added to context on every turn, and the bigger the file is, the more the model’s attention gets diluted. In practice, the key constraints get buried under the rest. In very long sessions like your repair cycles, you also get summarization, which can drop some instructions. So adding more rules often backfires.

What actually helps:

  1. Cut AGENTS.md down to the must-obey minimum. Keep only hard, deterministic constraints like MODULE_SIZE caps, PLR2004, TC001. Move everything else into separate rules that get pulled in only when relevant, not always. There’s a useful practical breakdown with measurements here: Trim your `.cursor/rules/` token load by 32% — shorthand dictionary + backbone-doc pattern (measured, 57 files)

  2. Hooks are what will actually solve the credit problem. A hook on afterFileEdit Hooks | Cursor Docs can run your Ruff and module-size audit after every edit and deterministically block the patch. Then violations get caught during generation, not at the end of a slice, and the model doesn’t have to redo everything in a loop. That’s enforcement, not guidance, which is what you want for deterministic rules.

  3. About Auto and credits. I get the logic, Auto is cheaper so you use it. But repair cycles are what really burn resources. For slices with strict constraints, pinning a stronger reasoning model usually boosts first-pass compliance a lot, which means fewer redo passes and less total spend. Also, on bigger tasks it helps to start a fresh session per slice so context doesn’t balloon.

As for why acknowledge plus repair doesn’t improve compliance further in the same session, that’s a result of the probabilistic nature of the model and the degradation in long runs I mentioned above. In practice, the combo of short AGENTS.md, Hooks, and a stronger model for strict slices gives the biggest improvement.

If you try Hooks and you see Chat context summarized flashing during repair cycles, tell me. That’s a separate thing I should pass to the team with details.

Thanks, this confirms one of the most important points for me: the rules were actually in context, so this was not an AGENTS.md loading problem.

I will test afterFileEdit hooks and reduce the always-loaded context as suggested.

However, I don’t think hooks fully solve the credit issue. They can detect the violation earlier and prevent the Agent from building more work on top of an invalid edit, which is definitely useful, but the model has already generated the violating edit. For MODULE_SIZE, PLR2004, and TC001, the repair is semantic and normally requires additional Agent reasoning/generation.

So the flow still becomes:


model generates known-rule violation
→ hook catches it immediately
→ model must repair it
→ additional model work/usage

That is much better than discovering it at the end of a long slice, but it does not address the underlying >95% first-pass violation rate I am reporting.

What I would really like to understand is whether Cursor considers that recurrence rate expected when the rule has been confirmed to be in context, or whether this is considered a model/Agent quality issue that is expected to improve.

I’ll also try a pinned reasoning model so I can compare:

  • first-pass compliance on Auto;
  • first-pass compliance on a pinned stronger model;
  • number of repair cycles;
  • total usage required to reach the same GREEN result.

I’ll report the results here.

One more thing: if afterFileEdit rejects an edit because Ruff or MODULE_SIZE fails, does Cursor guarantee that this rejection immediately becomes feedback to the same Agent and prevents it from continuing with dependent edits, or does it only report a hook failure? That distinction matters a lot for whether this actually reduces repair-loop usage.

This happens because un-scoped rules with universal globs: **/* get treated as ambient noise once the context window fills with conversation tokens.

Two fixes solved this completely for our Python services:

  1. Scope the rule specifically: Use globs: **/services/**/*.py or **/routes/**/*.py instead of global globs. This forces Cursor to re-inject the hard rule only when touching those files.
  2. Provide a minimal contrast snippet: Inside the .mdc rule, include a 4-line // BAD vs // GOOD example of your interface contract. The agent anchors on syntax examples 10x better than abstract prose constraints.

You can grab our open-source Python & FastAPI deterministic rules on GitHub: AymaneWebDEV/developer-prompt-vault