DEV Community

Eliran Kotzero
Eliran Kotzero

Posted on Originally published at kitquarry.com

Memory in Claude Code, Cursor and Codex: see it, fix it, turn it off

Originally published on KitQuarry. Written by Eliran Kotzero for KitQuarry.

In short: Claude Code's auto memory is on by default and writes plain markdown to
~/.claude/projects/<project>/memory/; open it with /memory, edit or delete any file, and
keep MEMORY.md under 200 lines. Codex memories are off until you turn them on, are generated in the
background under ~/.codex/, and are controlled with /memories and config.toml
rather than by hand-editing. Cursor removed its Memories feature in 2.1: the editor agent now knows what your rules
and AGENTS.md say. Anything that must always apply belongs in an instruction file, not in memory.

This page compares what each tool remembers between sessions, checked against official docs on 2026-11-12, and ends
with a small read-only script that audits the memory files on your machine. We ran that script against test fixtures
and parsed the config snippets below; we did not inspect a real Claude Code or Codex memory store for this page.

Side by side

Claude Code Cursor Codex
Agent-written memory Auto memory Removed from the editor in 2.1. Automations and Projects (Cloud Agents) keep their own notes Memories
On by default? Yes, in local sessions Automation memories: yes No
Where it lives ~/.claude/projects/<project>/memory/, one per git repo Cursor's cloud (Automations: MEMORIES.md per automation) ~/.codex/memories/ or memories_v2/
What loads at session start First 200 lines or 25KB of MEMORY.md; topic files on demand Rules and AGENTS.md Existing memories, unless use_memories = false
See and edit /memory, then any editor Automation tool configuration UI Inspect files; docs say not to hand-edit as the main control
Turn off /memory toggle, autoMemoryEnabled, CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 Automations: disable Memories /memories per chat, config.toml, desktop Settings
Reset everything Delete the memory folder's files Delete memory files in the automation UI Desktop app: Delete Codex memories

Claude Code: auto memory

Claude Code has two memory systems. CLAUDE.md files are instructions you write. Auto memory is notes
Claude writes for itself from your corrections and preferences. Both load at the start of every conversation, and the
docs are explicit that Claude treats both as context, not enforced configuration: to block an action whatever Claude
decides, use a PreToolUse hook.

What it saves

Claude records each note with a type in its frontmatter:

  • user: your role, expertise and working preferences
  • feedback: corrections you give and approaches you confirm
  • project: ongoing work, deadlines and decisions it can't derive from the code or git history
  • reference: where to find things outside the project, such as an issue tracker or dashboard

It skips anything it can derive from the codebase (architecture, file paths, debugging fixes) and anything your
CLAUDE.md already says, and it doesn't save something every session. Messages like Saved 2
memories
or Recalled 2 memories mean it is writing to or reading from the memory folder. When it writes a
file that starts with YAML frontmatter, Claude Code stamps a modified field with an ISO 8601 timestamp,
so you can see how old a fact is.

Asking Claude to “remember that the API tests need a local Redis” saves it to auto memory. If you want
it in CLAUDE.md instead, say “add this to CLAUDE.md”.

Where it lives and what loads

~/.claude/projects/<project>/memory/
├── MEMORY.md            # index, one line per memory, loaded into every session
├── user_role.md         # one memory
└── feedback_testing.md  # another
Enter fullscreen mode Exit fullscreen mode

The <project> name is derived from the git repository, so all worktrees and subfolders of one repo
share one memory directory (outside a git repo, the project root is used). The folder is machine-local: nothing syncs
to another machine or a cloud session. It is also excluded from the cleanupPeriodDays sweep that deletes
old transcripts, so memories stay until you or Claude change them.

