Artificial Intelligence

Claude Code Hooks for .NET: dotnet format and dotnet test

Team Nippysoft
• • 11 min read
Claude Code Hooks for .NET: dotnet format and dotnet test

A CLAUDE.md can ask Claude to format the code and run the tests before it finishes. That describes what you would like to happen. A hook is what always happens: Claude Code runs it at a fixed point in the session, whatever the model decides. The Claude Code hooks guide covers that difference, the Stop hook that requires green tests, and formatting every edited file with Prettier.

This post takes those two hooks to a .NET project: dotnet format after every edit to a .cs file, and dotnet test before Claude closes its turn. Both scripts are Node. .NET brings problems the guide does not cover, and the first one raises no error at all.

Before copying them: these hooks run code from the repository, because dotnet format may build it and run its analyzers, and dotnet test builds it and runs the tests. Microsoft warns about it for dotnet format: "Only invoke the tool against trusted code". They also do not replace the checks in the CI/CD pipeline: they run on the machine of whoever uses Claude Code, and only when Claude edits a file or closes a turn.

Format the file Claude just edited

The format hook works like format-on-save in an editor: nobody has to remember to ask for it, and it also applies to what Claude writes.

The PostToolUse event with the Edit|Write matcher runs right after Claude edits or creates a file. The script gets the path in tool_input.file_path, and the hooks reference says it always arrives absolute: "always absolute, with the platform's native separators, so backslashes on Windows".

The dotnet format documentation defines --include as "A space-separated list of relative file or folder paths to include in formatting", and in the lab that relative path was resolved against the folder the command runs from, not against the project or the solution. Given the absolute path, with either kind of slash, dotnet format exited with 0 and left the file alone. A hook that passes the path through as it arrives looks like it works and formats nothing.

The script makes the path relative to the project root, which Claude Code hands it in CLAUDE_PROJECT_DIR, runs dotnet format from that root, and passes the .csproj nearest to the file:

#!/usr/bin/env node
// PostToolUse hook (matcher "Edit|Write"): runs dotnet format on the one .cs file Claude just changed.
// dotnet format reads .editorconfig. --include takes paths relative to the CURRENT folder;
// an absolute path is accepted but formats nothing, so the path is made relative here.
import { readFileSync, readdirSync } from "node:fs";
import { dirname, join, relative, isAbsolute } from "node:path";
import { spawnSync } from "node:child_process";

// Not a block: the edit already happened. This only adds a note for Claude.
function tell(text) {
  process.stdout.write(
    JSON.stringify({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } }),
  );
}

let event;
try {
  event = JSON.parse(readFileSync(0, "utf8"));
} catch {
  process.exit(0);
}

const file = event.tool_input?.file_path ?? "";
if (!file.toLowerCase().endsWith(".cs")) process.exit(0);

const root = process.env.CLAUDE_PROJECT_DIR || event.cwd || process.cwd();
const rel = relative(root, file);
if (!rel || rel.startsWith("..") || isAbsolute(rel)) process.exit(0); // outside the project

// Nearest folder with a .csproj, from the file's folder up to the root and never above it,
// so the root may hold several projects or solutions.
let dir = dirname(file);
let found = [];
for (;;) {
  found = readdirSync(dir).filter((f) => f.toLowerCase().endsWith(".csproj"));
  if (found.length > 0 || relative(root, dir) === "") break;
  dir = dirname(dir);
}
if (found.length === 0) process.exit(0);
// Two or more projects in that folder: the file's project is ambiguous, so skip it and say why.
if (found.length > 1) {
  tell(`dotnet format skipped for ${rel}: ${found.length} .csproj files in ${relative(root, dir) || "."} (${found.join(", ")}).`);
  process.exit(0);
}

const r = spawnSync("dotnet", ["format", join(dir, found[0]), "--no-restore", "--include", rel], {
  cwd: root,
  encoding: "utf8",
});

if (r.status !== 0) {
  const tail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split(/\r?\n/).slice(-15).join("\n");
  tell(`dotnet format failed on ${rel} (exit ${r.status}):\n${tail}`);
}
process.exit(0);

