Artificial Intelligence

Why AI forgets your rules: three different failures behind the context window

Team Nippysoft
• • 13 min read
Why AI forgets your rules: three different failures behind the context window

When people say an AI forgot a rule, they are lumping together three failures that need different fixes. This post shows how to tell them apart by symptom, what each tool keeps when the context window fills, and which control fits each failure.

  1. The text left. It is no longer sent: it was truncated, or summarized and the summary didn't keep it. The fix is a mechanism that puts it back.
  2. The text is still there, but performs worse. The context is long or noisy; position matters when locating facts. The fix is to trim the context.
  3. The text was never enforced. It is in context and the model doesn't follow it. The fix is a control outside the model.

Here the tools sit side by side, with the open source code of Codex and Gemini CLI read at a specific commit. No model was run for this post: the performance figures come from vendors or published studies.

Three failures with one name Three failures with one name 1. The text left rule summary 2. Still there, performs worse rule noise 3. Never enforced rule hook or permission

What the context window is and what fills it

Anthropic treats it as the model's working memory. Everything that travels in the conversation takes up room: messages, replies, files read and errors. The size is fixed per model, although in Claude Code some models support 1M-token windows, depending on the model and plan, and you can adjust the threshold for compaction, meaning the point where it summarizes the conversation to free space. /context shows what is using that space in Claude Code and Copilot CLI.

What happens when it fills, tool by tool

Does the oldest text always go first? No: most tools summarize rather than delete, and two APIs return an error by default without removing anything. In the source column, doc. means official documentation and code means reading the source at a pinned commit; Codex's budgets and Gemini CLI's 30% aren't in the documentation.

ToolWhen fullDoes the oldest go?What returns or staysSource
Claude API, no optionsError 400 or stopNothing leavesNot applicabledoc.
Claude API, compactionSummary of older turnsOlder turns are summarizedRecent turns, if requesteddoc.
Claude API, context editingClears tool results and, if enabled, thinking blocksYes, only that contentEverything elsedoc.
Claude CodeSummarizes the conversationAll of it is summarizedRoot CLAUDE.md and auto memory, from disk; up to 5 files read or editeddoc.
OpenAI Responses, defaultError 400Nothing leavesNot applicabledoc.
OpenAI Responses, truncation: auto (deprecated)Drops itemsYes, from the beginningThe recent partdoc.
OpenAI, server-side compactionCompressed itemEarlier context is prunedWhat follows the itemdoc.
Codex CLISummary plus recent user messagesWhatever doesn't fit the budget: 64,000 tokens with OpenAI and Azure, 20,000 with other providersRecent user messagescode, code
Gemini CLI, automaticAt 50% by default, configurable: summary plus the last 30%Older part is summarizedLast 30%; GEMINI.md with every promptcode, doc.
Gemini CLI, /compressThe documentation says it replaces everything; at the commit we read it also keeps the last 30%Depends on the sourceLast 30% in the code; GEMINI.mddoc., code
GitHub Copilot CLICompresses at 95%Not statedCustom instructions: not stateddoc.
VS Code CopilotSummarizes earlier historyEarlier history is summarizedNot stateddoc.
CursorUnconfirmedUnconfirmedUnconfirmeddoc.

Pure deletion survives in truncation: auto, marked deprecated, and in context editing, which clears tool results and thinking blocks. With a summary, your rule depends on what the summary keeps. Claude Code warns that "detailed instructions from early in the conversation may be lost", and Anthropic adds that overly aggressive compaction can lose context whose importance only shows up later.

In Codex, the code keeps user messages, newest to oldest: up to 64,000 tokens with OpenAI and Azure, and 20,000 with other providers. An early rule stays verbatim as long as it fits. There's no direct data on where a rule should sit: a 2023 study, with the models of that time, found better performance with the fact at the start or end of the context, but it measures locating information. The risk of the first message is a different one: that it stops being sent.

What comes back after compaction

A rule that has to last the whole Claude Code session belongs in the root CLAUDE.md or an unscoped rules file. In a path-scoped file or a nested CLAUDE.md, the next compaction folds it into the summary, and it stays out until Claude touches a triggering file again.

Context rot: what the evidence says and what it doesn't

The term is official in Anthropic's platform documentation: "As token count grows, accuracy and recall degrade, a phenomenon known as context rot." Its engineering article and the Opus 4.6 announcement use it too. It doesn't appear in the Claude Code documentation, and we didn't see it in the pages we read from OpenAI, Gemini CLI, GitHub and Cursor, which aren't their full documentation.