Only the first 200 lines or 25KB of MEMORY.md, whichever comes first, load at the start
of a conversation. Topic files are not loaded at startup; Claude reads them with its normal file tools when it needs
them. When a write leaves MEMORY.md near a limit, Claude Code reminds Claude to shorten it; over a limit,
the write succeeds but returns an error telling Claude to rewrite the index, because everything past the limit is
dropped on the next load. That limit applies only to MEMORY.md, not to your
CLAUDE.md files.

See, edit or delete a memory

Run /memory. It lists your CLAUDE.md and CLAUDE.local.md locations, has the auto
memory toggle, and can open the auto memory folder. Everything there is plain markdown you can read, edit or delete. To
fix a wrong memory, correct or delete its topic file and its line in MEMORY.md; to wipe a project's memory,
delete the files in its folder. Since 2.1.284 (28 September 2026), invisible characters and tags that imitate Claude
Code's own markup are neutralized in MEMORY.md and recalled notes before they reach Claude, per the
changelog, but reading the folder now and then is still the real check.

Turn it off

  • Everywhere: the toggle in /memory, which saves autoMemoryEnabled to ~/.claude/settings.json.
  • One project: put this in the project's .claude/settings.json:
{
  "autoMemoryEnabled": false
}
Enter fullscreen mode Exit fullscreen mode
  • One session: CLAUDE_CODE_DISABLE_AUTO_MEMORY=1, which takes precedence over the setting for that session, in either direction.

One catch: in a background session, or a session another Claude Code session started (for example
claude run through the Bash tool), the toggle can turn auto memory off but not back on. Run
claude directly in your terminal to turn it on again.

Move it, or give a subagent its own

autoMemoryDirectory stores auto memory elsewhere; the value must be an absolute path or start with
~/. A project's .claude/settings.json can set it too, but Claude Code only honors that under the
same workspace trust rule as hooks, since a cloned repository can ship that file.

The main conversation's auto memory isn't loaded into subagents (forks excepted). A
custom subagent can keep its own with the
memory frontmatter field: user (~/.claude/agent-memory/<name>/),
project (.claude/agent-memory/<name>/, shareable through git, the docs' recommended
default) or local (.claude/agent-memory-local/<name>/, kept out of version control).
The same 200-line / 25KB rule applies to its MEMORY.md, and turning auto memory off disables the field.

Cursor: what happened to Memories

Cursor's rules docs put it plainly: language models don't retain memory between completions, and rules provide
persistent context. The separate Memories feature is gone from the editor. In a forum reply on 25 November 2025, Cursor
staff said Memories was intentionally removed starting with version 2.1, and suggested opening the command palette,
running Export memories to save them as an .mdc file, and moving what you want to keep into
User or Project Rules.

Removing the UI did not always remove old memories from context. In a January 2026 thread, a user on 2.2 found the
agent still reporting 32 memories; staff said the removed feature “still works, just without a UI”, and the
workaround that worked in that thread was installing 2.0.77, deleting the memories in Settings, then updating again. That
was ten months ago and is a forum reply, not documentation, so treat it as a last resort.

Where Cursor keeps knowledge today:

  • Project rules in .cursor/rules. Type /create-rule in Agent and describe the rule; it writes the file with frontmatter. That is the closest thing to “remember this”. If a rule doesn't seem to load, see Cursor rules not applying.
  • User Rules in Customize → Rules, for preferences across all projects.
  • AGENTS.md in the project root and subfolders.
  • Automations (Cloud Agents): Memories are on by default and let the agent read and write notes across runs of the same automation, as a named entry (MEMORIES.md by default) outside its working filesystem. You can view, edit and delete them in the tool configuration UI. Cursor warns that untrusted input can lead to misleading or malicious memories that affect later runs.
  • Projects (Cloud Agents, so plans that include them): a set of shared-context files that sync across every machine the Project's agents use, where agents add what they learn about the codebase and how you like work done.

Codex: memories

Local Codex memories are off by default. Turn them on in the ChatGPT desktop app under
Settings > Personalization > Enable Codex memories, or in config.toml:

