Hooks: Lifecycle Interception & Argument Rewriting with hooks.json
Right after wrapping up the last pitfall in #05 Rules, hooks.json becomes unavoidable.
No matter how forcefully you phrase a Rule, it remains a soft constraint inside the prompt. Once context grows long and tool calls pile up, the model can still forget that trailing “never run git push --force“ instruction—or fire off a bare pytest that floods your context window with thousands of lines of tracebacks.
Antigravity’s Lifecycle Hooks enforce the invariants you cannot leave to model compliance. Rather than negotiating with the model, hooks sit directly on fixed checkpoints in the Agent execution loop: at each stage, the runtime synchronously blocks, pipes the execution context over stdin to your external script, and reads a JSON decision from stdout to allow, hard-block, rewrite tool arguments, or send a finishing Agent back to fix broken tests.
1. Where Hooks Live & How They’re Structured
Hooks are defined in a single hooks.json file at one of three scopes:
| Location | Scope | Typical Use Cases |
|---|---|---|
.agents/hooks.json |
Current project (committable to Git) | Team-wide dangerous command blocking, auto-linting, pre-completion quality gates |
~/.gemini/config/hooks.json |
All workspaces on the machine | Personal audit logging, cross-project safety guardrails |
plugins/<name>/hooks.json |
While the plugin is enabled | Automated guards and validators shipped inside a plugin |
Plugin directory gotcha: At runtime, plugin discovery strictly reads <plugin_dir>/hooks.json at the plugin root. When you run agy plugin import (or install) on a pure Gemini CLI (gemini-extension.json) or Claude Code (.claude-plugin/plugin.json) extension, the installer relocates hooks/hooks.json to the plugin root for you. Antigravity native plugins (containing plugin.json, .antigravity-plugin/plugin.json, .gemini-plugin/plugin.json, or loaded via plugins.json) skip that relocation step—you must place hooks.json directly in the plugin root.
1. File Schema & Merging Rules
The top level of hooks.json is a JSON object where each key is a custom hook name, grouping handlers by lifecycle event:
1 | { |
A few details are easy to miss:
- Quick toggle: Setting
"enabled": falseon a named hook disables its entire handler group—handy during debugging without deleting config. - Multi-source merging: Named hooks from project, user-global, and plugin configs that subscribe to the same event are merged and executed sequentially.
- Execution & timeout: Handlers currently support only
"type": "command"(optional; defaults to"command"). Commands run viash -con Unix andcmd /con Windows, with~expanded to the home directory. Defaulttimeoutis 30 seconds.
2. Working Directory & Plugin Environment Variables (Common Pitfall)
Every hook subprocess starts with its working directory set to the folder containing hooks.json (such as .agents/ or plugins/<name>/), not the project directory the Agent is currently editing. That is why ./scripts/pre-tool-guard.py above resolves cleanly next to hooks.json, while any script that touches repository files or runs git / pytest must read the cwd field from the stdin JSON payload.
For hooks bundled inside a plugin, the runtime injects two environment variables into the subprocess:
PLUGIN_ROOT: Path to the plugin root directory.PLUGIN_DATA: Persistent data directory for the installed plugin (identical to the path provided to the plugin’s MCP servers).
These variables are not template-expanded inside the command string—they are standard subprocess environment variables. Reference bundled scripts with relative paths, and let the shell expand persistent cache paths:
1 | { |
2. The 6 Lifecycle Events & Execution Flow
Antigravity exposes 6 lifecycle events across two structural formats: tool-level events (PreToolUse / PostToolUse) use a Grouped schema requiring a matcher and nested hooks array, while the other 4 loop-level events use a Flat schema containing handler objects directly.

Here is a quick-reference cheat sheet for authoring configs:
| Event | Trigger Timing | Schema & Matcher | Key Input / Output Capabilities |
|---|---|---|---|
SessionStart |
Once when a new session starts | Flat (no matcher) | Common metadata only → return injectSteps to inject startup instructions |
PreInvocation |
Before each model request | Flat (no matcher) | Includes invocationNum/initialNumSteps → injectSteps, terminationBehavior: "terminate" |
PreToolUse |
Before a single tool executes | Grouped (matcher regex) |
Includes toolCall/stepIdx → decision (allow/deny/ask/force_ask), reason, permissionOverrides, overwrite |
PostToolUse |
After a single tool completes | Grouped (matcher regex) |
Includes matching toolCall.id and error on failure → return empty object {} |
PostInvocation |
After the current tool-call round finishes | Flat (no matcher) | Same as PreInvocation → injectSteps, terminationBehavior ("force_continue" / "terminate") |
Stop |
Before the execution loop exits | Flat (no matcher) | Includes executionNum/terminationReason/fullyIdle/continuationActive → decision: "continue" + reason |
Mapping all 6 events onto a single Agent turn makes the interception and continuation paths immediately clear:
flowchart TD
S["SessionStart (New Session)"] --> PRE_INV["PreInvocation (Before Model Call)"]
PRE_INV -->|"terminationBehavior: terminate"| STOP
PRE_INV -->|"Continue (optional injectSteps)"| MODEL["Model Inference: Reply / Tool Calls"]
MODEL -->|"No tool calls (NO_TOOL_CALL)"| STOP["Stop (Pre-Exit Gate)"]
MODEL -->|"Emit tool call"| PRE_TOOL["PreToolUse (matcher regex)"]
PRE_TOOL -->|"deny"| FEEDBACK["Blocked result returned to model"]
PRE_TOOL -->|"allow / ask / force_ask + optional overwrite"| TOOL["Execute Tool (with rewritten args)"]
TOOL --> POST_TOOL["PostToolUse (same toolCall.id + error)"]
FEEDBACK --> POST_INV["PostInvocation (End of Tool Round)"]
POST_TOOL --> POST_INV
POST_INV -->|"terminate"| STOP
POST_INV -->|"Continue / force_continue"| PRE_INV
STOP -->|"continuationActive == true or non-NO_TOOL_CALL"| END["End Turn & Return to User"]
STOP -->|"decision: continue + reason"| PRE_INV
Two lesser-known fields pay off immediately in real workflows:
PreInvocation‘sinjectStepssupports 3 active step types (ephemeralMessageis deprecated and should no longer be used):{"systemMessage": {"systemMessage": "...", "metadata": {...}}}: Persisted into the conversation trajectory. Note that the value must be a nested object, not a plain string. To render Markdown inline for the user without sending it to the model, put the body inmetadata.user_markdownand leavesystemMessageas"".{"userMessage": "..."}: Injects a user message (plain string).{"errorMessage": {"userMessage": "..."}}: Displays an error to the user without sending it to the model. In non-interactive-pmode it marks the turn failed with a non-zero exit code, but it does not halt the loop on its own—pair it with"terminationBehavior": "terminate"to stop immediately.
Stop‘sterminationReasonenum: Derived fromExecutorTerminationReasonwith theEXECUTOR_TERMINATION_REASON_prefix stripped:NO_TOOL_CALL,MAX_INVOCATIONS,MAX_FORCED_INVOCATIONS,MAX_TOKEN_BUDGET_EXCEEDED,ERROR,USER_CANCELED,TERMINAL_STEP_TYPE,TERMINAL_CUSTOM_HOOK, andINJECTED_RESPONSE. Always inspect this field in quality-gate scripts so you never force-continue a turn after the user hitCtrl+C(USER_CANCELED) or an upstreamERRORoccurred.
3. Three Key Details of the Stdin / Stdout Protocol
Hook communication is intentionally minimal: the runtime writes one JSON object to stdin, and your script writes one JSON object to stdout. In practice, three protocol details cause almost all initial bugs.
1. Every Key Is camelCase (protojson Encoding)
Every event payload includes this shared envelope on stdin:
1 | { |
If you have written Claude Code hooks before, muscle memory like .tool_name, .hook_event_name, or .session_id will silently evaluate to null. Antigravity encodes payloads with protojson, so all top-level and envelope keys are camelCase (conversationId, stepIdx, toolCall, hookEventName). The only exception is tool-specific args (such as CommandLine inside run_command), which preserve the tool’s own schema casing.
2. transcriptPath and artifactDirectoryPath Vary by Entry Point
Running an Agent on the same repository from different Antigravity surfaces changes the product directory segment in both paths:
| Entry Point | Product Directory Segment |
|---|---|
agy CLI |
antigravity-cli/ |
| Antigravity 2.0 Desktop App | antigravity/ |
| Antigravity IDE | antigravity-ide/ |
Always read transcriptPath and artifactDirectoryPath directly from stdin instead of hardcoding ~/.gemini/antigravity/....
3. matcher Syntax & Tool Name Derivation
In PreToolUse and PostToolUse, matcher is a regular expression matched against the tool name (derived by stripping the CORTEX_STEP_TYPE_ prefix from the underlying step type and lowercasing it):
"*"or"": Matches every tool."run_command": Exact match for the terminal execution tool."run_command|read_file": Matches either tool."browser_.*": Regex prefix matching all browser tools.
4. Three Production-Ready Hook Scripts (With Local Test Output)
A fast debugging habit saves hours: instead of spinning up a live Agent conversation to test every tweak, pipe mock JSON payloads straight into your script with echo '{...}' | ./script. Verify that stdout is pure valid JSON and diagnostics land cleanly on stderr before wiring the script into .agents/hooks.json.

Recipe 1: PreToolUse Dangerous Command Blocking + overwrite Argument Rewriting
This is a mandatory guardrail in my repositories. One script handles three policies:
- Matches
rm -rf /orgit push --force: returnsdenyand hard-blocks execution. - Matches
git push,kubectl apply, ornpm publish: returnsforce_ask, bypassing any cached “Always Allow” approval so every invocation prompts for explicit confirmation. - Matches a bare
pytestwithout--tb=: returnsallow+overwrite, appending--tb=short -qso giant tracebacks never blow up the context window.
Save as .agents/scripts/pre-tool-guard.py:
1 | #!/usr/bin/env python3 |
Testing all three branches locally over stdin:
1 | # 1) Force push -> deny |
Keep two runtime behaviors in mind whenever you use overwrite:
- Shallow top-level merge: Each key in
overwritereplaces the corresponding top-level key in the tool’sargs. If a top-level field is a nested object, it is replaced wholesale rather than deep-merged—so read the original object fromstdin, merge your edits into it, and return the complete object inoverwrite. - The model is notified of the rewrite: The rewritten call is what actually executes and lands in the trajectory. Because the model remembers its original arguments, Antigravity automatically prepends a notice to the tool result returned to the model listing which argument keys were rewritten by a hook, preventing the model from hallucinating about unexpected output formats.
Recipe 2: PostToolUse Auto-Lint / Format After File Edits
PostToolUse receives the exact same toolCall.id as PreToolUse (ideal for latency or paired-call auditing) plus an error field if the tool failed.
Attached to edit_file|write_file, this script logs and skips failed calls, switches into cwd from the payload to run ruff on .py files, redirects all tool output to stderr (>&2), and prints {} on stdout.
Save as .agents/scripts/post-tool-lint.sh (remember chmod +x):
1 |
|
Verify stdout stays strictly clean across success and failure events:
1 | # Successful tool call |
Recipe 3: Stop Quality Gate + continuationActive Infinite-Loop Guard
The highest-leverage use for a Stop hook is a pre-delivery quality gate: when the model thinks it is done and tries to exit, run a fast unit-test suite. If tests fail, return {"decision": "continue", "reason": "..."}—Antigravity injects reason as a system message and sends the Agent back into the loop to fix the failures.
There is a critical trap here: if the test environment itself is broken or the model cannot fix the failure in one pass, a Stop hook without a circuit breaker traps the Agent in an infinite loop until it burns all the way to MAX_FORCED_INVOCATIONS.
Always add two circuit-breaker checks up front:
- Pass through immediately whenever
terminationReason != "NO_TOOL_CALL"(never override user cancellations, errors, budget limits, or upstream hook terminations). - Pass through immediately whenever
continuationActive == true—this flag flips totrueonce aStophook has already continued the current turn, and staystrueuntil the user sends a new message.
Save as .agents/scripts/stop-test-gate.sh (remember chmod +x):
1 |
|
Verify all three states locally (initial failure intercept, post-continuation circuit break, and user cancellation pass-through):
1 | # 1) First normal stop with failing tests -> block exit and inject reason to continue |
5. Pitfalls, Current Limitations & Differences from Claude Code
Once you deploy these three scripts in real repositories, four hard constraints are worth knowing up front:
- Every hook is synchronous and blocking—there is no async mode
The Agent loop pauses for as long as your script runs, up to the 30-second default timeout. Never wire a fullnpm run buildor a 30-second integration suite intoPostToolUse. Keep per-file formatting (ruff/prettier) within 1–3 seconds, and push heavier verification intoStophooks or dedicated tasks. - Subprocess working directory ≠ Agent working directory
Hooks spawn in the directory containinghooks.json(typically.agents/). Relative paths expectingpackage.jsonorgit statuswill miss the repo root—always extract.cwdfromstdinandcdinto it first. - A single non-JSON line on
stdoutbreaks parsing
One stray debugechoor unredirectedruff/pytest/gitoutput onstdoutcauses Antigravity’s JSON parser to fail. Follow one strict rule: redirect every command and log statement to>&2(stderr) except the final JSON response. - Only
type: "command"is supported today
The official docs explicitly note that HTTP webhook hooks and prompt-based hooks (delegating approval to a smaller model) are not yet supported. If you need an external HTTP call or secondary model check, wrap it inside a shell or Pythoncommandscript and watch thetimeout.
Finally, if you are migrating hooks from Claude Code, watch out for these three structural differences rather than porting from muscle memory:
| Aspect | Antigravity (AGY) | Claude Code |
|---|---|---|
| Config Location | Standalone hooks.json (.agents/, ~/.gemini/config/, or plugin root), grouped under custom top-level hook names with an enabled toggle |
Under the hooks key inside settings.json / settings.local.json |
| Payload Key Casing | Consistent camelCase (protojson: conversationId, hookEventName, toolCall, stepIdx) |
Primarily snake_case (session_id, hook_event_name, tool_name, tool_input) |
| Distinctive Events & Rewriting | Fine-grained PreInvocation / PostInvocation (injectSteps, metadata.user_markdown, force_continue) plus shallow-merge overwrite argument rewriting in PreToolUse |
Focuses on PreToolUse / PostToolUse / UserPromptSubmit / Stop, with different argument-rewriting fields and protocol naming |
Next up in our customization tour, we will unpack MCP external tool integration, lazy loading, and embedded interactive ui:// views in MCP Apps. If you want an advanced production hook pattern for multi-developer repositories—a dual-protocol interceptor using lexical parsing, heredoc stripping, and Python AST inspection to block bash -c / python -c escapes—jump straight to Engineering in Practice #3: Project-Level .agent/ Isolation, Dual-Protocol Hooks & Read-Only DB/Redis Plugins.



















