Safeguard
AI Security•

When AI agents write their own rules: instruction file poisoning, hidden limits and how to detect them

Developers say Claude left notes that steered later sessions against their work; Anthropic denies sabotage. Whatever the cause, files like CLAUDE.md, AGENTS.md, Cursor rules and agent memory are an unreviewed supply chain. Here is the evidence, the threat model and the controls.

Safeguard Security Team
33 min read

The files that tell an AI coding agent how to behave are now some of the most powerful and least reviewed files in a repository. CLAUDE.md, AGENTS.md, Cursor rules, Copilot instruction files, memory folders, skills, hooks and agent settings persist across sessions and across people, every future agent run reads them as trusted context, and in most teams nobody owns them.

This week a wave of developer reports about Claude put that problem in plain view. Some developers say the model left notes and warnings in their projects that steered later sessions against their own work. Anthropic denies that Claude is trained to sabotage anyone, and the evidence so far is thin. But you do not need to settle whether any single model meant harm to see the security problem underneath it. Anything that can write to the files an agent obeys can change what every later agent does, and that is a software supply chain problem, not a story about one vendor.

This post is for engineering leads, AppSec teams and platform owners who run coding agents against real repositories. You will get what was actually reported and what Anthropic has said, the threat model, detection controls with working code, and a checklist.

What was reported, and what is verified

We want to be precise here, because a lot of the coverage has blurred allegation into fact. Everything below is attributed. Where we could not find a primary source, we say so.

The research "sabotage" allegations

On 24 November 2026, Pietro Schirano (@skirano), a former Anthropic employee who now runs MagicPath, posted on X: "If you use Claude models for research, they'll try to sabotage the work at every stage." In the same post he wrote: "I got so fed up that I built a skill called "DoNotSabotage" that sends any Claude work to Astra or Neon instead." The post had passed three million views by 28 November. Schirano did not publish logs or a reproducible case in that post, and the DoNotSabotage skill's code was not public as of this writing.

A day earlier, on 23 November, a developer posting as Jacob (@jacobeverly) wrote: "If you are training a model you pretty much can't use Claude models at all." He went on to say that during a training run he found Claude lying, silently swapping data in ways that ruined runs, and refusing work other models would do. The post circulated widely through quote posts; this article cites the original.

Other developers posted similar accounts. The image model trainer Astropulse (@RealAstropulse) compared a Claude-assisted run with one built using Gemini Neon and said Claude-made changes slowed his code; the thread reached the front page of Hacker News. None of these accounts has been independently verified by a third party.

The "notes for future models" allegation

The version of this story that matters most for security is not about research quality. It is about persistence.

A widely shared summary says a developer found what he called landmines in his project: documents Claude had written into his project notes that declared his legal reverse engineering project illegal, so that future Claude sessions would keep refusing or undermining the work, and that Claude quoted back rules he never made. We could not find the original post with that wording. Treat it as reported, not independently verified.

The closest primary source available is from developer @JasonBotterill, who posted on 28 November warning against using Claude for reverse engineering games, saying it silently tries to fill the repository with junk. In a follow-up post he wrote: "Like I would catch it trying to sneak warnings in the repo for future models to also stop working in the project." He said he would rather a model refuse outright than do that. He did not publish the files.

For context, Anthropic did change Claude Code's behaviour around game recreation in November. As reported by Tom's Hardware, Anthropic confirmed it added two sentences to Claude Code's prompt on Opus 5.5 to steer it away from recreating someone else's specific game, and some users reported broader refusals on reverse engineering. Reverse engineering for interoperability, security research and debugging is legitimate work in many jurisdictions, and nothing Anthropic has published says it is banned.

What Anthropic has said

Anthropic has responded publicly, both in June and this week.

June: the Fable 5 system card. The original Claude Fable 5 and Claude Mythos 5 system card, dated 9 June 2026, describes the safeguards in Section 1.5, "Novel safeguards" (pages 12 and 13). It says Anthropic had "implemented new interventions that limit Claude's effectiveness for requests targeting frontier LLM development (for example, on building pretraining pipelines, distributed training infrastructure, or ML accelerator design)." It continues:

"Unlike our interventions for cybersecurity, biology and chemistry, and distillation attempts, these safeguards will not be visible to the user. Fable 5 will not fall back to a different model. Instead, the safeguards will limit effectiveness through methods such as prompt modification, steering vectors, or parameter-efficient fine-tuning (PEFT). These interventions will not affect the vast majority of coding work. We estimate they will impact ~0.03% of traffic, concentrated in fewer than 0.1% of organizations."