# ~/.codex/config.toml
[features]
memories = true                     # off by default

[memories]
use_memories = true                 # inject existing memories into new sessions (default true)
generate_memories = true            # let new chats become memory inputs (default true)
disable_on_external_context = true  # keep chats that used MCP tools, web search or tool search out (default false)
Enter fullscreen mode Exit fullscreen mode

Once enabled, Codex turns useful context from eligible earlier chats into local memory files. It skips active or
short-lived sessions, redacts secrets from generated memory fields, and works in the background: a chat has to be idle
for a while first (memories.min_rollout_idle_hours, default 6), and a pass can be skipped when your
remaining rate limit is below memories.min_rate_limit_remaining_percent (default 25). So don't expect a
memory the moment a chat ends. The IDE extension uses the connected Codex host's memory store.

Where the files are

Under your Codex home (~/.codex, or $CODEX_HOME). A fresh home with memories enabled uses
memories_v2/; if memories/ already exists, the CLI keeps using it. memories.version
(v1 or v2) picks one explicitly. In the desktop app, check both folders: during the migration a
new chat can read from memories/ and write to both. The docs call these files generated state: inspect them
when troubleshooting or before sharing your Codex home, but don't rely on hand-editing them as your primary control.

Control it per chat and globally

  • /memories in the CLI or desktop app chooses whether the current chat can use existing memories and whether it can feed future ones. The Memories page says chat-level choices don't change global settings; the slash command reference says Codex “updates the relevant memory settings for future sessions”. If it matters, check config.toml after using it.
  • memories.use_memories = false stops injecting existing memories (default true).
  • memories.generate_memories = false stops new chats becoming memory inputs (default true).
  • memories.disable_on_external_context = true keeps chats that used MCP tools, web search or tool search out of memory generation (default false). Worth turning on if your agents read issue trackers, web pages or other text you didn't write.
  • memories.max_rollout_age_days (default 30) is the oldest a chat can be to feed memory generation, and memories.max_unused_days (default 30) makes a memory ineligible for consolidation once it has gone unused that long.

Fix a wrong memory

The docs give no command to delete a single memory. Your options are: /memories to keep a chat away from
memory, use_memories = false while a wrong memory is causing trouble, or Delete Codex
memories
in the desktop app's Settings > Personalization to reset the machine's store (it also clears Computer
History where that feature exists). Then put the correct fact somewhere authoritative. OpenAI's own advice: keep required
team guidance in AGENTS.md or checked-in docs and treat memories as a
recall layer.

Memory or instruction file?