That more context performs worse is a documented trend with no general figure. Anthropic says it shows up across all models and describes it as "a performance gradient rather than a hard cliff". That is the vendor's explanation. Several things shift the effect:

  • The model. On MRCR v2, a test that hides facts ("needles") in a long text and asks for them back, with 8 needles at 1M tokens, Anthropic reports a score of 76% for Opus 4.6 and 18.5% for Sonnet 4.5.
  • The question. On a needle test, Anthropic raised Claude 2.1's score from 27% to 98% by adjusting the prompt.
  • Noise. Shi and colleagues, in 2023, concluded that "the model performance is dramatically decreased when irrelevant information is included". What they studied is noise, not length.
  • Position. Liu and colleagues, in 2023, saw performance fall when the fact sat in the middle of a long context. Anthropic recommends putting the question last and cites improvements of up to 30% in its tests.

For Claude Code, watching the limit is no longer the advice: "Most current models have a 1M-token window and compaction happens on its own, so running out is rare." Keeping the context focused still applies.

None of these sources gives a token count at which a model starts getting worse. If someone hands you one as a general rule, ask which model, task and data it came from.

When a rule stops being sent, in a simulator

This script calls no model and measures no product. It is a teaching simulation: it answers whether a piece of text is still sent word for word under the shape of each policy, never whether the model obeys it. The sizes and the 80% trigger are invented, and the summary takes no space; only the shape of each policy comes from OpenAI, Codex and Gemini CLI.

"""Simulates which text stays word for word in a conversation under documented retention policies.

No model is called. It answers "is this text still sent?", never "will the model obey it?".
Message sizes are invented; only the shape of each policy comes from vendor documentation or source.
"""
from __future__ import annotations

from dataclasses import dataclass
from functools import partial


@dataclass(frozen=True)
class Message:
    role: str
    tokens: int
    name: str = ""


RULE = "RULE"


def validate(window: int, messages: list[Message]) -> None:
    if window <= 0:
        raise ValueError("window must be positive")
    if any(message.tokens < 0 for message in messages):
        raise ValueError("token counts must not be negative")


def drop_from_start(messages: list[Message], window: int) -> list[Message]:
    """OpenAI Responses truncation=auto: drop items from the beginning until the rest fits."""
    validate(window, messages)
    kept = list(messages)
    while kept and sum(message.tokens for message in kept) > window:
        kept.pop(0)
    return kept


def summarize_all(messages: list[Message], window: int) -> list[Message]:
    """Replace the whole history with a summary: a generic shape. Gemini CLI documents /compress this way, but its code also keeps the latest 30%."""
    validate(window, messages)
    return [Message("summary", 0, "summary")]


def keep_recent_user_messages(messages: list[Message], window: int, budget: int = 20_000) -> list[Message]:
    """Codex compaction: newest user messages first, whole while they fit the budget, plus a summary."""
    validate(window, messages)
    remaining = budget
    selected: list[Message] = []
    for message in reversed([m for m in messages if m.role == "user"]):
        if remaining == 0:
            break
        if message.tokens <= remaining:
            selected.append(message)
            remaining -= message.tokens
        else:
            # The source keeps a cut-down version here; it is no longer word for word.
            selected.append(Message("user", remaining, f"{message.name}:cut"))
            remaining = 0
    return list(reversed(selected)) + [Message("summary", 0, "summary")]


def keep_latest_fraction(messages: list[Message], window: int, fraction: float = 0.3) -> list[Message]:
    """Gemini CLI automatic compression: summary plus roughly the latest 30% of the history."""
    validate(window, messages)
    if not 0 <= fraction <= 1:
        raise ValueError("fraction must be between 0 and 1")
    total = sum(message.tokens for message in messages)
    target = total * fraction
    kept: list[Message] = []
    size = 0
    for message in reversed(messages):
        if size + message.tokens > target:
            break
        kept.append(message)
        size += message.tokens
    return [Message("summary", 0, "summary")] + list(reversed(kept))


def rule_is_verbatim(messages: list[Message]) -> bool:
    return any(message.name == RULE for message in messages)


def run(policy, trigger: float, window: int = 200_000, rule_tokens: int = 300, turns: int = 400) -> int | None:
    """Returns the first turn after which the rule is no longer word for word, or None."""
    history = [Message("user", rule_tokens, RULE)]
    for turn in range(1, turns + 1):
        history.append(Message("user", 500, f"u{turn}"))
        history.append(Message("assistant", 4_500, f"a{turn}"))
        if sum(message.tokens for message in history) > window * trigger:
            history = policy(history, window)
            if not rule_is_verbatim(history):
                return turn
    return None


