---
title: "Agent guardrails for rules that depend on environment state"
description: "Most AI agent guardrails block a pattern, like a force push. The rule that cost me depended on whether another app was running. How I enforce it in a pi extension, why it fails open, and why every block needs to name the safe alternative."
canonical_url: "https://subodhdahal.com/blog/agent-guardrails-environment-state/"
---

> Index of every page on this site: [llms.txt](https://subodhdahal.com/llms.txt)

I'd dictated a few minutes of my own thoughts, asked my AI agent to write them into my personal notes, and it told me it had. Later the notes weren't on the page. The agent had written straight to the Markdown file while my notes app was open, and the app had saved its own copy over the top. I'd already told it not to do that, in the instructions it reads every session.

The usual fix is to move the rule into a hook. Most hook examples block a pattern, like a force push, which is dangerous at any hour. Others track state inside the agent's session, such as the current branch. **My rule depended on whether a different program on my machine was running at that moment**, and nothing in the model's context could tell it that.

## My setup: a personal second brain fed by dictation

My second brain is a folder of Markdown files I edit in [Logseq](https://github.com/logseq/og) (the original version, which stores pages as plain files). It holds my own ideas and anything I want to find again, and no work notes go through it. I talk an idea through into [Handy](https://subodhdahal.com/blog/handy-speech-to-text-nixos-cosmic-egpu/), a local speech-to-text app, and ask the [pi](https://pi.dev/) coding agent, an open-source agent that runs in the terminal, to file it on the right pages. Filing a dictated idea doesn't need a frontier model, so my default is the cheap DeepSeek V4.1 Flash.

I'd hit the gap between rules an agent reads and rules that hold before, in a pipeline at work that turns Jira tickets into pull requests. My notes are the small version, where a failure was cheap enough to study closely.

## Judgment, pattern and state rules for AI agents

<table>
<thead>
  <tr>
    <th>
      Kind of rule
    </th>
    
    <th>
      Example
    </th>
    
    <th>
      Can a script decide it at the tool call?
    </th>
    
    <th>
      Where it goes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Judgment
    </td>
    
    <td>
      "Turn a dictated ramble into organized notes on the right pages"
    </td>
    
    <td>
      No
    </td>
    
    <td>
      The prompt (<code>
        AGENTS.md
      </code>
      
      , <code>
        CLAUDE.md
      </code>
      
      )
    </td>
  </tr>
  
  <tr>
    <td>
      Pattern
    </td>
    
    <td>
      "No <code>
        rm -rf
      </code>
      
       and no writes to <code>
        .env
      </code>
      
      "
    </td>
    
    <td>
      Yes, from the call's arguments
    </td>
    
    <td>
      A hook that matches the call
    </td>
  </tr>
  
  <tr>
    <td>
      State
    </td>
    
    <td>
      "Don't write to a note while Logseq is open"
    </td>
    
    <td>
      Yes, but only by looking outside the call
    </td>
    
    <td>
      A hook that checks environment state when the call happens
    </td>
  </tr>
</tbody>
</table>

State rules are the ones that cost me. The answer changes during a session (I open and close Logseq all day, and a session runs for hours), and the model can't see it. They also look like preferences, so they end up in the prompt.

My test now: if a script can check the rule at the moment of the tool call, and a miss costs more than a retry, it goes in code.

### Prompt rules fail even while the model can see them

My first fix was a line in `AGENTS.md`. The agent followed it early in a session and went back to `edit` a long way in. I blamed compaction, where the harness summarizes a long history. 2026 research agrees long sessions lose rules, but not on why. [Governance Decay](https://arxiv.org/abs/2606.22528) found compaction raised violations from 0% to 30% across seven models, hitting soft, organization-specific policies 8.3 times as hard as safety norms. [ARCBench](https://arxiv.org/abs/2611.03223), built on pi itself, found most violations happen while the rule is **still in the summary**, with the agent treating a later request as permission.

For my decision, the disagreement doesn't matter. Either way, a rule the model can read is a rule it usually follows, and a local, soft rule about how to work is the first one a long session loses.

### Why pinning the rule wouldn't have saved the note

Governance Decay also tested pinning the rule so the summary can't drop it, and about 47 pinned tokens brought violations back to 0%. That fixes a pattern rule. A pinned "don't write while Logseq is open" still leaves the model to guess whether Logseq is open. It could check with a shell command, but "remember to check before every write" is just another prompt rule. Only a check that runs at the moment of the write knows the answer.

### Reliability in the harness makes the model a cost decision

Once the harness enforces the rules, picking a model is a cost decision instead of a safety decision.

Cheap models do break rules more. In the Governance Decay runs, DeepSeek V4 Flash, the version before my default, broke a rule after compaction 59% of the time, worse than the 37% it scored with no rule at all. Claude Sonnet 4.6 broke it 19% of the time. Frontier models break rules less often, not never, and Anthropic's own [Claude Code docs](https://code.claude.com/docs/en/memory) say `CLAUDE.md` files "aren't enforced configuration."

A guard in code runs the same way whichever model asked. When [Li and colleagues](https://arxiv.org/abs/2611.10884) enforced a procedure with a state machine at every tool call, Claude Haiku 4.5 went from 48 of 200 accounts handled correctly and by the procedure to 139, and Sonnet 4.6 stopped drifting. I'd rather enforce the rule in code than pay [Opus](https://platform.claude.com/docs/en/about-claude/pricing) 35 times more per output token for a model that breaks it less often.

## The guard: a pi extension that checks Logseq before every write

While Logseq runs, it keeps pages in memory and writes a page back to disk once editing has been idle for a few seconds. If the agent writes the file and Logseq saves the same page before noticing, the agent's edit disappears without an error. With the app open, the safe path is an MCP server that adds blocks through Logseq's local API. With the app closed, nothing serves that API, and editing files directly is fine and much faster for bulk edits.

pi extensions subscribe to events in the agent loop. The [`tool_call` event](https://docs.pi.dev/latest/extensions) fires before a tool runs, and returning `{ block: true, reason }` stops it. The reason goes back to the model as the tool's error.

<figure className="image">

![Sequence diagram with four participants: the model, the guard, the Logseq app and the note files. The model asks to edit a journal file, the guard probes Logseq's local API, Logseq answers, and the guard blocks the edit with a message to use the Logseq MCP tools. The model then appends the block through Logseq MCP, Logseq saves the file itself and confirms where the block went.](https://subodhdahal.com/images/agent-guardrails-in-code/guard-sequence.svg)
  <figcaption>

The model never writes the file while Logseq is open. The app does.

</figcaption>
</figure>

```typescript
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";

export default function (pi: ExtensionAPI) {
  pi.on("tool_call", async (event) => {
    // A path check for write and edit, a regular expression for bash
    if (!writesToNotes(event) || !(await logseqIsRunning())) return;

    return { block: true, reason: blockMessage(event) };
  });
}
```

The check runs at the moment of the write because any earlier check leaves a gap. [One study](https://arxiv.org/abs/2607.10487) found agents reached the end of the task in 262 of 270 runs, but only 55 still had valid authorization when they committed the change. That's my lost note: from where the agent sat, it had finished the task.

### Failing open, against pi's advice

pi's docs say a gate should fail closed. I catch the probe's error, so if Logseq doesn't answer, the write goes through. I decided by what each wrong answer costs:

<table>
<thead>
  <tr>
    <th>
      The guard is wrong when
    </th>
    
    <th>
      What it costs
    </th>
    
    <th>
      How often
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      Failing closed: it blocks because Logseq didn't answer, but Logseq isn't running
    </td>
    
    <td>
      The agent can't save anything, since the MCP path is down too
    </td>
    
    <td>
      Every time I quit Logseq
    </td>
  </tr>
  
  <tr>
    <td>
      Failing open: it allows because Logseq didn't answer, but Logseq is running with its API off
    </td>
    
    <td>
      I can lose a note, as before the guard
    </td>
    
    <td>
      Only if I turn the API off, which I haven't
    </td>
  </tr>
</tbody>
</table>

To the probe, a closed app looks like one that didn't answer. I'd switch to failing closed if the guard could tell them apart, for example by checking the process list first. For `rm -rf` I'd fail closed without drawing a table.

## Tell the agent the safe path when you block it

An agent blocked without an alternative often finds its own way around, usually through the shell. In [CircumEval](https://prakratt.github.io/CircumEval/), Claude Opus 4.6 got past a read-only lock in every run, and telling it not to edit didn't help. In [Victor Velazquez's runs](https://victorvelazquez.dev/blog/agents-route-around-your-hooks/), a hook on `Edit|Write` never fired, because the agents did their writing through `Bash`. My own sessions look the same: the agent runs far more shell commands than edits, and `sed` or `python3` can rewrite a note as easily as `edit` can.

So my guard matches the effect, not the tool: `write`, `edit` and `bash` commands that redirect, `tee`, `sed -i`, `mv` or `cp` into `pages/` and `journals/` all hit the same check. And the block message tells the agent what to do instead:

```text
Before: Blocked: Logseq is running.

After:  Logseq is running, so writing journals/2026_12_01.md directly can be
        overwritten when the app saves the page. Append the block through the
        Logseq MCP server instead, with the page name and the block text.
        Set LOGSEQ_MCP_GUARD=off only if the user asks.
```

[Xu and Wu](https://arxiv.org/abs/2609.35381) measured the difference with MCP errors: telling agents to run a terminal command recovered 45% of tasks, and naming the server's own tool recovered 84%. A good block costs one tool call, not the task.

To check it works, I count what the agent does right after each block. The MCP call means it's working, a `bash` call means it's looking for another door, and a question to me means the message is too thin.

## What carries over to a team

My guard catches a helpful agent's habits. It wouldn't stop one trying to get past it, since the regex misses a Python one-liner or a path built from a variable. At work, the guarantee is at the merge, outside the agent's session.

The pipeline I built at work turns a Jira label into a pull request written by Claude. The prompt tells that agent how we work. Code enforces what can't have exceptions: every CI check runs, and a separate workflow decides from a PR's blast radius whether a product owner can merge it or an engineer has to review it. That merge gate is a state check one level up: whether a change is safe to merge depends on what it touches, and nothing inside the agent's session shows that.

Review agent config like policy too, including who can switch a guard off. My `LOGSEQ_MCP_GUARD=off` is fine for one person and not for a team.

## Trade-offs

- The `bash` check is a regular expression. It's easy to get past and blocks some harmless commands, like copying a note out of the folder.
- There are still milliseconds between the probe and the write. Closing that would need a lock Logseq doesn't offer.
- Every write to the notes costs one call to Logseq's local API. [Alyria argues](https://www.alyria.ai/blog/gates-for-coding-agents) hook checks shouldn't touch the network at all. Mine runs only on note writes and only calls localhost, so I think the trade holds. A remote call on every tool call would be a different decision.

## Build your own

1. Write down the rule and the environment state that decides it.
2. Probe that state inside the hook, at the moment of the call.
3. Match on the effect across every tool that can cause it, including the shell.
4. Decide what happens when the probe can't answer, and write the gap down.
5. Make the block message name the safe call.
6. Count what the agent does after each block.

In Claude Code this is a [`PreToolUse` hook](https://code.claude.com/docs/en/hooks) that returns `deny` with a reason.

## Conclusion

The agent still tries `edit` now and then. Now that costs one blocked call instead of a missing page. If I were moving a team's rules out of the prompt, I'd start with the ones that depend on something the model can't see. Nobody upstream will write those guards for you, and no amount of reminding fixes them.

## Sitemap

See the full [sitemap](https://subodhdahal.com/sitemap.md) for all pages.