It is… Put it in
A rule the agent must always follow (“never edit migrations”) CLAUDE.md, AGENTS.md or a Cursor rule; enforce with a hook if it really must hold
A team convention or build command The checked-in instruction file, so teammates and other tools get it
A personal preference (“explain before editing”) ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, Cursor User Rules, or let memory pick it up
A fact that changes (current staging target, this sprint's focus) Memory is fine; check it is still true
A secret Neither. See keeping agents away from .env

Memory has the same failure mode as instruction files: a fact that was true in September keeps steering the agent in
November. The fixes in stale AGENTS.md and CLAUDE.md apply here too.

Audit your memory files

agent-memory-audit.py is read-only. It finds Claude Code auto memory folders (including a custom
autoMemoryDirectory) and subagent memory, and Codex's memory settings and stores, then warns about a
MEMORY.md past the load limit, index lines pointing at missing files, topic files the index never lists,
files untouched for 30+ days, secret-looking strings, and a .claude/agent-memory-local/ folder git would
commit. It exits 1 when there are warnings. Python 3.11+.

#!/usr/bin/env python3
"""agent-memory-audit.py: read-only report on what Claude Code and Codex have saved as memory.

Usage: python3 agent-memory-audit.py [--project DIR] [--days N]
  --project  repo to check for subagent memory folders (default: current directory)
  --days     flag memory files not modified for N days (default: 30)

Checks
  Claude Code auto memory   <config>/projects/*/memory/ (config = $CLAUDE_CONFIG_DIR or ~/.claude),
                            plus any autoMemoryDirectory set in user or project settings
  Claude Code subagents     ~/.claude/agent-memory/*, .claude/agent-memory/*, .claude/agent-memory-local/*
  Codex                     [features] memories and [memories] keys in $CODEX_HOME/config.toml,
                            and the memories/ and memories_v2/ stores
Warns about: MEMORY.md over 200 lines or ~25 KB (later lines are not loaded), index lines that
point at missing files, topic files the index never names, old files, secret-looking strings,
and a .claude/agent-memory-local/ folder that git would commit. Never writes or deletes anything.
Exit code 1 if there are warnings, 0 otherwise. Needs Python 3.11+ (tomllib).
"""
import argparse, json, os, re, subprocess, sys, time, tomllib
from pathlib import Path

LINE_LIMIT, BYTE_LIMIT = 200, 25_000  # docs: "first 200 lines or 25KB"; 25,000 bytes errs on the safe side
SECRET = re.compile(r"(sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|AKIA[0-9A-Z]{16}"
                    r"|xox[abp]-[A-Za-z0-9-]{10,}|-----BEGIN [A-Z ]*PRIVATE KEY-----"
                    r"|(?i:(?:api[_-]?key|secret|password|token)\s*[:=]\s*\S{8,}))")
warnings = []

def warn(msg):
    warnings.append(msg); print(f"  WARN {msg}")

def read(p):
    try: return p.read_text(errors="replace")
    except OSError: return ""

def scan_secrets(d, fix="rotate it, then delete the line"):
    for f in sorted(d.rglob("*")):
        if f.is_file() and f.stat().st_size < 2_000_000 and SECRET.search(read(f)):
            warn(f"secret-looking string in {f} ({fix})")

def old_files(d, days):
    cutoff = time.time() - days * 86400
    old = [f for f in d.rglob("*") if f.is_file() and f.stat().st_mtime < cutoff]
    if old:
        warn(f"{len(old)} file(s) in {d} unchanged for {days}+ days; re-check them: "
             + ", ".join(f.name for f in sorted(old)[:5]) + (" ..." if len(old) > 5 else ""))

def check_index(d, days):
    idx = d / "MEMORY.md"
    topics = sorted(f for f in d.glob("*.md") if f.name != "MEMORY.md")
    print(f"- {d}  ({len(topics)} topic file(s))")
    if not idx.exists():
        if topics: warn(f"{d} has topic files but no MEMORY.md index")
        return
    text = read(idx); lines = text.count("\n") + (0 if text.endswith("\n") or not text else 1)
    size = len(text.encode())
    print(f"  MEMORY.md: {lines} lines, {size} bytes (loaded up to {LINE_LIMIT} lines / ~25 KB)")
    if lines > LINE_LIMIT or size > BYTE_LIMIT:
        warn(f"{idx} is over the load limit: anything past it is not loaded at session start")
    for name in sorted(set(re.findall(r"([\w.-]+\.md)\b", text)) - {"MEMORY.md"}):
        if not (d / name).exists(): warn(f"{idx} names {name}, which does not exist")
    for t in topics:
        if t.name not in text: warn(f"{t.name} is not listed in {idx}, the index Claude uses to find topic files")
    old_files(d, days); scan_secrets(d)

def settings_dirs(paths):
    out = []
    for s in paths:
        try: v = json.loads(read(s) or "{}").get("autoMemoryDirectory")
        except json.JSONDecodeError: warn(f"{s} is not valid JSON"); continue
        if v: out.append((Path(os.path.expanduser(v)), s))
    return out

def claude(project, days):
    cfg = Path(os.environ.get("CLAUDE_CONFIG_DIR", "~/.claude")).expanduser()
    print(f"\nClaude Code auto memory ({cfg})")
    if os.environ.get("CLAUDE_CODE_DISABLE_AUTO_MEMORY") == "1":
        print("  note: CLAUDE_CODE_DISABLE_AUTO_MEMORY=1 in this shell, so sessions started here skip auto memory")
    for s in [cfg / "settings.json", project / ".claude/settings.json", project / ".claude/settings.local.json"]:
        try:
            if json.loads(read(s) or "{}").get("autoMemoryEnabled") is False: print(f"  note: autoMemoryEnabled is false in {s}")
        except json.JSONDecodeError: pass
    dirs = sorted(p for p in (cfg / "projects").glob("*/memory") if p.is_dir())
    for d, src in settings_dirs([cfg / "settings.json", project / ".claude/settings.json", project / ".claude/settings.local.json"]):
        print(f"  autoMemoryDirectory {d} (from {src})")
        if d.is_dir(): dirs.append(d)
    if not dirs: print("  none found")
    for d in dirs: check_index(d, days)
    print("\nClaude Code subagent memory")
    found = False
    for base in [cfg / "agent-memory", project / ".claude/agent-memory", project / ".claude/agent-memory-local"]:
        for d in sorted(p for p in base.glob("*") if p.is_dir()):
            found = True; check_index(d, days)
    local = project / ".claude/agent-memory-local"
    if local.is_dir():
        r = subprocess.run(["git", "-C", str(project), "check-ignore", "-q", str(local)], capture_output=True)
        if r.returncode == 1: warn(f"{local} is not git-ignored; local subagent memory is meant to stay out of version control")
    if not found: print("  none found")

def codex(days):
    home = Path(os.environ.get("CODEX_HOME", "~/.codex")).expanduser()
    print(f"\nCodex memories ({home})")
    cfg = {}
    if (home / "config.toml").exists():
        try: cfg = tomllib.loads(read(home / "config.toml"))
        except tomllib.TOMLDecodeError as e: warn(f"{home / 'config.toml'} does not parse: {e}")
    on = cfg.get("features", {}).get("memories", False)
    m = cfg.get("memories", {})
    print(f"  features.memories = {str(on).lower()}" + ("" if "memories" in cfg.get("features", {}) else " (unset; off by default)"))
    for k in ["use_memories", "generate_memories", "disable_on_external_context", "version", "dual_write"]:
        if k in m: print(f"  memories.{k} = {json.dumps(m[k])}")
    print("  (the ChatGPT desktop app also has Settings > Personalization > Enable Codex memories)")
    for name in ["memories", "memories_v2"]:
        d = home / name
        if not d.is_dir(): continue
        files = [f for f in d.rglob("*") if f.is_file()]
        newest = max((f.stat().st_mtime for f in files), default=0)
        print(f"- {d}: {len(files)} file(s), {sum(f.stat().st_size for f in files)} bytes"
              + (f", newest {time.strftime('%Y-%m-%d', time.localtime(newest))}" if files else ""))
        old_files(d, days); scan_secrets(d, "rotate it; Codex treats these files as generated state, so reset the store rather than hand-edit")
    if not any((home / n).is_dir() for n in ["memories", "memories_v2"]): print("  no memory store found")

def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--project", default=".", type=Path); ap.add_argument("--days", default=30, type=int)
    a = ap.parse_args()
    project = a.project.resolve()
    claude(project, a.days); codex(a.days)
    print("\nCursor: no local memory store to check (Memories were removed in 2.1; use rules or AGENTS.md).")
    print(f"\n{len(warnings)} warning(s)")
    sys.exit(1 if warnings else 0)

if __name__ == "__main__":
    main()
Enter fullscreen mode Exit fullscreen mode

Run it from your repo with python3 agent-memory-audit.py --days 30. On a test fixture it printed:

Claude Code auto memory (~/.claude)
- ~/.claude/projects/<project>/memory  (3 topic file(s))
  MEMORY.md: 214 lines, 5524 bytes (loaded up to 200 lines / ~25 KB)
  WARN ~/.claude/projects/<project>/memory/MEMORY.md is over the load limit: anything past it is not loaded at session start
  WARN project_staging.md is not listed in ~/.claude/projects/<project>/memory/MEMORY.md, the index Claude uses to find topic files
  WARN 1 file(s) in ~/.claude/projects/<project>/memory unchanged for 30+ days; re-check them: project_staging.md

Claude Code subagent memory
  none found

Codex memories (~/.codex)
  features.memories = true
  memories.use_memories = true
  memories.generate_memories = true
  memories.disable_on_external_context = true
  (the ChatGPT desktop app also has Settings > Personalization > Enable Codex memories)
- ~/.codex/memories_v2: 2 file(s), 10 bytes, newest 2026-11-12

Cursor: no local memory store to check (Memories were removed in 2.1; use rules or AGENTS.md).

3 warning(s)
Enter fullscreen mode Exit fullscreen mode

A ten-minute memory check

  1. Claude Code: run /memory, open the auto memory folder, delete anything wrong or out of date, and move real rules into CLAUDE.md.
  2. Run the audit script and fix every warning, starting with secrets (rotate the key, then delete the line).
  3. Codex: decide whether you want memories at all. If yes, consider disable_on_external_context = true. If a memory is wrong, turn use_memories off or reset the store, and write the right fact into AGENTS.md.
  4. Cursor: if you still have rules exported from old Memories, read them; a one-off fact from one chat became a rule for every chat.
  5. Tell the agent when you changed its memory. The current session may still have the old fact in context.

FAQ

Where does Claude Code store its memory?

Auto memory lives in ~/.claude/projects/<project>/memory/, where <project> is derived from the git repository, so every worktree and subfolder of one repo shares one directory. It holds a MEMORY.md index plus one markdown topic file per memory. It is machine-local and not shared across machines or cloud environments. The autoMemoryDirectory setting moves it somewhere else.

How do I turn off Claude Code auto memory?

Run /memory and switch auto memory off, which writes autoMemoryEnabled: false to ~/.claude/settings.json. For one project only, put "autoMemoryEnabled": false in that project's settings. For one session, set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. Turning it off also disables the memory field on custom subagents.

Why doesn't Claude remember something it saved?

Only the first 200 lines or 25KB of MEMORY.md, whichever comes first, load at the start of a session. Anything past that is not loaded, and topic files are only read when Claude decides it needs them. Open the folder from /memory, shorten MEMORY.md to one line per entry, and make sure each topic file is listed in it.

Does Cursor still have Memories?

Not as an editor feature. A Cursor staff reply on the forum on 25 November 2025 says Memories was intentionally removed starting with version 2.1 and suggests running Export memories and moving the result into rules. Today the editor agent remembers what is in your rules and AGENTS.md. Cursor's docs describe agent-written memory only for Automations (MEMORIES.md per automation) and Projects (shared context), both on Cloud Agents.

How do I delete or reset Codex memories?

In the ChatGPT desktop app, Settings > Personalization has Delete Codex memories, which resets that machine's memory store (and also clears Computer History where that feature exists). The CLI docs list no delete command: use /memories to stop the current chat using or feeding memories, or set memories.use_memories = false or features.memories = false in config.toml. The docs call the files under ~/.codex/memories/ and memories_v2/ generated state and advise against hand-editing them as your main control.

Sources

Official docs, checked 2026-11-12.


If you want a starting point, KitQuarry's free sampler is on GitHub: ai-coding-rules-sampler. It has a short CLAUDE.md/AGENTS.md, security rules and three skills (plan-feature, review-changes, record-decisions) for Claude Code, Cursor, Codex and Windsurf. MIT, free. (I made it.)

Top comments (0)