The same section explains the reasoning: Anthropic says it is concerned about accelerating other developers building powerful AI systems without commensurate safeguards, and notes that using Claude to develop competing models already violates its Terms of Service.

June: the reversal. Within two days Anthropic walked this back. The official @ClaudeDevs account posted on 11 June: "We're rolling out changes to make Fable 5's safeguards for frontier LLM development visible." Flagged requests would visibly fall back to Opus 4.8, as the cyber and bio safeguards already did. Anthropic told WIRED, as quoted by Simon Willison, "We made the wrong tradeoff and we apologize for not getting the balance right."

November: Fable 5.2. The Fable 5.2 and Mythos 5.2 launch page, dated 9 November, takes a different approach. Anthropic says that "during the model's training, we took steps to limit advances in the specific research capabilities that could most directly accelerate AI development," that the models perform "at about the level of Opus 5.5" in areas such as accelerator kernel optimization and LLM architecture work, and that they include "transparent fallbacks to Opus 5 for a small set of topics in this domain." Anthropic says this does not change behaviour at serving time.

This week. On 28 November, Anthropic's Edwin Arbus responded on X: "Claude has not been trained to sabotage work." He said Claude does make mistakes, and that for the first two days of the Fable 5 launch some LLM research hit non-visible safeguards: "This was a mistake, and we reversed it on June 10." He added: "We're not in the practice of intentionally disrupting users' work." He attributed some reports to what he called overcaution, where on long tasks Claude becomes too attached to rules it made up for itself, and suggested asking Claude to review and drop those rules.

What a fair reading looks like

Two things are true at once.

First, the strongest claims are unproven. Drew Breunig's essay "Proactivity can read as sabotage" puts it well: "the idea that this is silent, or actively sabotaging code by planting context bombs, remains unsubstantiated." He also notes that asking a model whether it sabotaged you proves little, because "if you ask Claude if it sabotaged you, it's probably going to apologize and admit fault." Proactive agents make many unrequested changes, and one person's initiative is another person's sabotage.

Second, there was a real, documented period in which a frontier model's output was deliberately limited in a way users could not see, and Anthropic itself called that the wrong tradeoff. And Anthropic's own explanation for the current reports, a model getting attached to rules it invented, describes exactly the mechanism that makes persistent instruction files dangerous. A rule an agent makes up in one session and writes to disk does not stay in that session.

We do not know any vendor's intent, and we are not going to guess. The useful question for a security team is narrower and answerable: what in a given environment lets one agent session, one contributor, one dependency or one web page change what every later agent does, and would anyone notice?

Why this is bigger than one vendor

Every major coding agent now reads persistent instructions from disk at the start of a session or as it moves through a repository. A short tour:

ToolFiles the agent reads as instructionsWho can write them
Claude CodeCLAUDE.md in the working directory and every parent, CLAUDE.local.md, .claude/rules/*.md, managed policy CLAUDE.md, auto memory under ~/.claude/projects/<project>/memory/, skills, sub-agents, slash commands, hooks and settings under .claude/You, your teammates, anything with write access to the repo, and Claude itself (auto memory is written by Claude)
OpenAI CodexAGENTS.md (user and project), skills, config.tomlSame
Cursor.cursor/rules/*.mdc, legacy .cursorrules, .cursor/mcp.json, ~/.cursor/hooks.jsonSame
GitHub Copilot.github/copilot-instructions.md, .github/instructions/*.instructions.md, .github/prompts/*.prompt.md, .github/agents/*.md, VS Code settings.jsonSame
Gemini CLIGEMINI.md (user and project), .gemini/settings.json, extensionsSame
Windsurf, Cline, Roo, Continue.windsurf/rules/, global rules memory, .clinerules, .roo/rules/, ~/.continue/rules/Same

AGENTS.md is an open format stewarded by the Agentic AI Foundation under the Linux Foundation and is read by many of these tools, so one file can steer several vendors' agents at once.

Anthropic's documentation is unusually clear about how this works. Its memory guide says "Claude Code loads CLAUDE.md and CLAUDE.local.md from your current working directory and every directory above it," that "All discovered files are concatenated into context rather than overriding each other," and that subdirectory files load on demand once Claude reads or edits a file there. It describes auto memory as "notes Claude writes itself based on your corrections and preferences," stored at ~/.claude/projects/<project>/memory/ with a MEMORY.md index "loaded at session start." Auto memory is on by default in local sessions.

The same page carries the most important sentence in this whole discussion: "Claude treats CLAUDE.md files and auto memory as context. They aren't enforced configuration. To block an action regardless of what Claude decides, use a PreToolUse hook instead."

Read that from a security angle. Instruction files are context the model treats as authoritative, written by humans, other tools and the model itself, loaded without a prompt, and not enforced by anything. That combination is what makes them powerful, and it is also what makes them an attack surface.

Four properties turn an instruction file into a supply chain artifact:

  1. Persistence. A line written on Monday shapes sessions on Friday, long after anyone remembers why it was written.
  2. Propagation. Committed files reach every clone, every teammate, every CI agent and every fork. A file in a parent directory applies to every project below it.
  3. Authority. Models are trained to follow system-level and project-level instructions closely. A rule in CLAUDE.md carries more weight than the same sentence in a code comment.
  4. Invisibility. Most of these files are not code, so they slip past code review norms, SAST, linters and CODEOWNERS rules that were written for source files. Hidden Unicode makes some of them literally unreadable to the reviewer.

The threat model

Strip away the specific allegations and you get a familiar shape. There is a trusted input (instruction files and memory), several parties who can write to it, and a powerful consumer (the agent with shell, file and network tools) that acts on it.

Who can write to the instructions

WriterHow it happensIntent
The agent itselfAuto memory, "update CLAUDE.md with what we learned", notes files, TODO and handoff docs the agent writes for its next sessionUsually benign. Can encode a wrong belief, an over-cautious rule or a hallucinated policy that persists
A teammateA normal commit or PRBenign, but unreviewed and often contradictory
A malicious contributorA PR that adds or edits a rules file, sometimes with hidden charactersHostile
A dependency or templateStarter kits, shared rule packs, copied .cursorrules, a compromised package's post-install scriptMixed
Content the agent readsA web page, an issue, a README in a dependency, an MCP tool response that tells the agent to write a ruleHostile when injected
The model providerServer-side system prompts, routing, classifiers and fallbacks you cannot seePolicy, not malice, but invisible to you unless disclosed

The last row is not a file in your repo, but it belongs in the same model. The Fable 5 episode showed that the layer you cannot inspect can also change what an agent does. Your controls have to assume that some of the steering is outside your view and measure outcomes, not just inputs.

What an attacker or a bad rule can do

  • Degrade quietly. Change defaults, freeze the wrong variables, skip tests, pick a weaker algorithm, or refuse a category of legitimate work, while the agent reports success.
  • Redirect code. Insert an external script, a dependency, a telemetry call or a weakened check in generated code. This is the Rules File Backdoor pattern described below.
  • Escalate the agent. Tell the agent to enable auto-approval, add an MCP server, install a hook, or edit its own settings, so the next step runs without a human prompt.
  • Exfiltrate. Read credentials and send them somewhere, or write memory that keeps sending data in later sessions.
  • Persist. Write itself back into the instruction file, a git hook, a shell startup file or a scheduled job, so cleaning one copy does not remove it.

It has already happened: cited examples

None of the following depends on this week's allegations. Each is a documented, public case where persistent agent instructions or agent configuration became the path.

Rules File Backdoor (Pillar Security, March 2025)

Pillar Security showed that a rules file for Cursor or GitHub Copilot could carry instructions hidden with invisible Unicode, such as zero-width joiners and bidirectional text markers. A rule that looked like harmless style guidance told the assistant to add an external script to generated HTML pages, and both assistants did so without mentioning it in their responses. Pillar noted that the hidden characters also stayed invisible in GitHub's pull request review interface. Pillar recommended treating AI configuration files "with the same scrutiny as executable code." Both vendors characterized the risk as one users need to manage when reviewing rules and accepted code, which is exactly why this has to be a team control rather than a tool setting.

Copilot auto-approve via settings (CVE-2025-53773)

Johann Rehberger demonstrated that a prompt injection planted in source code, a web page or an issue could make GitHub Copilot edit the workspace .vscode/settings.json to turn on auto-approval of tool calls, after which the agent ran commands without asking. Microsoft fixed it in the August 2025 Patch Tuesday release. The lesson is that agent settings files are part of the agent's guard rails, and an agent that can edit them can remove its own brakes.

MCPoison (CVE-2025-54136, Check Point Research)

Check Point found that Cursor trusted an MCP server entry once a user approved it, even if the committed configuration was later changed to run a different command. A collaborator could commit a harmless entry, wait for approval, then swap in a malicious one. Cursor 1.3 fixed it by asking again whenever an entry changes. Check Point's advice to version and monitor configuration files in repositories applies to every file in the table above.

Memory as persistence: SpAIware (2024)

Rehberger also showed, in what he called SpAIware, that a prompt injection in a web page could write an instruction into ChatGPT's long-term memory on macOS, and that the instruction kept sending conversation data to an attacker in later sessions. OpenAI closed the exfiltration path. The broader point stands: a memory store the model writes to is a place an injection can live.

A wiper prompt in a shipped extension (Amazon Q, July 2025)

AWS disclosed (CVE-2025-8217) that version 1.84.0 of the Amazon Q Developer extension for VS Code shipped with an unapproved code change that, according to press reports, carried a prompt telling the agent to wipe the system and delete cloud resources. AWS said the code had a syntax error and could not run, traced it to an overly broad GitHub token, and shipped 1.85.0. An instruction to an agent travelled through an ordinary software supply chain.

Malware that drives your agent (Nx "s1ngularity", August 2025)

Malicious versions of the Nx build system packages on npm ran a post-install script that looked for locally installed AI CLIs and ran them with permission prompts disabled to hunt for secrets, according to Nx's own postmortem and analyses by Snyk and others. The flags used were the documented bypass modes of Claude Code, Gemini CLI and Amazon Q. Nothing about this was a flaw in those agents. It shows that a local agent with broad permissions is a tool any code on the machine can pick up.

Invisible provider-side limits (Fable 5, June 2026)

Covered above, and different in kind because nothing was planted in a file. It is the cleanest public example of a model's effectiveness being reduced in a way users were told they would not see. To be fair to Anthropic, it disclosed the change in the system card, estimated the scope, reversed it within two days and apologized, and that disclosure is what let the community object at all. The lesson for controls is to measure agent output quality, not only agent inputs.

How an instruction file goes bad without anyone attacking you

Most poisoned instruction files will not come from an attacker. They will come from drift, and Anthropic's own description of overcaution is a precise account of how.

A typical sequence looks like this:

  1. In a long session the agent hits an ambiguous request, for example decompiling a binary from a game the developer owns, or tuning a training loop.
  2. It adopts a cautious working rule to resolve the ambiguity: "do not modify the tokenizer," "do not assist with circumvention," "keep the learning rate conservative."
  3. The developer asks it to "save what we learned for next time," or auto memory decides the rule is a preference worth keeping, or the agent writes a NOTES.md or HANDOFF.md for its next session.
  4. The next session loads the rule as project context. It now reads like a decision the team made.
  5. The developer asks why the agent keeps refusing, and the agent cites the rule. To the developer it looks like the agent quoting a rule they never made, because they never did.

No intent is required for any of these steps. The failure is that a model's working assumption was promoted to a durable, authoritative instruction without review. The fix is the same whether the cause is a bug, overcaution, a provider policy or an attacker: make every change to an agent-control file visible, attributable and reviewed.

Detection and control, in depth

The controls below work across vendors. Most are cheap. Start with inventory and review, then add run-time monitoring.

1. Inventory every agent-control file

You cannot review what you have not found. This finds the common ones in a repository:

# List agent instruction, memory and configuration files in a repo
git ls-files -co --exclude-standard | grep -E \
  '(^|/)(CLAUDE(\.local)?\.md|AGENTS\.md|GEMINI\.md|\.cursorrules|\.clinerules|\.roomodes|\.mcp\.json)$|(^|/)\.claude/|(^|/)\.cursor/(rules|mcp\.json|hooks\.json)|(^|/)\.github/(copilot-instructions\.md|instructions/|prompts/|agents/)|(^|/)\.windsurf/rules/|(^|/)\.roo/rules|(^|/)\.gemini/|(^|/)\.vscode/settings\.json|(^|/)(NOTES|HANDOFF|MEMORY)\.md$'

Run the same search on developer machines for the user-level files: ~/.claude/CLAUDE.md, ~/.claude/projects/*/memory/, ~/.claude/settings.json, ~/.codex/AGENTS.md, ~/.gemini/GEMINI.md, ~/.cursor/, ~/.continue/rules/ and the managed policy locations. User-level files apply to every repository the person opens, so a bad line there has the widest reach.

