DEV Community

Cover image for How to stop AI coding assistant from forgetting my project rules across sessions?
Edward Izgorodin
Edward Izgorodin

Posted on Originally published at mnemoverse.com

How to stop AI coding assistant from forgetting my project rules across sessions?

Put each rule in the instruction file that your assistant loads by itself, keep that file short, confirm at the start of a session that it loaded, and move any rule that must hold every time out of the file into a hook or a deny rule. Claude Code reads CLAUDE.md, Codex reads AGENTS.md, Cursor reads rules in .cursor/rules, GitHub Copilot reads .github/copilot-instructions.md, and Gemini CLI reads GEMINI.md. Each of them puts the text of the file in front of the model, and Anthropic states the limit for its own tool in the Claude Code memory documentation: "Claude treats CLAUDE.md files as context, not enforced configuration, so how you write instructions affects how reliably Claude follows them."

A rule that seems forgotten failed at one of three points, and each point has its own fix.

TL;DR

  • Not loaded. In Claude Code, Cursor, GitHub Copilot and Gemini CLI, a rule scoped to a path or a subdirectory applies only when the assistant works with a matching file. In Claude Code, compaction summarizes such rules away until Claude next reads, writes or edits a matching file, and an instruction given only in chat may not survive compaction. Keep rules that must always apply unscoped, in the file at the project root, and start a new session after you edit it.
  • Diluted. Anthropic's target is under 200 lines per CLAUDE.md, and Cursor's is under 500 lines per rule. Past a hard cap the miss is the first one: Codex stops adding AGENTS.md files once their combined size reaches 32 KiB by default.
  • Not obeyed. Anthropic and GitHub both say that instructions do not guarantee compliance. Anthropic's advice for Claude Code: "If something has to happen every time, make it a hook, a deny rule, or a managed setting."
  • Check before rewording. /context all in Claude Code, /memory show in Gemini CLI, the list of references on a Copilot Chat response, a TUI log of the instruction files Codex loaded, and the list of rules with their status in Cursor's Customize.

