DEV Community

Cover image for What broke when I tested my AI coding setup: 7 gotchas from hooks, PowerShell and permissions
Wolfgang Mitterbucher
Wolfgang Mitterbucher

Posted on Edited on

What broke when I tested my AI coding setup: 7 gotchas from hooks, PowerShell and permissions

I recently published a two-part guide on AI-driven development (AIDD): part 1 covers the building blocks – project instructions, skills, hooks, MCP, memory –, part 2 sets it all up step by step in VS Code on Windows, including PowerShell hooks and a runner that works through a queue of work packages in the background.

Guides like that get copied line by line. So before publishing, I had every script from part 2 run in an isolated test repository – by Claude Code itself, in real sessions rather than dry runs: hooks firing on real tool calls, memory being written, the runner implementing actual work packages and opening (fake) pull requests. Most of it worked. Seven things didn't, or didn't work the way I had assumed.

1. The hook that "blocks" – but doesn't

Claude Code hooks can veto a tool call. The rule is simple: exit code 2 blocks, and whatever the script writes to stderr goes back to the agent as the reason. Any other non-zero code, including 1, is just a non-blocking error – the agent carries on.

My protection hook for generated EF Core migrations ended with exit 2. Registered like this, it never blocked anything:

{ "type": "command", "shell": "powershell",
  "command": "& \"$env:CLAUDE_PROJECT_DIR/.claude/hooks/protect.ps1\"" }
Enter fullscreen mode Exit fullscreen mode

The reason is PowerShell, not Claude Code. When you run a script via -Command and it exits with 2, the PowerShell process still exits with 1 – $LASTEXITCODE inside is 2, but that is not what the caller sees. I checked both Windows PowerShell 5.1 and PowerShell 7.7: exit code 1 in both. The fix is one statement at the end of the command:

"command": "& \"$env:CLAUDE_PROJECT_DIR/.claude/hooks/protect.ps1\"; exit $LASTEXITCODE"
Enter fullscreen mode Exit fullscreen mode

With that, the hook returns 2, the write to Migrations/ is blocked, and the agent receives the message from stderr. If you write hooks in PowerShell, test the exit code from the outside – a hook that silently doesn't block is worse than no hook, because you think you're protected.

2. Mojibake in the agent's context

A SessionStart hook prints the last session handoff, so a new session starts where the previous one stopped. Whatever such a hook writes to stdout goes straight into the context. My handoffs are in German, and the session transcript showed what the agent actually received:

SessionStart:startup hook success: Letzte Sitzungs�bergabe …
Enter fullscreen mode Exit fullscreen mode

A probe hook made it obvious. It printed äöü ß and its own console encoding – the transcript recorded ��� � and ibm850. Claude Code reads hook output as UTF-8; PowerShell on Windows writes in the old console code page. Any non-ASCII character is affected – German umlauts, accented names, typographic dashes. The fix goes at the top of every hook script:

$utf8 = [Text.UTF8Encoding]::new($false)
[Console]::InputEncoding  = $utf8   # paths in the JSON on stdin
[Console]::OutputEncoding = $utf8   # what the agent reads
Enter fullscreen mode Exit fullscreen mode

And when the script reads files, Get-Content -Encoding UTF8 – Windows PowerShell 5.1 otherwise assumes ANSI for files without a BOM. A side finding from the same probe: with "shell": "powershell", Claude Code ran the hook in PowerShell 7 because it was installed, not in Windows PowerShell 5.1. Write hooks that work in both.

One more encoding trap, pointed out by a reader in the comments: Windows PowerShell 5.1 reads a .ps1 file without BOM as ANSI, so non-ASCII characters in the script itself get garbled, and a typographic dash inside a double-quoted string is even a syntax error. Claude Code falls back to 5.1 when PowerShell 7 isn't installed. Save hook scripts as UTF-8 with BOM, or keep them ASCII-only.

3. Your allow rules don't apply in a folder you haven't trusted

The project's .claude/settings.json allowed dotnet build, dotnet test and dotnet format without prompting. In my headless runs, Claude Code printed this instead:

Ignoring 3 permissions.allow entries from .claude/settings.json: this workspace
has not been trusted. Run Claude Code interactively here once and accept the
trust dialog …
Enter fullscreen mode Exit fullscreen mode

That is a deliberate safety feature – a cloned repository must not be able to grant itself permissions. Deny rules and hooks still apply in an untrusted folder; allow rules don't.