def main() -> None:
    print("Scenario: window 200000, rule 300 tokens in first message, each turn adds 500 user and 4500 assistant tokens")
    scenarios = [
        ("drop_from_start (OpenAI truncation=auto shape)", drop_from_start, 1.0),
        ("summarize_all at 80% (shape of a full-history summary)", summarize_all, 0.8),
        ("keep_recent_user_messages at 80%, 64000 tokens (Codex shape, OpenAI and Azure)", partial(keep_recent_user_messages, budget=64_000), 0.8),
        ("keep_recent_user_messages at 80%, 20000 tokens (Codex shape, other providers)", keep_recent_user_messages, 0.8),
        ("keep_latest_fraction at 50% (Gemini CLI shape)", keep_latest_fraction, 0.5),
    ]
    for label, policy, trigger in scenarios:
        print(f"{label}: first turn without the rule word for word = {run(policy, trigger)}")


if __name__ == "__main__":
    main()

Its output, with the sizes untouched:

Scenario: window 200000, rule 300 tokens in first message, each turn adds 500 user and 4500 assistant tokens
drop_from_start (OpenAI truncation=auto shape): first turn without the rule word for word = 40
summarize_all at 80% (shape of a full-history summary): first turn without the rule word for word = 32
keep_recent_user_messages at 80%, 64000 tokens (Codex shape, OpenAI and Azure): first turn without the rule word for word = 132
keep_recent_user_messages at 80%, 20000 tokens (Codex shape, other providers): first turn without the rule word for word = 61
keep_latest_fraction at 50% (Gemini CLI shape): first turn without the rule word for word = 20

In this simulation, with these invented sizes, the rule stops being sent verbatim somewhere between turn 20 and turn 132. Except in the two Codex shapes, the rule is lost the first time the policy acts: if you wrote it in the chat, plan for that. Change the sizes and the numbers change, possibly even the ranking between policies. A summary counts as not verbatim even if it keeps the idea. The script simplifies too: real Codex cuts down the text of the message that doesn't fit, while here it is only marked as cut; Gemini CLI measures that 30% in characters of the serialized messages, not tokens, splits only between turns, and first trims older tool outputs past a 50,000-token budget; and caching and images aren't modeled.

What actually enforces a rule

A re-injected file solves the first failure and doesn't touch the third. Claude Code puts it plainly: "Claude treats CLAUDE.md files as context, not enforced configuration". To block an action whatever the model decides, you need a hook or a permission: something that runs outside the model. In the API, validate each tool call yourself before running it; whether your tool has its own hooks or permissions, we didn't check here. Our guide to Claude Code hooks covers events and configuration, and this hook that blocks the Co-authored-by line in commits is a complete case.

A longer CLAUDE.md doesn't help either. Its documentation warns: "Files over 200 lines consume more context and may reduce adherence." Don't confuse that with the auto memory limit: only the first 200 lines or 25KB of MEMORY.md load, whichever comes first, while a CLAUDE.md loaded at launch arrives whole up to 4 MiB.

If the rule is about an action and must hold every time, stop rewriting it in capitals: move it to a hook or a permission, and test that it fires. A hook that fails lets the action through, unless it has onFailure: "block", and a permission on Bash arguments can be sidestepped. If it's about the result, check it afterwards with tests, a linter or CI. If it's about the wording, none of these controls enforces it: review it.

Diagnosis by symptom

QuestionIf yesWhat to do
Was there a compaction, and was the rule outside a file that comes back from disk?The text leftRepeat it, or move it where it comes back (list below)
In a new session, with only the rule and the task, does it hold across several tries?Worse performance/clear, or remove what you don't need
Does it fail in a new session too?Never enforced, or unclearRewrite it concretely; if it's an action, external control

That new-session test is our opinion, not a measurement. /context doesn't help with a rule written in the chat: it gives categories and which files loaded, and /context all is for checking whether a file is still loaded.

Where to put the rule so it comes back:

In Claude Code, each command has a price:

What was checked and what wasn't

Documentation read on November 9, 2026; Codex code at commit e1cc967 and Gemini CLI at f89c765, both of which can change.

Conclusion

Forgot covers three failures: a rule that stopped being sent, one that is sent and performs worse, and one that was never enforced. Repeating the rule can bring back one that left, but it won't clean a noisy context or enforce anything.

Next time an agent ignores an instruction, before rewriting it, check whether there was a compaction and where the rule lived. If it left, move it where it comes back. If it's still there, try it in a new session: if it holds, the context was the problem; if not, rewrite it concretely. And if it's an action that must hold every time, write the hook or the permission today.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code