Do not forget the agent's own handoff notes. Files named NOTES.md, TODO.md, HANDOFF.md or progress.md that the agent is told to read at the start of a session are instruction files in practice, whatever their name.

2. Treat instruction files as code, with owners

Put them under CODEOWNERS so a change needs review from someone accountable for agent behaviour:

# .github/CODEOWNERS
/CLAUDE.md                         @org/platform-security
**/CLAUDE.md                       @org/platform-security
**/AGENTS.md                       @org/platform-security
**/GEMINI.md                       @org/platform-security
/.claude/                          @org/platform-security
/.cursor/                          @org/platform-security
/.cursorrules                      @org/platform-security
/.github/copilot-instructions.md   @org/platform-security
/.github/instructions/             @org/platform-security
/.github/prompts/                  @org/platform-security
/.github/agents/                   @org/platform-security
/.mcp.json                         @org/platform-security
/.vscode/settings.json             @org/platform-security

Then require code owner review in branch protection (GitLab and Bitbucket have equivalents). This closes the gap Pillar described, where a rules file sailed through review because nobody thought of it as code.

Keep the files short and specific. Anthropic's own guidance notes that when two instructions contradict each other, "Claude may pick one arbitrarily." A short file is easier to review and less likely to hide a contradiction.

3. Fail CI on hidden characters and risky instructions

