• AI
  • coding agents
  • automation

Use coding-agent hooks for checks at the right moment

A beginner-friendly guide to Gemini CLI hooks: what they are, why a BeforeTool hook can stop a bad file write, how to build and test a path check step by step, and what hooks cannot enforce.

Imagine you share a kitchen with a helpful but fast-moving roommate. You keep telling them, “Raw meat goes on the bottom shelf only.” Sometimes they remember. Sometimes they do not. A sticky note on the fridge door works better, because it is there at the exact moment they open the door.

AI coding agents have the same problem. An AI coding agent is a program that uses a large language model to read your code, run commands and edit files on its own. During one task it may write dozens of files. A rule written in the prompt (“only write generated code under src/generated/”) is easy for the agent to forget. It is also hard for you to check afterwards.

A hook is the sticky note. It is a small script that the coding tool runs automatically at a fixed moment, such as just before the agent writes a file. The script can look at what the agent is about to do and say “yes” or “no”. Because the check is ordinary code, it gives the same answer every time.

This article builds one such check from start to finish in Gemini CLI, Google’s command-line coding agent. You will learn what each part does, how to test it without the agent, and where hooks stop protecting you. The facts come from the Gemini CLI hooks guide and the hooks reference.

The basic ideas

A few terms appear throughout. Each one is short.

  • Tool call. The agent does not touch your disk directly. It asks the host program to run a named tool, such as write_file, with some arguments. That request is a tool call.
  • Host. The program that runs the agent and its tools. Here it is Gemini CLI.
  • Event. A named moment in the host’s workflow. BeforeTool fires just before a tool runs. AfterTool fires just after.
  • JSON. A plain-text data format made of keys and values, like {"decision": "allow"}.
  • stdin, stdout, stderr. Every command-line program has three standard streams. Standard input (stdin) is what it reads. Standard output (stdout) is its main output. Standard error (stderr) is a second output meant for logs and errors.
  • Exit code. A number a program returns when it finishes. 0 usually means success.
  • Matcher. A pattern in the hook settings that decides which tools the hook applies to. In Gemini CLI it is a regular expression (regex), a small pattern language for matching text. write_file|replace means “the tool named write_file or the tool named replace”.

Why check before the write, not after

Suppose your repository has a rule: generated files must stay under src/generated/. You could check this at two moments.

An AfterTool hook runs after the file is written. It can tell you the agent wrote somewhere wrong. But the file already exists, and you must clean up.

A BeforeTool hook runs before the write. It can refuse the tool call, so the wrong file is never created. The agent receives your reason and can try again with a better path.

So the rule of thumb is simple. Use BeforeTool when you want to prevent an action. Use AfterTool when you only want to observe or report it.

How Gemini CLI talks to a hook

Gemini CLI starts your hook command and sends it a JSON payload on stdin. For BeforeTool, the payload includes tool_name and tool_input. tool_input holds the raw arguments the model produced, for example the file path.

Your hook answers by printing JSON on stdout. To block the call it prints {"decision": "deny", "reason": "..."}. The reference says this reason is sent to the agent as a tool error, so the agent can respond or retry. To let the call through it prints {"decision": "allow"}.

The exit code matters too:

  • 0 means success, and stdout is read as JSON. The reference recommends this for all normal logic.
  • 2 also blocks the tool. In that case the host uses the text on stderr as the reason.
  • Any other code is treated as a non-fatal warning, and the CLI continues.

One strict rule follows from this design. Your script must print nothing on stdout except the final JSON. Any extra text can break the parsing.

Build the path check step by step

You need Node.js (a JavaScript runtime for the command line) and a project folder. All commands below run in a terminal at the project root.

Step 1: Create the hook folder

mkdir -p .gemini/hooks

This creates the folder where project hooks usually live. Nothing is printed if it succeeds.

Step 2: Register the hook in the settings file

Project hooks are configured in .gemini/settings.json. Gemini CLI also reads user settings from ~/.gemini/settings.json and merges the layers, with project settings taking priority. Create or edit the project file with this content:

{
  "hooks": {
    "BeforeTool": [
      {
        "matcher": "write_file|replace",
        "hooks": [
          {
            "name": "generated-only",
            "type": "command",
            "command": "node \"$GEMINI_PROJECT_DIR/.gemini/hooks/generated-only.js\"",
            "timeout": 5000
          }
        ]
      }
    ]
  }
}

What each part does:

  • "BeforeTool" is the event.
  • "matcher" limits the hook to write_file and replace. These are Gemini CLI’s built-in tools for writing a file and editing part of a file. Both take a file_path argument.
  • "type": "command" means “run a shell command”. It is currently the only supported type.
  • "command" is the command to run. GEMINI_PROJECT_DIR is an environment variable the CLI gives every hook. It holds the absolute path of the project root.
  • "timeout" is in milliseconds. If you leave it out, the documented default is 60000 ms, which is 60 seconds. That is long for a check that runs before every write, so 5 seconds is set here.

Step 3: Write the script

Save this as .gemini/hooks/generated-only.js:

#!/usr/bin/env node
// .gemini/hooks/generated-only.js
// BeforeTool hook: allow write_file/replace only inside src/generated/.
const fs = require('fs');
const path = require('path');

const input = JSON.parse(fs.readFileSync(0, 'utf8'));
const root = process.env.GEMINI_PROJECT_DIR || input.cwd;
const allowed = path.resolve(root, 'src/generated');
const target = path.resolve(root, input.tool_input?.file_path ?? '');

// path.relative avoids the prefix bug: src/generated-old is not inside src/generated.
const rel = path.relative(allowed, target);
const inside = rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);

