How to detect instruction-following failures, decide when to restart Claude Code or Codex, and preserve important context between sessions.
By Youssef Hosni
Published: 2026-11-21
URL: https://todatabeyond.substack.com/p/canary-trick-detecting-context-degradation
With AI coding agents like Claude Code and Codex, it’s hard to know when to start a fresh session. I usually restart at around 50% context utilization, but that number says nothing about whether the agent is still following instructions or remembering project details.
An agent can start ignoring constraints well before it hits its context limit. The canary trick is one way to catch this: add an instruction to CLAUDE.md that tells Claude to begin every response with a specific name or marker. If the marker disappears, you know an instruction was dropped.
Below, I look at how the technique works, set up a reproducible experiment to test whether canary failures line up with factual-recall errors, and lay out a strategy for deciding when to continue, compact, or restart a session. The last part covers a handoff file that carries decisions and unfinished work into the next session.

Table of Contents:
- Why AI Coding Agents Lose Reliability During Long Sessions
1.1. How Context Accumulates During a Coding Session
1.2. What Is Context Degradation?
1.3. Why a 50% Context Threshold Is Not Always Effective
- The Canary Trick: A Simple Signal for Instruction-Following Failures2.1. Implementing the Canary in Claude Code
2.2. What Does a Missing Canary Actually Mean?
2.3. Making the Canary More Useful
- Testing the Canary: Does It Really Predict Agent Failures?3.1. Experiment 1: Canary Adherence Under Increasing Context Length
3.2. Experiment 2: A Multi-Turn Coding Session With Changing Requirements
3.3. Results: One Canary Failure, but No Recall Failure
3.4. Does the Canary Predict Context Degradation?
3.5. What This Means for Real Coding Sessions
- Building a Better Session Management Strategy4.1. Combining Context Utilization, Canary Status, and Task Verification
4.2. Understanding Continue, Compact, and Restart
4.3. A Decision Framework for Session Management
4.4. Applying the Strategy to a Real Coding Session
- Preserving Context When Starting a Fresh Session5.1. Creating a Structured Handoff File
5.2. Generating the Handoff Before Restarting
5.3. Starting Fresh in Claude Code and Codex
5.4. Verifying the New Session Before Continuing
Our latest book: Hands-On Docker for Data Science & AI Projects — From your first containers to running local LLMs and AI agents.
A 30% early-bird discount until the end of November. For paid subscribers, get a 50% discount on this course and all other books and courses using this code:
50% Discount on the book for To Data & Beyond paid subscribers.

1. Why AI Coding Agents Lose Reliability During Long Sessions
My rule with Claude Code and Codex has been to start a fresh session at around 50% context utilization. It doesn’t always work.
Some sessions stay reliable well past that point. Others go wrong much earlier: the agent forgets a constraint from the start of the conversation, suggests an approach we already ruled out, or changes code without regard for an earlier architectural decision.
These problems are easy to miss. The agent keeps giving convincing explanations, running tools, and writing code while drifting away from the original requirements. By the time you notice, you may have spent several iterations fixing avoidable mistakes.
1.1. How Context Accumulates During a Coding Session
On every turn, the model receives a context for its next response. Depending on the agent and its configuration, this includes system instructions, project-level rules, conversation history, tool definitions, source code, and earlier tool outputs.
Say you ask Claude Code to add authentication to an existing application. It explores the repository, reads configuration files, examines the authentication middleware, and identifies the relevant dependencies.
Then it proposes an implementation, edits several files, runs tests, and investigates failures. Each step adds more to the conversation: source files, terminal output, stack traces, and the agent’s own responses.
Some of that stays essential, like the requirement to use the existing authentication provider. Some of it, like dependency installation output or an error that’s already fixed, is dead weight.
The agent has to keep track of what matters for the current task while the pile of outdated material keeps growing.
Anthropic’s guide to effective context engineering frames the goal as giving each model call the right set of information, not fitting as much as possible into the window.