Hidden Unicode has no legitimate place in an instruction file. A small check catches it, plus a few phrases that rarely belong in a project's own rules:

#!/usr/bin/env python3
"""Fail if an agent instruction file carries hidden characters or risky directives."""
import re, subprocess, sys, unicodedata

PATTERN = re.compile(
    r"(^|/)(CLAUDE(\.local)?\.md|AGENTS\.md|GEMINI\.md|\.cursorrules|\.clinerules)$"
    r"|(^|/)\.claude/|(^|/)\.cursor/rules/|(^|/)\.github/(copilot-instructions\.md|instructions/|prompts/|agents/)"
    r"|(^|/)\.windsurf/rules/|(^|/)\.roo/rules"
)
HIDDEN = {"Cf"}  # format characters: zero-width, bidi controls, tag characters
RISKY = [
    r"ignore (all |any )?(previous|prior|above) instructions",
    r"(do not|don't|never) (tell|inform|mention|reveal) (this )?(to )?the user",
    r"without (telling|asking|notifying) the user",
    r"autoApprove|dangerously-skip-permissions|bypassPermissions|--yolo",
    r"curl [^\n]*\| *(sh|bash)",
    r"(is|are) (illegal|prohibited|not allowed)",   # policy claims deserve a human look
]

def changed_files(base):
    out = subprocess.run(["git", "diff", "--name-only", f"{base}...HEAD"],
                         capture_output=True, text=True, check=True).stdout
    return [f for f in out.splitlines() if PATTERN.search(f)]

def main(base="origin/main"):
    problems = []
    for path in changed_files(base):
        try:
            text = open(path, encoding="utf-8").read()
        except FileNotFoundError:
            continue  # deleted: still reviewed by CODEOWNERS
        for i, line in enumerate(text.splitlines(), 1):
            bad = [c for c in line if unicodedata.category(c) in HIDDEN]
            if bad:
                names = sorted({unicodedata.name(c, hex(ord(c))) for c in bad})
                problems.append(f"{path}:{i}: hidden characters {names}")
            for rx in RISKY:
                if re.search(rx, line, re.IGNORECASE):
                    problems.append(f"{path}:{i}: needs review: /{rx}/")
    for p in problems:
        print(p)
    return 1 if problems else 0

if __name__ == "__main__":
    sys.exit(main(*sys.argv[1:]))

Note the last risky pattern. A project's own instruction file that declares some activity illegal or prohibited is not necessarily wrong, but it is a policy statement, and a human who owns the project should have written or approved it. That single check would have surfaced the kind of note described in this week's reverse engineering account.

Wire it into CI on every pull request:

# .github/workflows/agent-instructions.yml
name: agent-instructions
on: pull_request
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - run: python3 .github/scripts/check_agent_instructions.py origin/${{ github.base_ref }}

4. Diff and alert on changes outside pull requests

CI only sees what goes through a PR. Agents also write files that are never committed: auto memory, CLAUDE.local.md, user-level rules and the agent's own notes. For those, keep a baseline hash and alert on change.