The .csproj is explicit because, without a project, "MSBuild searches the current working directory for a file that has a file extension that ends in proj or sln", and a root with several solutions or projects makes it fail. The search stops at the root: a .cs with no project up to there is skipped. If the nearest folder holds more than one .csproj, the script does not pick one: it skips formatting and tells Claude in additionalContext.

In the lab, a messy .cs came out formatted and the other messy file of the project stayed as it was. A .md, a .cs outside the project and a .cs with no .csproj were skipped in about 50 ms, and a folder with a space in its name did not change the result. If dotnet format fails, the script does not block, because in PostToolUse the tool already ran: it hands the error to Claude in additionalContext.

The price is time. Every edit to a .cs waits for dotnet format: about 5 seconds in the lab, with --no-restore, which saves one second (6.2 s with restore, 5.1 s without). A real solution will take longer; that was not measured. If it hurts, dotnet format with whitespace --folder took 1.7 s and accepts the absolute path, but it only applies whitespace rules, not style or analyzer rules.

A real session shows one more effect: when Claude makes two edits in a row to the same file, the second can fail with "String to replace not found", because the hook already changed the file's spacing and the text Claude had in memory no longer matches. Claude reads the file again and redoes the edit, at the cost of one more step.

Line endings still need pinning. dotnet format takes its rules from .editorconfig ("Preferences will be read from an .editorconfig file, if present"), and without end_of_line the formatted file ended up with four CRLF lines and two LF lines. With end_of_line set to lf or crlf, every line matched.

Don't let Claude finish with failing tests

Stop runs when Claude finishes responding. If the hook returns decision: "block" with a reason, Claude does not stop and gets the reason as an instruction to keep going. The guide already shows that mechanism with npm test; in .NET three things change.

First, dotnet test compiles before it tests ("builds the solution and runs the tests"), so a build error blocks too: in the lab, the reason carried error CS1002: ; expected. With a failing test, the last 40 lines of output hold the test name, the expected value and the actual one.

Second, cost. Stop fires at the end of every response, even when you are only chatting, and the lab suite took about 2.7 s. The script first checks whether git status shows uncommitted changes to files that feed the build: .cs and .csproj files, MSBuild .props and .targets files (such as Directory.Build.props, Directory.Build.targets and Directory.Packages.props), solutions, global.json and .editorconfig. If there are none, it exits in about 85 ms without running anything. Any other kind of file that also feeds the build does not trigger the tests until it is added to the script's watched list. A new file that git does not track yet counts as a change. The comparison is with the last commit, not with what Claude did in that turn: with uncommitted work of your own that has failing tests, the hook also blocks the answer to a plain question.

Third, the cap. Claude Code breaks the loop once Stop hooks have continued the turn eight times in a row, but "The count of consecutive continuations resets each time Claude calls a tool". While it tries to fix the code, Claude edits, and the count goes back to zero; if the fix never comes, that cap barely kicks in. So the script keeps its own counter per turn: it blocks three times and on the fourth try lets Claude finish with a warning. Giving up only guards against the loop: the turn closes with the tests still failing, and the warning shows that to whoever uses Claude Code. STOP_TESTS_MAX changes the number.