Mnemoverse (the author's company) makes a memory server for AI agents; nothing below describes or tests it.

Why does a coding assistant forget a project rule between sessions?

A project rule is an instruction kept in a file that the coding assistant adds to the model's context by itself, without being asked in the chat.

The model carries nothing from one session to the next. Cursor's rules documentation: "Large language models don't retain memory between completions." Anthropic: "Each Claude Code session begins with a fresh context window." The file is what carries a rule into the next session, so a rule that seems forgotten failed in one of three ways.

Miss What happened What fixes it First check
Not loaded The rule was not in this session's context: wrong file or folder, a path scope that did not match, lost in compaction, or edited after the session started Rules that must always apply go unscoped into the always-loaded file at the project root; a new session after an edit The tool's own view of loaded instructions
Diluted The rule was in context among too much other text, or beside a rule that contradicts it A shorter file, rules split by path, contradictions removed The file's size against the vendor's guidance
Not obeyed The rule was in context and the model decided otherwise A hook, a deny rule or a managed setting, where the tool has one Whether the rule must hold every time or is a guideline

Sergei Parfenov, in a dev.to comment of 14 September 2026, gave the reason to keep the misses apart:

I'd still record whether the constraint reached the model, because "never retrieved it" and "received it but ignored it" need different fixes.

Anthropic covers the second and the third in one sentence, for Claude Code, in its best practices: "If Claude keeps ignoring a line that is in CLAUDE.md, adding IMPORTANT probably won't fix it. Either the file has grown long enough that the line gets lost, or the line is a rule that can't have exceptions, in which case it belongs in a hook." For the other four tools, this article assembles the three misses from separate lines of their documentation.

Where does each assistant read its rules, and when?

Claude Code Codex Cursor GitHub Copilot Gemini CLI
Rules file CLAUDE.md; rules in .claude/rules/ AGENTS.md .mdc files in .cursor/rules .github/copilot-instructions.md; path-specific instructions GEMINI.md
When it loads Files above the working directory at launch; subdirectory files and paths: rules on demand When Codex starts: once per run, usually once per TUI session Always Apply: every chat session; other types by description, file pattern or @-mention Added to requests automatically, with every chat message With every prompt; more files when a tool accesses a directory
Size guidance Target under 200 lines per file Stops adding files at 32 KiB combined, by default Keep rules under 500 lines Short, self-contained statements not covered here
Check that it loaded /context all, list under Memory files TUI log of the instruction files it loaded; or ask it to summarize the current instructions Customize shows all rules and their status List of references on a chat response /memory show; count in the footer
Beyond instructions Hooks, deny rules, managed settings Hooks, "not a complete enforcement boundary"; command rules, experimental Hooks, fail-open by default Hooks, depending on the surface Hooks, such as BeforeTool

Sources: Claude Code memory and best practices; Codex AGENTS.md and hooks; Cursor rules and hooks; Copilot repository instructions, custom instructions and comparing customizations; Gemini CLI GEMINI.md and hooks. "Not covered here" means this article quotes nothing on that point for that tool, not that the tool lacks it.

One file does not reach every tool. Claude Code: "By default, Claude reads AGENTS.md only when you have no CLAUDE.md in your working directory or above it." Its own troubleshooting line: "If your repository has an AGENTS.md and Claude doesn't seem to know what it says, the usual cause is a CLAUDE.md somewhere on the project path." Copilot reads AGENTS.md too: "When Copilot is working, the nearest AGENTS.md file in the directory tree will take precedence." It accepts the other two names as well: "Alternatively, you can use a single CLAUDE.md or GEMINI.md file stored in the root of the repository." Codex goes by file name, with a list you can extend: "If your repository already uses a different filename (for example TEAM_GUIDE.md), add it to the fallback list so Codex treats it like an instructions file." And: "Filenames not on this list are ignored for instruction discovery." Gemini CLI: "While GEMINI.md is the default filename, you can configure this in your settings.json file." A team that uses several assistants checks each tool's view of what it loaded instead of assuming that one file serves all of them.

Why did the rule not load in this session?

Claude Code loads in two waves: "CLAUDE.md and CLAUDE.local.md files in the directory hierarchy above the working directory are loaded at launch. Files in subdirectories load on demand." Rules follow the same split: "Rules without paths frontmatter are loaded at launch with the same priority as .claude/CLAUDE.md", while "A path-scoped rule loads when Claude uses the Read, Write, or Edit tool on a matching file."

Compaction is the step in which the assistant replaces earlier conversation with a summary to free context. Claude Code "compacts automatically as you approach the limit", and compaction treats the two waves differently (context window): "Path-scoped rules and nested CLAUDE.md files load into message history when Claude reads, writes, or edits their trigger file, so compaction summarizes them away with everything else." For both, the same page's table of what survives compaction says "Claude Code reloads them on demand", so they return when Claude next touches a matching file. The root file comes back: "Project-root CLAUDE.md survives compaction: after /compact, Claude re-reads it from disk and re-injects it into the session."

Anthropic lists the causes when a rule vanishes: "If an instruction disappeared after compaction, it was given only in conversation, lives in a nested CLAUDE.md that hasn't reloaded yet, or is a path-scoped rule that hasn't matched a file since." The fix: "If a rule must persist across compaction, drop the paths: frontmatter or move it to the project-root CLAUDE.md." For context that has to return after every compaction, the hooks guide: "Use a SessionStart hook with a compact matcher to re-inject critical context after every compaction."

An edit to the project-root or user-level CLAUDE.md made during a session does not apply right away. The prompt caching page says of those files: "Editing them mid-session does not invalidate the cache, but the edit also doesn't apply." And: "The new content loads on the next /clear, /compact, or restart."

Two places a rule does not reach. Worktrees: "If you work across multiple git worktrees of the same repository, a gitignored CLAUDE.local.md only exists in the worktree where you created it." Cloud sessions, from the glossary: they "start from a fresh clone of your repository and don't read ~/.claude/ on your machine." A personal rule in ~/.claude/ stays on the machine; a rule committed to the repository travels with the clone.

Codex "builds an instruction chain when it starts (once per run; in the TUI this usually means once per launched session)." The search has an end: "Codex stops searching once it reaches your current directory, so place overrides as close to specialized work as possible." For an edit that seems ignored: "If instructions look stale, restart Codex in the target directory." On compaction, the commands page says Codex "replaces earlier turns with a concise summary, freeing context while keeping critical details"; what that summary keeps is not covered here. Its hooks can run after it: "After Codex compacts a root session, SessionStart hooks that match source: "compact" run before the next model request."

Cursor applies a rule by its type: "If alwaysApply is true, the rule will be applied to every chat session. Otherwise, the description of the rule will be presented to the Cursor Agent to decide if it should be applied." The other types apply when a file matches a pattern or when the rule is @-mentioned in chat. Two quiet failures. A plain Markdown file: "A plain .md file in .cursor/rules is ignored by the rules system because it has no frontmatter to specify description, globs, and alwaysApply." And a file that a rule only mentions: "The file's contents are not inlined into the prompt, and this is the same in the editor, the CLI, and Cloud Agents. Put anything that must always be in context directly in the rule body."

GitHub Copilot adds repository-wide instructions on its own: "Instructions are automatically added to requests that you submit to Copilot." Path-specific instructions depend on where Copilot runs: "Currently, on GitHub.com, path-specific custom instructions are only supported for Copilot cloud agent and Copilot code review." The concept page adds: "For example, an environment may support path-specific instructions for one task but not another." Code review reads the branch under review: "When reviewing a pull request, Copilot reads repository custom instructions, agent instructions, and agent skills from the head branch (the branch with your changes), not the base branch." A rule added to the base branch reaches that review only once the branch contains it.

Gemini CLI "concatenates the contents of all found files, and sends them to the model with every prompt." More files join as the agent works: "When a tool accesses a file or directory, the CLI automatically scans for GEMINI.md files in that directory and its ancestors up to a trusted root." After an edit, /memory reload "Forces a re-scan and reload of all GEMINI.md files from all configured locations."

Is the rules file too long?

Size works in two ways: past a hard cap, a file is cut or not added at all; below the cap, a long file still dilutes each line.

The caps. Codex: "Codex skips empty files and stops adding files once the combined size reaches the limit defined by project_doc_max_bytes (32 KiB by default)." Its troubleshooting line: "Instructions truncated: Raise project_doc_max_bytes or split large files across nested directories to keep critical guidance intact." Claude Code: "Claude Code skips a file over 4 MiB and loads none of it." For files that load on demand: "When a subdirectory CLAUDE.md or a rules file that loads on demand is over a per-file size limit, Claude receives only the start of it."

The guidance. Anthropic: "target under 200 lines per CLAUDE.md file. Longer files consume more context and reduce adherence." The 200 is a target, not a cutoff: "Claude gets the whole of each CLAUDE.md file that loads at launch, as long as the file is 4 MiB or smaller." The load limit of the first 200 lines or 25KB in the same documentation is for auto memory's index, and Anthropic says so: "This limit applies only to MEMORY.md."

Why length matters, from Anthropic's best practices: "Claude Code loads CLAUDE.md into every session, which means every line in it takes a little of Claude's attention on every task, whether it's relevant or not." Splitting a file into imports does not help: "Imports help you organize a long file but don't reduce its context cost, because imported files load together with the CLAUDE.md that imports them." Path-scoped rules do cut what loads at launch, at the price of the loading and compaction behavior above.

Cursor: "Keep rules under 500 lines" and "Split large rules into multiple, composable rules". GitHub: "Custom instructions consist of natural language instructions and are most effective when they are short, self-contained statements." Among its cases against custom instructions: "The instructions are so detailed that they distract from the immediate task."

Artjoms Stukans, in a dev.to comment of 27 August 2026, described the same limit from use: "Always loaded rules file works for me too, but it has own ceiling, when file grows the model starts to skim it." Anthropic's article on context engineering says it of context in general, not of rules files: "Context, therefore, must be treated as a finite resource with diminishing marginal returns."

Contradictions dilute in a different way. Anthropic: "if two instructions contradict each other, Claude may pick one arbitrarily." And: "Check whether your instruction competes with guidance Claude Code adds on its own." Each tool resolves a conflict by its own order. Cursor: "All applicable rules are merged; earlier sources take precedence when guidance conflicts." Codex: "Files closer to your current directory override earlier guidance because they appear later in the combined prompt."

Why does the model ignore a rule it can see?

Because the file is context, not a control. Claude Code delivers it as a message: "CLAUDE.md content is delivered as a user message after the system prompt, not as part of the system prompt itself." What follows from that: "Claude reads it and tries to follow it, but there's no guarantee of strict compliance, especially for vague or conflicting instructions." Stronger wording does not change it: "But no matter how strongly you word it, whether Claude follows that line on a given turn is still Claude's call." Anthropic's own example: "A line like Always typecheck before you finish in this file works most of the time, not every time."

GitHub says the same of Copilot in its custom instructions concept page: "Due to the non-deterministic nature of AI, Copilot may not always follow your custom instructions in exactly the same way every time they are used." And on comparing customizations: "Instructions guide the model, but do not guarantee that it will follow every rule."

For Codex, Cursor and Gemini CLI, this article quotes how rules load and what hooks do, not a statement on compliance. Wording still helps at the margin, in Anthropic's words: "The more specific and concise your instructions, the more consistently Claude follows them."

What makes a rule hold every time?

A hook is a command or script that the assistant itself runs at a defined event, such as before a tool call.

A step outside the model's decision. Anthropic: "If something has to happen every time, make it a hook, a deny rule, or a managed setting. CLAUDE.md is for guidelines, and Claude is allowed to decide a guideline doesn't apply." To block an action: "To block an action regardless of what Claude decides, use a PreToolUse hook instead." For settings: "Settings rules are enforced by the client regardless of what Claude decides to do." With two limits: "A prompt or agent hook asks another model to decide, so it isn't deterministic either." And: "For real enforcement, use a command or http hook, and add onFailure: "block" if the action should also be stopped when the hook itself crashes or times out."

Each of the other four documents hooks with its own caveat:

Tool What its hooks can do The vendor's caveat
Codex Block: "You can also use exit code 2 and write the blocking reason to stderr." "Treat tool hooks as a useful guardrail, not a complete enforcement boundary."
Cursor Hooks "can observe, block, or modify behavior"; exit code 2 means "Block the action" Other exit codes: "Hook failed, action proceeds (fail-open by default)"; the failClosed field turns failures into blocks
GitHub Copilot "hooks execute code at defined events" "Supported events and controls depend on the surface."
Gemini CLI "Validate actions: Review tool arguments and block potentially dangerous operations." A risk rather than a limit: "Hooks execute arbitrary code with your user privileges."

Codex also has rules of another kind, for commands rather than instructions: "Use rules to control which commands Codex can run outside the sandbox." They carry a warning: "Rules are experimental and may change."

This article's reading: a hook fits a rule that a command can check at a fixed point, such as a forbidden command or a check that must pass before a task ends; a rule about style or judgment stays in the file as a guideline.

How do you check that a rule reached the model?

Before rewording a rule, confirm that it was in context. Each tool has its own view:

  • Claude Code: "To confirm the file loaded, run /context all in a session and check the list under Memory files." And: "If one is missing there, Claude can't see it." For a record over time: "Use the InstructionsLoaded hook to log which CLAUDE.md and rules files are loaded, when they load, and why."
  • Codex: "To audit which instruction files Codex loaded, opt into a plaintext TUI log with codex -c log_dir=./.codex-log and check ./.codex-log/codex-tui.log, or inspect the most recent session-*.jsonl file if you enabled session logging." The same page gives the command codex --ask-for-approval never "Summarize the current instructions." and the expected result for the global file: "Expected: Codex quotes the items from ~/.codex/AGENTS.md before proposing work."
  • GitHub Copilot: "To find out whether repository custom instructions were used, expand the list of references at the top of a chat response in the Chat panel and check whether the .github/copilot-instructions.md file is listed."
  • Gemini CLI: /memory show "Displays the full, concatenated content of the current hierarchical memory." And: "The CLI footer displays the number of loaded context files, which gives you a quick visual cue of the active instructional context."
  • Cursor: "From Customize you can see all rules and their status." A view of what one chat applied is not covered here.

A view of loaded files shows delivery, not obedience. Zira, in a dev.to comment of 17 September 2026 on loading rules in stages: "progressive disclosure needs evidence that the intended context actually loaded." Her method: "In practice I'd log a context manifest per turn (source path or skill, reason, version or hash, and token estimate) and attach it to the tool or action trace." Her test: "Then test a small canary matrix: a task that should load a rule, a task that must not load it, and a cross-boundary task that should retrieve it explicitly." What it catches: "Otherwise a lean root can look healthy while silently omitting the payment rule, or loading two conflicting ones." And its limit: "Progressive disclosure is a loading strategy, not proof that the loaded rules were sufficient or obeyed." Parfenov adds a control: "Then add a task where the constraint should not apply, so repeating every remembered rule does not look like success."

Put together, a check for one rule:

  1. Start a new session and confirm in the tool's own view that the file is loaded.
  2. Run a task where the rule applies and a task where it must not apply. For a rule scoped to a path, run the first task once more after compaction.
  3. If the file was loaded and the rule was still broken, the miss is the second or the third: shorten the file and remove contradictions, and if the rule must hold every time, move it to a hook or a deny rule.

A two-minute test of whether an agent is reading a rules file or obeying it is on the library page Why does my code editor AI keep overriding custom repository guidelines every session?

Should the assistant's own memory hold project rules?

Not for rules that must apply. Several assistants write their own memory, and their documentation keeps it apart from rules. Codex, on memories: "Keep required team guidance in AGENTS.md or checked-in documentation." And: "Treat memories as a helpful recall layer, not as the only source for rules that must always apply." GitHub on Copilot Memory: "Copilot creates memories itself, as a byproduct of working with you." And: "Because this is a judgment Copilot makes, rather than a guarantee enforced by the system, a stored fact should not be relied on as a rule that will always be followed. To provide instructions consistently, use custom instructions instead." Claude Code loads the first 200 lines or 25KB of its auto memory index, MEMORY.md, in each session, a cap that a CLAUDE.md loaded at launch does not have: "Content beyond that threshold is not loaded at session start."

A note being written is not the same as a note being read. Lutz Leonhardt tested Cursor's Projects beta and reported on the Cursor forum on 25 September 2026, with his setup stated as "Model on Auto, Pro plan, no rules, skills or custom prompts." His count: "The Project Notes, a short index of the current work with an archive for finished items, were written 111 times and explicitly read once." Those are notes the tool kept, in a setup without any rules file, so the count says nothing about rules files; it says that what an assistant writes down is not thereby read.

What this article does not claim

No measurement of any assistant and no figure for how often any of them follows a rule. The numbers above are vendor guidance and limits (200 lines, 500 lines, 32 KiB, 4 MiB) and one forum post's count, with its setup beside it. A cell or line that says "not covered here" means this article quotes nothing on that point for that tool, not that the tool lacks it. Hooks are quoted with each vendor's own caveats; no hook was run for this article. The check for one rule is a proposal, not any team's procedure.


Sources and method. Every quotation was read on 3 November 2026 with two instruments, a browser-like request, in several cases on the Markdown or raw version of the page, and a reader service with its cache off; the dev.to comments and the Cursor forum post were read a third time through the dev.to API and the forum's own JSON. A made-up address on each host answered 404 as a control; on the Anthropic site the reader service gave no 404 mark, so the one quotation from that site counts only as an exact match. The Claude Code memory page changed after that reading and was read again on 4 November 2026: it now names /context all, and the quotation and the table use that wording. Every quotation and every vendor fact was read again on 14 November 2026 with the same instruments, and none had changed. The text describes those pages as of those dates. The Mnemoverse documentation library answers the same question for Claude Code among the common questions of How to give Claude Code persistent context across separate terminal sessions?

Edward Izgorodin · Mnemoverse · 2026-11-03

Top comments (0)