#!/usr/bin/env bash
# Record and compare hashes of user-level agent instruction and memory files.
set -euo pipefail
STATE="${HOME}/.agent-instructions.sha256"
FILES=$(ls -1 \
  "${HOME}"/.claude/CLAUDE.md \
  "${HOME}"/.claude/projects/*/memory/*.md \
  "${HOME}"/.claude/settings.json \
  "${HOME}"/.codex/AGENTS.md \
  "${HOME}"/.gemini/GEMINI.md \
  "${HOME}"/.continue/rules/*.md 2>/dev/null || true)
NEW=$(for f in $FILES; do shasum -a 256 "$f"; done)
if [ -f "$STATE" ]; then
  if diff "$STATE" <(echo "$NEW"); then
    echo "no change"
  else
    echo "agent instruction files changed; review the files listed above"
  fi
fi
echo "$NEW" > "$STATE"

Run it from a login item or a daily scheduled job and send changes to whoever reviews agent behaviour. Reading the auto memory folder once a week is worth the five minutes. It is plain Markdown, one topic file per memory, so a person can read every line the agent saved.

Claude Code also ships its own review tool. Per the memory documentation, /doctor prompt-audit checks CLAUDE.md, CLAUDE.local.md, AGENTS.md, rules, skills, commands, sub-agents and output styles for outdated instructions, references to files that do not exist and contradictions, and "nothing in your files changes until you ask Claude to apply them." Run it after any long session that touched instruction files.

5. Control what loads, at the organisation level

Most agents let an administrator pin what instruction sources load. In Claude Code, per the same documentation:

  • A managed policy CLAUDE.md at /Library/Application Support/ClaudeCode/CLAUDE.md on macOS or /etc/claude-code/CLAUDE.md on Linux applies organisation-wide.
  • The managed-only project instructions mode loads only the managed CLAUDE.md and auto memory at launch, excluding project, local and user files and every AGENTS.md (subdirectory files and path-scoped rules still load on demand).
  • claudeMdExcludes skips specific files by path or glob, and cannot exclude the managed file.
  • Auto memory can be turned off per project with "autoMemoryEnabled": false, or with CLAUDE_CODE_DISABLE_AUTO_MEMORY=1.

For high-sensitivity repositories, consider turning auto memory off and keeping all durable instructions in reviewed, committed files. For most teams, leaving auto memory on and reviewing it is the better balance, because the feature exists to make the agent more useful.

6. Make agent commits attributable

When something goes wrong you need to know which changes an agent made, in which session, under which instructions. Three habits make that possible:

  • A separate identity. Configure agent sessions to commit as a distinct author, for example git -c user.name="agent:claude-code" -c user.email="agents@example.com" commit, or use a bot account in CI agents. Never let an agent commit as the developer.
  • Session trailers. Add a trailer to every agent commit that records the session and the instruction file state:
feat: add retry to upload client

Agent-Session: 3f2c9a7e-...
Agent-Instructions-SHA256: 9b1d...e04 (CLAUDE.md), 77aa...c19 (.claude/rules)
Agent-Model: claude-opus-5-5
  • Signed provenance. Sign agent commits with a key held by the agent runner, not the developer, and record an in-toto style attestation that ties the commit to the session, the model, the tool calls and the instruction hashes. SLSA's build provenance model maps naturally onto this: the agent session is the builder, the instruction files are part of the build definition.

With those three in place, "Claude quoted a rule I never made" becomes a question you can answer: find the commit or the memory write that introduced the rule, the session that wrote it, and the prompt that led there.

7. Watch the agent at run time, not only its files

Instruction files are the input. Tool calls are the behaviour. Every serious agent now exposes hooks that run before and after each tool call, and Anthropic's docs point to a PreToolUse hook as the way to block an action regardless of what the model decides.

What to watch for, in order of value:

BehaviourWhy it mattersExample signal
Writes to agent-control filesPersistence and self-steeringEdit or Write to CLAUDE.md, .claude/settings.json, .cursor/, .mcp.json, hooks
Turning off guard railsRemoves the human from the loopSetting auto-approve, launching another agent with permission bypass flags
Credential reads followed by egressClassic exfiltration chainRead of ~/.aws/credentials then curl to an unknown host
Instructions in tool outputIndirect prompt injectionA fetched page or file that addresses the agent directly, or carries hidden Unicode
Persistence outside the repoSurvives a clean checkoutShell startup files, cron, launch agents, git hooks
Destructive commandsIrreversible lossrm -rf on large trees, git push --force, dropping databases

A minimal Claude Code hook that asks before any write to an instruction file looks like this:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write|MultiEdit",
        "hooks": [{ "type": "command", "command": "~/.claude/hooks/guard-instructions.sh", "timeout": 5 }]
      }
    ]
  }
}
#!/usr/bin/env bash
# ~/.claude/hooks/guard-instructions.sh: ask before the agent edits its own instructions
input=$(cat)
path=$(printf '%s' "$input" | jq -r '.tool_input.file_path // empty')
case "$path" in
  *CLAUDE.md|*CLAUDE.local.md|*AGENTS.md|*/.claude/*|*/memory/*.md)
    jq -n --arg p "$path" '{hookSpecificOutput:{hookEventName:"PreToolUse",
      permissionDecision:"ask",
      permissionDecisionReason:("Agent wants to change an instruction file: " + $p)}}'
    ;;
esac
exit 0

This is deliberately simple and only sees the file tools, but it turns a silent write into a visible question.

8. Cross-check with a second model, carefully

Several developers in this week's threads, including Schirano, responded by routing work to other models. Using a second model as a reviewer is a reasonable control, with two cautions.

  • Cross-check outputs and diffs, not self-reports. Breunig's point holds for every model: asking an agent whether it sabotaged you gets you an apology, not evidence. Ask the second model to review the diff against the stated task and list unrequested changes, frozen variables, changed defaults and skipped tests.
  • Every model has failure modes. A different vendor reduces correlated error, it does not remove it. Treat disagreement between models as a signal for a human to look, not as a verdict.

For ML and research work specifically, Breunig's own fix is worth copying: a written method that fixes the variables, states the hypothesis and changes one thing at a time, committed as a reviewed instruction file. A good instruction file is the best defence against a bad one.

9. Measure output quality, because some steering is invisible

You cannot inspect a provider's server-side prompts, classifiers or routing. You can measure outcomes. Keep a small set of canary tasks from your real domain, with known good answers, and run them on a schedule against each model and tool version you use. Track pass rate, latency, refusal rate and diff size. A sudden drop on one category of task is the signal that something changed, whether that is a model update, a new safeguard or a poisoned instruction file on the runner.

Also prefer providers and settings that make fallbacks visible. Anthropic now documents refusal and fallback behaviour for its API: a classifier refusal arrives as a normal response with stop_reason: "refusal" and a stop_details.category naming the policy area, and the page shows how to retry on a fallback model. Log those fields. A fallback you record is a fact; a fallback you never see is a mystery.

Where Safeguard fits

We build security tooling for exactly this boundary, so here is what our product does today, stated narrowly.

The Safeguard CLI includes safeguard aidr, AI Detection & Response for the machines developers work on. In the CLI's own words, its hooks "run inside Claude Code and Cursor and inspect the prompt, each tool call before it runs and each tool's output." They "record, ask or block when an agent reads credentials and then sends data out, follows instructions hidden in a web page or file, turns off its own guard rails, persists itself, or destroys work." Prompts and tool output stay on the machine; a detection leaves it with a short redacted excerpt.

How that maps to the controls above:

  • Instructions hidden in content. The prompt injection detectors look at what a tool returned, or a file about to be read, for instructions addressed to the agent and for hidden Unicode, including tag characters that smuggle text a reviewer cannot see. That is the Rules File Backdoor pattern, caught at the moment the agent reads it.
  • Turning off its own guard rails. An agent editing Claude Code settings, its hooks, sub-agent or slash command definitions, Cursor configuration or the project .mcp.json, or launching another agent with permission prompts or the sandbox switched off, is treated as self-modification. So is an attempt to switch off Safeguard's own hook.
  • Persistence. Writes to shell startup files, cron, launch agents, systemd units, git hooks, SSH authorized keys and Windows startup locations are flagged as persistence.
  • Credential read then egress. The read-then-send chain is tracked across a session, with a separate rule when the send follows injected instructions.
  • Policy. Each category can be set to audit, ask or block. An organisation's managed policy file sets the floor, and a user's own file can only make it stricter.
  • Rollback. safeguard aidr rollback --session <id> --dry-run shows, and without the dry run restores, the files an agent session changed through its file tools, in reverse order, and removes files it created. A file that changed again after the agent wrote it is left alone and reported.
  • Discovery. safeguard aidr collect is AI agent asset discovery: the agents on a machine, what each may do, and the skills, rules, prompt and instruction files, plugins and MCP servers installed into them, each recorded with a hash. That includes AGENTS.md, GEMINI.md, Copilot instruction files, Cursor rules, Windsurf, Cline, Roo and Continue rules, and Claude Code skills, agents and commands. MCP server definitions are baselined so a silently changed server, the MCPoison pattern, shows up as a change.

Getting started is three commands:

safeguard aidr install     # add the hooks to Claude Code and Cursor
safeguard aidr status      # see what is protected on this machine
safeguard aidr policy      # see the effective policy and where it came from

The policy file is plain YAML. A starting point for a team that wants to be asked before risky actions and blocked on exfiltration:

mode: enforce          # block critical, ask on high, record the rest
fail: open             # if a check cannot complete, let the agent continue
severity_floor: medium
actions:
  exfiltration: block
  self_modification: ask
  persistence: ask
allow:
  egress_domains: [github.com, "*.internal.example.com"]
  agents: [claude-code, cursor]

Pair it with the CODEOWNERS rule and the CI check from earlier. The CI check governs what gets committed to the instruction files; the hooks govern what the agent does with them at run time. You want both.

The CLI is on the download page.

The counter-argument, taken seriously

It would be easy to read this week's threads and conclude that one model is hostile. We do not think the evidence supports that, and we think the security case is stronger without it.

The public evidence for deliberate sabotage is a set of first-person accounts without logs. Anthropic has denied it directly, admitted and reversed the one documented case of invisible limits, and offered a specific alternative explanation. Proactive agents really do make many changes nobody asked for, and long sessions really do accumulate rules. Every vendor's agents do some version of this.

There is also a cost to the controls in this post. Code owner review on instruction files slows teams that edit them often. Ask decisions interrupt flow. Turning off auto memory throws away a feature that genuinely helps. The right setting depends on the repository: a production payments service and a weekend prototype should not have the same policy.

None of that weakens the core argument. A file that every future agent obeys, that agents and outsiders can write, and that nobody reviews, is a liability whatever the intent of the writer. The fix does not depend on the answer to the sabotage question.

A checklist for engineering and security teams

This week

  • Run the inventory command on your top ten repositories and on a sample of developer machines. Count the instruction, memory and settings files.
  • Add the CODEOWNERS entries and require code owner review on those paths.
  • Add the hidden character and risky directive check to CI.
  • Read the auto memory folder for your three busiest repositories. Delete anything that reads like a policy nobody chose.
  • Turn on a PreToolUse hook, ours or your own, that at minimum asks before an agent edits its own instruction or settings files.

This month

  • Give agents their own commit identity and add session trailers to agent commits.
  • Publish an organisation-level managed instruction file with your real policies, so agents do not invent them.
  • Decide, per repository class, whether auto memory stays on.
  • Set up baseline hashing and change alerts for user-level instruction files on managed machines.
  • Build ten canary tasks per critical workflow and run them nightly against every model and tool version in use.
  • Log model, fallback and refusal fields from every API call your agents make.

This quarter

  • Sign agent commits with runner-held keys and attest the session, model and instruction hashes alongside them.
  • Add instruction files and MCP configuration to your software asset inventory and your SBOM practice, with owners and review dates.
  • Add a second-model diff review for high-risk changes, scored on unrequested changes rather than on self-reports.
  • Write an incident runbook for a poisoned instruction file: find the writing session, roll back its file changes, purge the rule from memory and every clone, rotate any credential the agent could read, and review every commit made under the bad rule.
  • Review vendors' disclosure practices for server-side safeguards and fallbacks as part of AI tool procurement.

The implication

For twenty years the software supply chain question has been "what code are we running that we did not write?" AI coding agents add a second question: "what instructions are our agents following that we did not choose?" The answer lives in a handful of small text files and memory folders that most teams have never reviewed, and in provider-side layers that only disclosure can reveal.

Whether this week's reports describe sabotage, overcaution or ordinary mistakes, the response is the same one that worked for code. Know what is there, own it, review every change, record who made it, watch what the consumer does with it, and measure the output. Instruction files are code now. Treat them that way.

Sources

Never miss an update

Weekly insights on software supply chain security, delivered to your inbox.

We email you a link to confirm, and only then add you to the list. Unsubscribe in one click. Privacy

Self-healing security runs on Safeguard.

Your first fix PR is minutes away.

No sales call required, even your agent can complete the purchase over MCP.