#!/usr/bin/env node
// Stop hook: runs dotnet test before Claude ends its turn. If tests fail, it blocks the stop
// and gives Claude the failing output. It gives up after MAX blocks in one turn, because the
// built-in cap of 8 resets every time Claude calls a tool, so a turn that keeps editing
// without fixing the tests could loop for a long time. Giving up guards against the loop;
// the turn then ends with the tests still failing.
import { readFileSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "node:child_process";

const MAX = Number(process.env.STOP_TESTS_MAX ?? 3);

let event;
try {
  event = JSON.parse(readFileSync(0, "utf8"));
} catch {
  process.exit(0);
}

const root = process.env.CLAUDE_PROJECT_DIR || event.cwd || process.cwd();
// One small file per session in the system temp folder holds the blocks of the current turn.
const counter = join(tmpdir(), `stop-tests-${event.session_id ?? "nosession"}.txt`);

// Skip the run when nothing that feeds the build has uncommitted changes (questions, docs, plans):
// C# files, projects, MSBuild files such as Directory.Build.props, Directory.Build.targets and
// Directory.Packages.props, solutions, global.json and .editorconfig.
const watched = ["*.cs", "*.csproj", "*.props", "*.targets", "*.sln", "*.slnx", "*global.json", "*.editorconfig"];
const st = spawnSync("git", ["status", "--porcelain", "--", ...watched], { cwd: root, encoding: "utf8" });
if (st.status === 0 && st.stdout.trim() === "") process.exit(0);

const r = spawnSync("dotnet", ["test", "--no-restore"], { cwd: root, encoding: "utf8" });
if (r.status === 0) {
  rmSync(counter, { force: true });
  process.exit(0);
}

// stop_hook_active is false on the first stop of a turn: start counting again there, so blocks
// left over from an interrupted or resumed session do not carry into a new turn.
let blocks = 0;
if (event.stop_hook_active) {
  try {
    blocks = Number(readFileSync(counter, "utf8")) || 0;
  } catch {}
}
if (blocks >= MAX) {
  rmSync(counter, { force: true });
  process.stdout.write(JSON.stringify({ systemMessage: `dotnet test still fails after ${MAX} tries; stopping anyway.` }));
  process.exit(0);
}
writeFileSync(counter, String(blocks + 1));

const tail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim().split(/\r?\n/).slice(-40).join("\n");
process.stdout.write(
  JSON.stringify({
    decision: "block",
    reason: `dotnet test failed (exit ${r.status}, try ${blocks + 1} of ${MAX}). Fix the code, not the tests, then finish:\n${tail}`,
  }),
);
process.exit(0);
The hook does not judge the code. It makes Claude see the output of dotnet test before closing the turn, and keeps it from closing on red until the tries run out.

Like the one in the guide, the script does not exit when stop_hook_active arrives as true, since that would allow a single retry. It uses the field for something else: it arrives as false on the first Stop of each turn, and the count starts over there. The counter is a small file in the system temp folder, with the session_id in its name, and it is deleted when the tests pass or when the script gives up. If the session is interrupted on red, the file stays, but the next turn, including the first one of a resumed session, starts again at the first try.

Three limits change what to copy. With more than one solution or project in the root, dotnet test with no arguments fails with "MSB1011: Specify which project or solution file to use because this folder contains more than one project or solution file", and the hook blocks on something Claude cannot fix in the code; name the solution in the script, as in dotnet test Lab.slnx --no-restore, which ran green in the lab. If the suite takes longer than the timeout, Claude Code cancels the hook, "discarding the hook's output", and Claude finishes without knowing the tests were red: the timeout has to be longer than the suite. And "Fix the code, not the tests" is text for the model, not a barrier: nothing stops Claude from changing a test.

The configuration

Both scripts go in .claude/hooks/ and are registered in the repository's .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/format-cs.mjs"], "timeout": 60 }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "node", "args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-tests.mjs"], "timeout": 300 }
        ]
      }
    ]
  }
}

It uses exec form: with args, Claude Code launches command without a shell, so Windows needs neither jq nor Git Bash. The reference puts it this way: "The node plus script-path pattern works on every platform because node.exe is a real binary". ${CLAUDE_PROJECT_DIR} is substituted in args and also arrives as an environment variable, which is what the scripts read.

In someone else's repository, read its .claude/settings.json and its scripts before opening it with Claude Code.

Frequently asked questions

Is there a way to run the tests without a script?

The hooks reference has an agent hook on Stop with the prompt "Verify that all unit tests pass. Run the test suite and check the results.": a subagent runs the suite and decides. Agent hooks are experimental, their default timeout is 60 seconds, and that option was not tested for this post.

Verified on November 16, 2026 with Claude Code 2.1.325 and 2.1.326, .NET SDK 10.0.401, Node 22 and the documentation as of that date, on Windows 11. The scripts were tested with fake events on standard input (2.1.325) and in real sessions (2.1.326), on a lab solution with two projects and xUnit tests on VSTest. They were not tested on Linux or macOS, or on a large solution.

References

Subscribe

Get the latest posts delivered right to your inbox.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Comments

No comments yet. Be the first to share your thoughts!

Subscribed!

Registered! A confirmation link has been sent to your email address. If you don't see it, please check your spam folder.

Error

An error occurred. Please try again.

Full code