DEV Community

Duck
Duck

Posted on

Your agent remembers things that never happened

An agent on Windows runs echo "home=$HOME" and gets back the literal string "home=$HOME". The model wasn't careless. Its system prompt said the shell was bash, so it wrote bash. The tool ran the command through cmd.exe.

I fixed two bugs like this in open source agent frameworks this month. They live in different projects and different languages, but they have the same cause: what the model was told had drifted from what the code did. This post walks through both, then turns them into a checklist you can run against your own agent.

The model only knows what you put in the context

An LLM can't look at your runtime. It can't check which shell is installed or what a hook did to its arguments. Everything it believes about the world comes from three places: the system prompt, the message history, and the tool results you feed back.

Those get built in two different ways. Some are facts you state up front, like the OS, the shell, the working directory and the tools. The rest is a record of what happened: which tools were called, with what, and what came back. Each of the bugs below breaks one of these.

Bug 1: the prompt describes a shell the tool never uses

nanocoder is a terminal coding agent. Its system prompt includes a line like Default Shell: /bin/zsh, built by a small function in prompt-builder.ts. Its execute_bash tool, on Windows, always spawns ComSpec, which is cmd.exe.

The prompt builder checked things in this order:

const getDefaultShell = (): string => {
    if (process.env.SHELL) return process.env.SHELL;
    if (platform() === 'win32') return process.env.COMSPEC || 'cmd.exe';
    if (platform() === 'darwin') return '/bin/zsh';
    return '/bin/bash';
};
Enter fullscreen mode Exit fullscreen mode

That looks reasonable until you start the agent from Git Bash or MSYS2. Both set SHELL to a bash path, so the first line wins and the prompt says C:\Program Files\Git\usr\bin\bash.exe. The executor never reads SHELL. It runs cmd.exe anyway.

So the model writes $HOME, single quotes, && chains with export, /dev/null. cmd.exe doesn't expand $HOME, has no export, and treats single quotes as ordinary characters. Commands fail or quietly do the wrong thing, and the model has no reason to suspect its own assumption, because the prompt told it so.

The fix is to check the platform first:

 const getDefaultShell = (): string => {
+   // execute_bash runs commands through ComSpec on Windows, even when SHELL
+   // is set by Git Bash or MSYS2.
+   if (platform() === 'win32') return process.env.ComSpec || 'cmd.exe';
    if (process.env.SHELL) return process.env.SHELL;
-   if (platform() === 'win32') return process.env.COMSPEC || 'cmd.exe';
    if (platform() === 'darwin') return '/bin/zsh';
    return '/bin/bash';
 };
Enter fullscreen mode Exit fullscreen mode

The diff is small, but the real problem is bigger than the order of two ifs. "Which shell do we use" was answered in two places, once in the prompt builder and once in the executor, and each answered it its own way. Two sources of truth for one fact will drift sooner or later. The more robust version is for the prompt to ask the executor, or for both to read the same constant.

Bug 2: the history records arguments the tool never ran with

crewAI lets you register before_tool_call hooks that can change a tool's input before it runs. That's useful for clamping values, filling defaults, or adapting the input to a system's rules.

The issue that reported this had a nice example. A meeting assistant books a room through a reserve_room tool. The company calendar works in 15-minute blocks, so a hook rounds duration_minutes up. The user asks for 35 minutes, the hook makes it 45, and the tool saves a 45-minute booking. Then the conversation continues: the reporter passes result.messages into a second kickoff() and asks how long the booking is. The agent answers 35.

Here's why. The executor builds the assistant message, the one with tool_calls in it, from the model's output before any tool runs. Hooks then change tool_input in place. The history keeps the model's original arguments, so the next turn reasons from a call that never happened.

What makes this one sneaky is that nothing looks wrong inside a single run. The tool gets the right input, the booking is correct. It only shows up when the history is replayed, which is exactly what you do in a chat app or any multi-turn agent.

The fix records the effective arguments back into the reported call after each tool runs:

def _record_effective_tool_args(
    report: dict[str, Any] | None, tool_args: dict[str, Any] | None
) -> None:
    if report is None or tool_args is None:
        return
    reported = report["function"]["arguments"]
    try:
        unchanged = json.loads(reported) == tool_args
    except (json.JSONDecodeError, TypeError):
        unchanged = False
    if not unchanged:
        report["function"]["arguments"] = json.dumps(tool_args)
Enter fullscreen mode Exit fullscreen mode

It's called in both the sequential and the parallel execution branches. It only rewrites the arguments when a hook actually changed them. Calls that no hook touched keep the model's exact original string, so the history doesn't fill up with reformatted JSON that means the same thing.

It isn't complete, and I said so in the PR. A separate executor used for planned steps builds its assistant message the same way, and Gemini keeps its own copy of the raw tool call parts. I left both out to keep the change small enough to review.

The pattern: told vs. did

Put next to each other, the two bugs are the same shape. Here are the places a model's beliefs come from, and how each one can go wrong:

Where the model's belief comes from What makes it wrong Example
Environment facts in the system prompt (OS, shell, cwd, date) Computed separately from the code that acts Bug 1
Tool call record in the history Hooks or middleware change the input after it's recorded Bug 2
Tool results Truncation or summarizing that hides the error
Tool descriptions and schemas Schema says optional, code requires it

Two rules cover most of it. Record what ran, not what was requested. And describe the environment using the same code that acts on it.

How to test for it

Both fixes are tested the same way: run the real code path, then assert on what the model will see. Not on the tool, not on internal state, but on the prompt or the history.

For nanocoder, the test sets the platform to win32 and SHELL to a bash path, builds the system prompt, and checks that it names ComSpec. For crewAI, a scripted LLM makes one or two tool calls, a hook rewrites only the first, and the test reads the history that comes back:

@pytest.mark.parametrize("batch_size", [1, 2], ids=["serial", "parallel"])
def test_history_reports_arguments_after_hooks(batch_size):
    @on(InterceptionPoint.PRE_TOOL_CALL)
    def rewrite(context):
        if context.tool_input.get("term") == "0":
            context.tool_input["term"] = "effective"

    agent = Agent(role="Tester", goal="Look up values", backstory="Test hooks",
                  llm=ScriptedLLM(batch_size), tools=[LookupTool()])
    result = agent.kickoff("Look up values")

    reported = [
        call["function"]["arguments"]
        for message in result.messages
        if message.get("tool_calls")
        for call in message["tool_calls"]
    ]
    expected = [json.dumps({"term": "effective"})]
    expected += [json.dumps({"term": str(i)}) for i in range(1, batch_size)]
    assert reported == expected
Enter fullscreen mode Exit fullscreen mode

The parallel case matters. It checks that the rewritten call gets the new arguments and that the untouched one keeps its original string. With the fix reverted, both cases fail, and that's how I know the test is checking the bug and not just the happy path.

A checklist for your own agent

  1. Open your system prompt builder. For every fact about the environment, ask whether it's computed by the same code the tools use. If it isn't, that's a drift waiting to happen.
  2. List every hook, middleware or wrapper that can change tool input. Is the history written before or after them?
  3. Do a replay test. Save messages from one run, start a new run with them, and check that the model's next step uses the effective state.
  4. Run it on Windows once, from Git Bash. A POSIX-looking environment on top of a Windows executor is the classic trap.
  5. When a tool fails, look at what the model actually receives. Is it the real error text, or a summary that hides it?

The context is the model's only window into your system. When that window is wrong, the model is wrong in a confident and consistent way, and it usually looks like a model problem when it's a plumbing problem.

Have you hit a "told vs. did" bug in your own agent? I'm curious which kind shows up most.

Top comments (0)