if (!inside) {
  console.error(`blocked write to ${target}`); // logs go to stderr
  console.log(JSON.stringify({
    decision: 'deny',
    reason: `Generated files must be written under src/generated/, not ${path.relative(root, target)}.`,
  }));
} else {
  console.log(JSON.stringify({ decision: 'allow' }));
}
process.exit(0);

What happens, line by line in plain words:

  1. It reads the whole payload from stdin (fs.readFileSync(0) reads file descriptor 0, which is stdin) and parses the JSON.
  2. It finds the project root from GEMINI_PROJECT_DIR, or falls back to the cwd field in the payload.
  3. It turns both the allowed folder and the requested file into absolute paths with path.resolve. This also collapses tricks like src/generated/../app.ts into src/app.ts.
  4. It asks path.relative how to get from the allowed folder to the target. If the answer starts with .., the target is outside.
  5. It prints a log line to stderr and a JSON decision to stdout, then exits with 0.

Why not just check target.startsWith(allowed)? Because the string /repo/src/generated-old/api.ts starts with /repo/src/generated. A prefix check would wrongly allow it.

Step 4: Test the script by hand

You do not need the agent to test the decision logic. You can play the host yourself. Pipe a sample payload into the script, using the same field names as a real BeforeTool call:

echo '{"cwd":"/repo","hook_event_name":"BeforeTool","tool_name":"write_file","tool_input":{"file_path":"src/generated-old/api.ts","content":"x"}}' \
  | GEMINI_PROJECT_DIR=/repo node .gemini/hooks/generated-only.js
echo "exit=$?"

This runs in your terminal. echo prints the JSON, the | (pipe) feeds it to the script’s stdin, and echo "exit=$?" prints the script’s exit code.

Try four representative paths: an allowed file, a sibling folder, a ../ trick and an absolute path. Run with Node.js 24.4.1, they gave these results (stderr lines included):

### src/generated/api.ts
{"decision":"allow"}
exit=0
### src/generated-old/api.ts
blocked write to /repo/src/generated-old/api.ts
{"decision":"deny","reason":"Generated files must be written under src/generated/, not src/generated-old/api.ts."}
exit=0
### src/generated/../app.ts
blocked write to /repo/src/app.ts
{"decision":"deny","reason":"Generated files must be written under src/generated/, not src/app.ts."}
exit=0
### /etc/hosts
blocked write to /etc/hosts
{"decision":"deny","reason":"Generated files must be written under src/generated/, not ../etc/hosts."}
exit=0

Only the file inside src/generated/ is allowed. The other three are denied with a readable reason. Every run exits with 0, so the host will read the JSON.

Step 5: Test it inside the agent

Step 4 tests the script, not the host. I did not run this hook inside Gemini CLI itself. To finish the check yourself:

  1. Open the project in Gemini CLI.
  2. Run /hooks panel. This is the documented command for viewing hooks. Confirm generated-only is listed and enabled.
  3. Ask the agent to create a file such as src/app-generated.ts. Expect the write to be blocked and the agent to receive the reason.
  4. Run git status in a terminal. Expect no new file outside src/generated/.
  5. Ask the agent for a file inside src/generated/. Expect that write to succeed.

If both the blocked case and the allowed case behave as expected, the hook is ready for daily use.

Common mistakes

  • Printing debug text on stdout. A stray console.log("checking...") corrupts the JSON answer. Send logs to stderr with console.error.
  • Checking paths with string prefixes. As shown above, src/generated-old passes a prefix test. Resolve paths and compare them with path.relative.
  • Forgetting the timeout. The default is 60 seconds. A slow or stuck hook delays every matching tool call. Avoid network calls in a hook that runs this often.
  • A matcher that is too narrow. The matcher only covers the tools you name. A run_shell_command call that runs echo > other.ts writes a file without passing through a write_file|replace hook.
  • Ignoring symbolic links. The script does not resolve symbolic links. If a link inside src/generated/ points elsewhere, a write can land outside. Add fs.realpathSync on the existing parent folder, or rely on filesystem permissions.
  • Using an unexpected exit code. Exit codes other than 0 and 2 only produce a warning, and the tool call goes ahead.

What a hook does not guarantee

Hooks belong to a specific host and event. Their names, input fields, error handling and ability to block actions differ between tools and may change between versions. This article follows the Gemini CLI documentation on its main branch in November 2026.

A hook is not a security boundary. It can fail, time out, or be turned off with /hooks disable. For real access limits, use operating-system permissions or the agent’s sandbox. Running the agent in an isolated worktree or sandbox is one way to do that. For code correctness, keep using tests and review.

Treat hooks that come with a project as executable code. Gemini CLI warns that hooks run with your user privileges. It also fingerprints project hooks: if a hook’s name or command changes, for example after git pull, it is treated as a new, untrusted hook, and you are warned before it runs. Read the script before you accept it.

Hooks also solve only one kind of problem: running a check at a fixed moment. If you instead want the agent to load reusable instructions only when they are relevant, agent skills with progressive disclosure are the better fit.

Conclusion

A hook is a small script the coding tool runs at a fixed moment, and a BeforeTool hook is the right place for a check that must happen before an action. Keep it small. Resolve paths properly. Return a JSON deny with a clear reason, and set a short timeout instead of the 60-second default. Test the script by piping sample payloads before you trust the host to call it, then trigger one blocked and one allowed write in the agent. Pair hooks with filesystem permissions and human review for the guarantees they cannot give.

Written by Duy Pham Independent developer. I build the apps on this site and write about how they work.

More about me