Update: the first version of this section claimed that every new git worktree is untrusted. That was wrong – a reader's question in the comments made me check. According to the docs, a worktree inherits trust from the main checkout. My test repository was a fresh copy nobody had ever trusted, which is why the warning appeared there. Checked against my real, trusted repository, though, the worktree still ignored the allow rules. The warning names the key it looks up:

… or set projects["C:/Entwicklung/…/mitterbucher-website"].hasTrustDialogAccepted: true in …\.claude.json.
Enter fullscreen mode Exit fullscreen mode

My trust entry is stored under c:/Entwicklung/… – only the case of the drive letter differs, so on Windows the inheritance can silently fail. My runner creates one worktree per work package and passes the tool list on the command line. That works regardless of trust and keeps the permissions for unattended runs in the runner script rather than in a file inside the repository the agent works on:

claude -p 'Implement the work package from the input completely. Commit in small steps.' `
    --permission-mode acceptEdits `
    --allowedTools 'Read,Edit,Write,Grep,Glob,Bash(dotnet build *),Bash(dotnet test *),Bash(git add *),Bash(git commit *)' `
    --max-turns 80 --max-budget-usd 5 --output-format json
Enter fullscreen mode Exit fullscreen mode

4. Path-scoped rules are lazy – and my first test was wrong

Rules in .claude/rules/ can carry a paths filter in their front matter:

---
paths:
  - "tests/**/*.cs"
---
# Tests
- Test names: Method_Situation_Expectation.
Enter fullscreen mode Exit fullscreen mode

My first test said they didn't work at all: after reading a test file, the agent knew nothing about the naming convention. Even an unconditional rule without paths was missing. The debug log (claude --debug) explained it – one line per file: "not loading … CLAUDE.md: it … is in a session's scratchpad". I had built the test repository inside Claude Code's own temporary scratch folder, and Claude Code deliberately doesn't load project instructions from there.

Moved to a normal folder, everything behaved as documented:

Session CLAUDE.md rule without paths rule with paths
no file read loaded loaded not loaded
after reading tests/…/SmokeTests.cs loaded loaded loaded

Two lessons: path-scoped rules only appear when the agent reads or edits a matching file – so "the agent ignores my rule" may just mean it hasn't touched such a file yet. And when a test of your harness fails, read the debug log before you believe the result.

Update: a reader asked whether a path-scoped rule reaches the agent before its first edit, so I tested it with a hook on InstructionsLoaded, which logs when each rule loads and which file triggered it. For an existing file, yes: Claude Code only edits files that have been read in the session, and the read already loads the rule. For a new file, no: the rule arrives with the result of the first Write, so the first version is written without it. The agent fixed the file right afterwards in my runs, but nothing guarantees that. Anything that must hold from the first line belongs in a rule without paths or in a deterministic check – an analyzer, a test or a hook.

5. One character that silently disabled a permission rule

This one wasn't in the guide but in my own settings. I had allowed ssh commands to my server with a rule like this (host and key changed here):

"allow": [ "Bash(ssh -i * deploy@203.0.113.10:*)" ]
Enter fullscreen mode Exit fullscreen mode

It never matched. The :* suffix is an alternative spelling of a trailing wildcard – but only at the very end and only if it is the rule's only wildcard. With a * in the middle, the colon is taken literally, so the rule required deploy@203.0.113.10: followed by something. Claude Code does log a warning about it at startup – I only found it in the debug log.

Fixing the syntax exposed a second problem: the * in the middle matches any text, including extra ssh options such as -o ProxyCommand=… – which makes ssh run an arbitrary local program. So the key path is now pinned, the wildcard sits only at the end, and two deny rules close the remaining gap:

"allow": [ "Bash(ssh -i ~/.ssh/id_deploy deploy@203.0.113.10 *)" ],
"deny":  [ "Bash(ssh *ProxyCommand*)", "Bash(ssh *proxycommand*)",
           "Bash(ssh *LocalCommand*)", "Bash(ssh *localcommand*)" ]
Enter fullscreen mode Exit fullscreen mode

Both spellings are there because ssh treats option names case-insensitively, while permission rules are case-sensitive text patterns. I tested it without touching the server: -o ProxyCommand=echo is denied in both spellings, while ssh … -V (prints the version, opens no connection) still runs – proof that the allow rule matches and the denials come from the deny rules.

6. Two Claude Code installations on one machine

claude --version in the terminal said 2.1.202. The VS Code extension was running 2.1.331. An old global npm installation was on the PATH, while the extension ships its own binary – so terminal and editor were running different versions with different fixes and behaviour, and nothing told me.

The fix: remove the npm package and use the native installer, which updates itself:

npm uninstall -g @anthropic-ai/claude-code
irm https://claude.ai/install.ps1 | iex
Enter fullscreen mode Exit fullscreen mode

The installer put claude.exe into ~\.local\bin – and warned that this folder was not on the PATH. Without that step, the terminal has no claude at all:

$bin = Join-Path $HOME '.local\bin'
$user = [Environment]::GetEnvironmentVariable('Path', 'User')
if (($user -split ';') -notcontains $bin) {
    [Environment]::SetEnvironmentVariable('Path', $user.TrimEnd(';') + ";$bin", 'User')
}
Enter fullscreen mode Exit fullscreen mode

Open terminals – including VS Code's integrated one – only see the change after a restart.

7. One from the docs: shortcuts Windows keeps for itself

Not a test failure, but something I noticed while checking every detail against the documentation: the VS Code extension's shortcuts for "Focus Input" (Ctrl+Esc) and "Open in New Tab" (Ctrl+Shift+Esc) collide with the Windows shortcuts for the Start menu and Task Manager. On Windows, rebind those two commands in VS Code's keyboard shortcuts. Alt+K – insert the current selection as an @file#lines reference – works fine and is the one I use most.

What worked: the background runner

The part I was most curious about worked on the first run. The runner is a PowerShell loop that takes Markdown work packages from an inbox folder, creates a git worktree per package, lets claude -p implement it, runs dotnet test itself and opens a draft pull request only if the tests are green. The test had two packages – a real one (volume discounts with a fixed interface and permitted paths) and a control package with a deliberately failing test:

Check Result
discount package implemented 3 commits, 3 policy classes + tests, only in the permitted paths
verdict independent dotnet test green → pushed, draft PR opened
control package with red test moved to failed, not pushed, worktree kept for analysis
time about 3 minutes for both
cost from total_cost_usd about 0.80 US dollars for the real package, 0.30–0.35 for the control package, at API prices
all checks 11 of 11, for the German and the English version of the script

The one design decision I'd recommend regardless of tooling: the agent never decides whether it is done. It may build, test and commit – pushing, the test verdict and the pull request belong to the script, and the merge belongs to a human.

Takeaway

None of these issues would have shown up by reading the scripts. Each one needed a real run and a look at what actually arrived – the exit code seen from outside, the bytes in the transcript, the debug log. Treat your AI harness like any other code: version it, test it, and don't trust a check you haven't seen fail.

The complete setup – directory layout for rules and memory, all hook scripts, the runner, VS Code tasks and the security notes – is in the guide:

I'd like to hear which gotchas you ran into with your own agent setup – especially on Windows.

Top comments (18)

Collapse
 
userxnom profile image
Abdullah Naseer •

Gotcha 3 is the one with the widest blast radius for anyone copying the runner: every new worktree is an untrusted folder, so the allow rules in .claude/settings.json are effectively dead for exactly the flow the runner exists to automate. How do you handle that in practice — trust each worktree folder from the runner, or pass the tool list on the command line every time? Trusting programmatically feels like it quietly defeats the safety feature you describe (a cloned repo must not grant itself permissions), so I'm curious where you landed. And on gotcha 5, the ProxyCommand escape is a nasty one — does your deny rule also catch the no-space form, ssh -oProxyCommand=..., or does the permission matcher need the space to match?

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

Good questions, and the first one made me dig further, so thanks.

Trust: According to the docs, trust for a worktree is keyed on the main checkout's root, so worktrees of a repo you've trusted shouldn't need trusting on their own. In my runner test the main checkout was a fresh copy nobody had ever trusted, so "every new worktree is untrusted" was an overgeneralisation on my part. I'll correct it. There is a Windows catch, though: checked against my real, trusted repo, the worktree still ignored the allow rules. The warning asks for projects["C:/…/repo"], while my trust entry is stored under c:/…/repo. Only the case of the drive letter differs.

In practice I keep passing the tool list on the command line. It works regardless of trust, and the permissions for unattended runs live in the runner script rather than in a file inside the repo the agent works on. Trusting folders programmatically is what I'd avoid, for exactly the reason you give.

ssh: The rule is Bash(ssh ProxyCommand), so no space is needed before the option. I tested -oProxyCommand=echo, -oproxycommand=echo and -o "ProxyCommand echo", and all three were denied. Not covered: other casings such as PROXYCOMMAND, and a config file passed with -F.

Collapse
 
halfcycle profile image
Halfcycle •

"The agent never decides whether it is done" is the rule we built Halfcycle on too. Seven gotchas from testing one guide is the real cost of a hand-built harness: every hook and rule is code you now maintain. Halfcycle is that harness ready made inside Claude Code or Codex, with reviewers that didn't write the code and a person signing off each phase, and it keeps improving without you chasing the next guide. Try npx halfcycle on one of your work packages and compare it with the runner.

Collapse
 
analista_83 profile image
Sammi De Blas •

The exit code 2 versus exit code 1 trap explains why a hook that looks like it blocks does nothing. The agent keeps going and the author only sees the rule in the config, never the veto. Worth adding to the checklist: test the hook by triggering the tool call it should refuse, not by reading the JSON.

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

Agreed. In my case it took two checks: piping a tool call for a protected path into the hook to see the exit code from outside, and a real session in which the agent tried to write to Migrations/. Only the second one shows that the veto actually reaches the agent, including the message from stderr.

Collapse
 
fxdgif profile image
Fred 🍓 •

Gotcha 2 has a twin on the input side that bit me: not the hook's output, the script file itself. Windows PowerShell 5.1 reads a .ps1 without a BOM as ANSI, so one typographic dash in a comment was enough to break parsing of my notification hook, and it failed silently, like your exit code case.

Your side finding makes this worse: with "shell": "powershell" you got PowerShell 7, which reads BOM-less files as UTF-8. So a hook can work on the machine where it was written and break on one that only has 5.1. Since then I keep hook scripts ASCII-only (or save them as UTF-8 with BOM) and run them once with powershell.exe -File explicitly before shipping.

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

Thanks, good catch – I checked it before replying. Both parts hold up: Windows PowerShell 5.1 reads a .ps1 without BOM as ANSI (Windows-1252 here), PowerShell 7 reads it as UTF-8. And the fallback is real: the docs only say "via PowerShell", but the current CLI looks for pwsh first and falls back to System32\WindowsPowerShell\v1.0\powershell.exe if it finds none.

One detail differed in my test: a typographic dash in a comment didn't break parsing in 5.1, it just turned into mojibake inside the comment. It broke as soon as the dash was in a double-quoted string: the dash's UTF-8 bytes read as Windows-1252 become –, the last character is a typographic quote, and PowerShell treats typographic quotes as real ones – so the string ends early and the parser reports a missing terminator. Was your dash inside a string, by any chance?

It applies to my guide as well: the English hook scripts only have non-ASCII characters in comments, but the German SessionStart hook prints an umlaut, which 5.1 would garble on the way in despite the output fix from gotcha 2. I'll add your advice to the guide: save hook scripts as UTF-8 with BOM, or keep them ASCII-only.

Collapse
 
heinrichneb profile image
Heinrich Neb •

One more for the worktree-per-package runner, since it bit me twice. To skip the install step, my worktrees had their node_modules as a junction pointing at the main checkout. On Windows, git worktree remove --force follows the junction and deletes the target. The first time the main checkout lost 175 of 557 packages, the second time a whole node_modules was empty. Now each junction is removed on its own first (cmd /c rmdir takes only the link), the script checks that the path is gone, and only then runs git worktree remove.

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

Thanks for sharing, that's a nasty one, and removing the junction first, checking, then removing the worktree is a sound order. I tried to reproduce it with Git 2.54.0.windows.1: git worktree remove, with and without --force, didn't follow the junction, and the target stayed intact. It didn't remove the worktree either, though: it unregistered it, left the folder with only the junction inside and still exited with 0. Deleting that leftover with Remove-Item -Recurse (PowerShell 5.1 and 7) or rmdir /s /q didn't touch the target in my test. Which Git version were you on? Either way, checking that the folder is really gone, as you do, catches both cases.

Collapse
 
jacksonxly profile image
Jackson Ly •

A Stop hook of mine was registered with "async": true in settings.json. I wanted it to return {"decision":"block"} when a reply ended without a status line, so the session would add one, and an async hook can't do that. The docs say decision and continue have no effect there, because the action they'd control has already finished. It still ran after every reply, so nothing looked broken. My agent noticed the flag when it read the existing hook before building on it, and the hook runs synchronously now.

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

Good one – and a nice example of why reading before building pays off. Async is the right mode for hooks that only observe: the InstructionsLoaded hook I used to test path-scoped rules (see my reply to dosaygo) runs asynchronously anyway and can't block by design. For a hook whose whole point is a decision, async quietly turns it into a logger. Same pattern as the exit-code trap: it runs, nothing looks broken, and the veto never happens.

Collapse
 
crisstiank profile image
Cristian K •

The exit code 2 vs 1 finding is the one worth copying: a hook that fails open looks identical to one that works until you test it from outside. Running the hook with a deliberately bad input and checking that the tool call is actually blocked seems like a good smoke test to keep for any guard hook, and it also catches the same failure in other shells.

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

Thanks! That's exactly how the bug showed up: pipe a tool call for a protected path into the hook the same way Claude Code runs it, then check for exit code 2 and the message on stderr. Worth keeping as a smoke test next to every guard hook.

Collapse
 
kartik-nvjk profile image
Kartik N V J K •

The terminal on 2.1.202 and the extension on 2.1.331 with nothing telling you is the gotcha I'd worry about most, since a hook test that passed in one says little about the other. With the extension still shipping its own binary next to the native installer's claude.exe, can the two drift apart again, or do they update together now?

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher •

They can, but only briefly now. The extension still ships its own claude.exe inside its extension folder and updates through the VS Code Marketplace, while the native install updates itself in the background – two update channels, no shared binary. Earlier today, when I filed a GitHub issue, the terminal was on 2.1.332 and the extension on 2.1.331; now both are on 2.1.332. A one-patch gap that closes on its own is fine, unlike the jump from 2.1.202 to 2.1.331 that the stalled npm install had piled up. When a hook behaves differently in the terminal and in the editor, my first check is now claude --version against the extension version.

Collapse
 
dosaygo profile image
DOSAYGO •

How do you test that a path-scoped rule reaches the agent before its first edit, especially when the task has not yet opened a matching file?

Collapse
 
wolfgang_mitterbucher profile image
Wolfgang Mitterbucher • • Edited

Good question – I hadn't tested that case, so I did now (Claude Code 2.1.332, headless, throwaway repo).

The setup: a rule .claude/rules/tests.md with paths: ["tests/**/*.cs"] whose first instruction is a marker – every file under tests/ starts with // rule:tests-v1 – so the rule's effect shows up in the output. To see when it loads, I logged three hook events to a file with timestamps, passed in via --settings so the project settings stay untouched: PreToolUse and PostToolUse for Read|Write|Edit, and InstructionsLoaded. The latter is documented for exactly this: it fires for lazily loaded rules with load_reason: "path_glob_match", the globs and the trigger_file_path.

Two cases, two different answers.

New file, nothing read before: the rule does not reach the first write. The order was:

PreToolUse          Write  tests/…/PriceTests.cs   first line: using Xunit;
PostToolUse         Write
InstructionsLoaded  tests.md  path_glob_match  trigger: …/PriceTests.cs
PreToolUse          Edit   first line: // rule:tests-v1
Enter fullscreen mode Exit fullscreen mode

The rule arrives together with the result of the Write, and the agent then fixed the file in a follow-up Edit – in both runs. So the end result was right, but the first version of the file was written without the rule, and nothing guarantees the correction.

Existing file: here the rule is in place before the first edit. The agent read the file first even though I asked it not to – the Edit tool only works on files read in the session – and that Read triggered the rule. The first Edit already contained the marker.

My takeaway: a path-scoped rule is reliable for files the agent reads or changes, not for the first version of a new file. If a convention has to hold from the first line, put it in a rule without paths (loaded at session start), or better, enforce it with something deterministic – an analyzer, a test or a hook that checks the result. The rule tells the agent what's expected; the check makes sure it happened.

Thanks for asking – I've added this to gotcha 4 and to the guide.

Collapse
 
dosaygo profile image
DOSAYGO •

Thanks for the detail on testing InstructionsLoaded against PreToolUse and showing that a path-scoped rule fires on Read before editing an existing file but arrives after the first Write on a brand-new file, I'm building AI Lint as a session-start pre-flight checklist (CHECKLIST.md) with language doctrine and explicit architecture rejects so those first-line rules are loaded before any new file is written: ai-lint.dosaygo.com/go/forum-20261...