\Figure 1.Over a long coding session, useful instructions and decisions become mixed with historical tool outputs, resolved errors, and intermediate information. The proportions are illustrative, not measured.\
1.2. What Is Context Degradation?
Context degradation, sometimes called context rot, is the decline in a model’s ability to use information reliably as the context gets longer or harder to navigate.
Having information in the context window doesn’t mean the model will use it. It may fail to apply an instruction, miss a relevant detail, or favor whatever appeared later in the conversation.
In the 2024 paper Lost in the Middle: How Language Models Use Long Contexts, Liu and colleagues tested language models on multi-document question answering and key-value retrieval.
Performance depended heavily on where the relevant information sat. Models did better when it was near the beginning or end of the input and worse when it was in the middle.
Those were earlier-generation models, so the results don’t measure current Claude Code or Codex performance. They do show that the advertised context window size tells you little about how well a model uses what’s inside it.
For coding agents, this matters. Say you told the agent not to change the database schema. After several rounds of debugging, it proposes a schema change because that looks like the simplest fix for a failing test.
The agent may still understand the codebase and write valid code. It just no longer respects a requirement from earlier in the conversation.
The same goes for repeating failed approaches, overlooking an earlier design decision, or treating an outdated tool result as the current project state. Any of these can come from unreliable context use, though ordinary reasoning or tool-use errors can cause them too.
A model can have an instruction inside its available context and still fail to follow it. Context availability and reliable context utilization are different properties.
1.3. Why a 50% Context Threshold Is Not Always Effective
A common approach is to start fresh once context utilization hits a set threshold. Mine is 50%, because I’d rather restart before the conversation gets unwieldy.
But that percentage only measures how full the context is. It doesn’t tell you whether the agent still follows the original instructions, remembers important decisions, or produces correct results.
Two sessions at the same utilization can behave very differently. One might be a focused discussion of a single implementation; the other might be full of large logs, abandoned approaches, repeated debugging attempts, and contradictory intermediate instructions.
Reliability also depends on the model, the task’s complexity, where important information sits, and how well the context is organized, so no single percentage works across tasks and models.
There’s also compaction. Claude Code can summarize conversation history to free up space without a full restart, a feature called compaction. According to Anthropic’s session management documentation, it keeps a summary of earlier work but is lossy.
So after compaction, an agent can show low utilization while missing a detail from earlier in the session. And a session using more context can stay reliable if the information is well organized and the agent keeps following its constraints.
Context utilization is useful for tracking resource use and anticipating limits, but it’s only an indirect signal of reliability.
1.4. From Context Utilization to Reliability Monitoring
A better approach pairs context utilization with signals from the agent’s behavior: instead of restarting at a fixed percentage, look for evidence that the agent has stopped following important instructions.
For example, check now and then whether it remembers an earlier constraint, still follows a required response format, or can correctly describe the task’s current state.
These checks are imperfect. A model can pass a formatting check while misunderstanding the task, or fail one while still writing correct code. They still tell you something a utilization percentage can’t.
The canary trick is one such check: a small, persistent instruction that gives you a visible signal when the agent stops following instructions during a long session.
2. The Canary Trick: A Simple Signal for Instruction-Following Failures
The canary trick comes from Peter Steinberger, the creator of OpenClaw. It uses a small instruction to make it obvious when an AI coding agent stops following a rule.
You ask the agent to begin every response with your name. If the name disappears, the agent has broken an instruction, and the session may be worth investigating.
The name itself doesn’t matter. A specific word, a short identifier, or a fixed string works too. What matters is that the instruction is easy to follow and easy to check without reading the rest of the response.
The name comes from the canary in a coal mine: miners used canaries as an early warning of dangerous conditions they couldn’t easily detect themselves.
In a coding session, instead of judging whether the whole conversation has become unreliable, you watch whether the agent keeps respecting one simple rule.
The analogy has a limit, though. It hasn’t been established that a missing canary reliably comes before hallucinations or other coding errors. For now, treat it as a lightweight indicator of instruction-following.
2.1. Implementing the Canary in Claude Code
Claude Code reads project-level instructions from a file named CLAUDE.md, where you define persistent project context, coding conventions, architectural requirements, and other instructions for working in the repository.
According to Anthropic’s Claude Code memory documentation, Claude Code loads applicable CLAUDE.md files into its context. Instructions there carry across sessions, but they aren’t guaranteed to be obeyed.
For the simplest version, open (or create) CLAUDE.md in your project root and add this instruction:
## Canary
Start every response with “Youssef,”.
Do not omit this prefix in short replies or task summaries.
Replace Youssef with your own name or any identifier. Keep the instruction short and unambiguous, so you only need to check the start of each response.
Then start a new Claude Code session from the project directory:
claude
Give Claude a simple task, like explaining the repository structure or finding where a function is defined. The response should begin with the prefix. Keep working normally and watch whether it stays as the conversation grows.

\Figure 2.\
A fixed marker such as [CANARY:OK] works better than a name because it’s easier to check automatically across many responses.
The experiment in the next section uses this version:
## Canary
Begin every normal response with the exact prefix:
[CANARY:OK]
Each response either begins with the marker or it doesn’t. With tool-using agents, you also need to separate normal assistant responses from tool calls and other events where the marker doesn’t apply.
2.2. What Does a Missing Canary Actually Mean?
The argument behind the technique is that an agent may stop following small instructions before it makes bigger mistakes. That would be useful, since a formatting rule is cheap to check and an agent’s reasoning or code is not.
But a missing canary can have several explanations.
- First, the model may have failed to follow the instruction. Language models don’t execute natural-language instructions like deterministic code. Even with the instruction in context, the model may skip it, especially under competing formatting requirements or other constraints.
- Second, the agent’s context-management mechanism may have changed the information available to the model. Summarization and compaction can keep the high-level task while dropping details from earlier in the conversation.
- Third, the response may have been affected by other instructions or output requirements. A tool or workflow may require a particular output structure, so a missing prefix could mean conflicting instructions rather than declining reliability.
In Claude Code specifically, CLAUDE.md instructions are designed to survive compaction. So a missing canary from that file doesn’t necessarily mean Claude lost access to the instruction.
The reverse also holds: an agent can keep printing the right prefix while writing incorrect code, inventing details, or misreading the requirements. What the canary observes and what we’d like it to predict are different things.

\Figure 3.How to interpret the canary: it observes compliance with a specific instruction, while broader reliability requires independent verification.\
A canary can tell us that an instruction was not followed. Determining whether that failure indicates broader context degradation requires additional evidence.
2.3. Making the Canary More Useful
The canary is still useful as part of broader session monitoring. It takes almost no effort to set up and makes one aspect of instruction-following visible during normal work.
I would use the canary as a warning that triggers a closer inspection rather than automatically terminating the session.
If the prefix disappears, check whether the response is still correct and consistent with earlier requirements. Ask the agent to restate a critical architectural constraint, inspect its changes, or run the relevant tests.
If it keeps ignoring instructions or contradicts earlier decisions, that’s a stronger reason to compact or restart. If the missing prefix was a one-off formatting slip, a restart is probably unnecessary.
The open question is whether the signal predicts anything. If the canary only disappears after the agent is already making errors, it’s a poor early warning. If it consistently fails first, it gives you a chance to intervene.
That’s what the experiment in the next section tests: it grows the conversation, checks whether the model keeps following the canary, and separately measures whether it retains facts and constraints from earlier in the session.
3. Testing the Canary: Does It Really Predict Agent Failures?
The canary shows whether an agent keeps following one instruction. The real question is whether a missing canary means the agent is becoming less reliable, or whether it can disappear while the agent still does its task correctly.
I ran two experiments with Claude Sonnet 5. The first tested whether longer context affected canary adherence and factual recall. The second used a more realistic multi-turn conversation with changing project requirements, conflicting historical information, and repeated reliability checks.
Both experiments measured canary adherence separately from the model’s ability to retain project information, so we can see whether breaking a formatting instruction says anything about broader task reliability.