greg features a deterministic, event-driven Lifecycle Hooks system. Hooks allow developers and engineering teams to intercept agent actions, enforce repository security policies, inject domain context, run linters after file edits, mutate tool arguments, and verify turn completion using custom shell scripts or isolated LLM evaluators.
Hooks run automatically as part of the Hernex execution cycle, without requiring custom wrappers or modified agent loops.
For the underlying architectural mechanics of how the Hernex engine processes hooks during turn cycles, see How Greg Works. For general everyday terminal recipes, see Common Workflows.
- How Hooks Work: Event lifecycle sequence and execution boundaries.
- Lifecycle Events:
PreToolUse,PostToolUse,Start, andStop. - Hook Execution Types: Shell
commandhooks vs isolated LLMprompthooks. - Configuration Files & Locations: Project
.greg/config/hooks.jsonvs global~/.greg/config/hooks.json. - Subprocess Communication Protocol: Input payloads, stdout controls, and exit code semantics (
0vs2). - Tool Matchers &
ifFilter Rules: Scoping hooks by tool name and wildcard command/path patterns. - Real-World Recipes: Practical examples for Git guardrails, formatting, prompt injection, and CI validation.
- Disabling & Bypassing Hooks: Managing execution with
--bare,disableGlobalHooks, anddisableAllHooks. - Next Steps: Guided links to deeper topics.
How Hooks Work
Hooks integrate directly intogreg’s execution engine via Hernex’s AgentHooks interface (onBeforeTurn, onAuthorizeTool, onPostTool, and onShouldStop).
Core Design Guarantees
- Non-Blocking Warnings: Unlike strict exit code protocols where any non-zero exit fails the process,
gregtreats generic non-zero exit codes (like1or127) as non-blocking warnings—logging diagnostics tostderrwithout crashing your agent turn. Only exit code 2 or an explicit JSONdecision: "block"halts execution. - Process Group Isolation: Every shell command hook executes in an isolated process group. When
gregexits or a hook exceeds its timeout, child subprocesses and their descendants are forcefully terminated (SIGKILL), preventing runaway background tasks. - No Context Pollution: Prompt-based hooks evaluate constraints in an ephemeral in-memory microkernel using read-only tools (
ReadFile,Glob,Grep). They never write to disk transcripts or pollute your primary session history.
Lifecycle Events
greg fires four deterministic lifecycle events during agent turns:
Hook Execution Types
Hooks are declared using thetype discriminator in hooks.json:
1. command Hooks (Shell Processes)
Spawns a local shell subprocess (bash on Linux/macOS or powershell on Windows). The process receives structured JSON on stdin and communicates decisions via exit codes or JSON on stdout.
command: Executable string or script path.shell: Shell interpreter ("bash"or"powershell", default:"bash").timeout: Wall-clock timeout in seconds (default: 60s). Can also specifytimeoutMs.statusMessage: Optional text displayed onstderrwhile the hook executes.once: Whentrue, automatically unregisters after running once.env: Extra environment variables with$VARand${VAR}interpolation.
2. prompt Hooks (Isolated LLM Evaluators)
Runs a fast, read-only AI evaluation model to verify safety, architecture, or functional correctness.
prompt: Evaluation instruction.$ARGUMENTSis automatically replaced with the serializedHookInputJSON.appendSystemPrompt: Optional instructions appended to the base safety evaluator system prompt.model: Target model inprovider/modelIdformat (defaults to the currently active runtime model).fallbackModels: Ordered fallback models attempted if the primary model fails.timeout: Timeout in seconds (default: 30s). Can also specifytimeoutMs.
Configuration Files & Locations
Hooks are declared in standard JSON configuration files:Precedence & Scoping Rules
- Project Precedence: Project-level hook matchers execute before global hook matchers.
- Project Isolation (
disableGlobalHooks): To prevent developer-local global scripts from interfering with a shared project, add"disableGlobalHooks": trueto your project’s.greg/config/hooks.json. - Master Kill Switch (
disableAllHooks): Set"disableAllHooks": trueto suspend all hook execution without deleting the file.
Subprocess Communication Protocol
Command hooks communicate withgreg over standard process boundaries:
Standard Input Payload (HookInput)
greg serializes a minimal JSON payload to the hook’s stdin:
Start events, the payload includes source and userPrompt instead of tool fields:
source is "startup" on Turn 1 of a brand-new thread; "resume" for resumed threads or any subsequent turn.
In addition to stdin, greg injects the following environment variables:
Subprocess Exit Codes
The child process exit code dictates the runtime outcome:- Exit Code
0(Success): Execution continues. The hook may optionally emit JSON onstdoutto mutate inputs or inject context. - Exit Code
2(Blocking Veto): Explicit veto protocol. Aborts the tool call or prevents turn completion immediately. Any text written to the hook’sstderris passed directly to the model as the blocking explanation. - Any Other Exit Code (e.g.
1,127): Non-blocking warning. The operation is not aborted; the failure is logged tostderrand recorded in metrics.
Standard Output Payload (HookOutput)
To mutate parameters or inject text, emit JSON on stdout with exit code 0:
Start hooks, emit updatedPrompt to rewrite the user’s prompt before the model sees it:
updatedPrompt is an empty or whitespace-only string it is ignored and the original prompt is preserved.
Tool Matchers & if Filter Rules
To prevent executing unnecessary subprocesses on every tool call, matchers and if filters narrow hook execution:
1. Tool Matchers (matcher)
Matched against the tool name (Bash, Write, Edit, Read, Glob, Grep, Lsp, WebFetch, WebSearch):
"*"(or omitted): Matches all tools unconditionally."Bash": Matches onlyBash."Write|Edit": Pipe-separated list matching eitherWriteorEdit."^(Read|Glob)$": Regular expression matching.
2. Argument Filters (if)
The if property uses greg’s permission rule syntax to match tool targets:
Real-World Recipes
Recipe 1: Block Dangerous Git Commands (PreToolUse)
Prevent the agent from accidentally force-pushing or modifying main:
Create .greg/config/hooks.json:
greg attempts git push origin main, the process exits with code 2 and the model receives:
Recipe 2: Auto-Format Code After Edits (PostToolUse)
Automatically format files with Prettier or Biome whenever Write or Edit completes:
Recipe 3: Inject Git Branch Context on Every Prompt (Start)
Automatically inject the current branch name as context before the model processes any prompt:
Recipe 4: Rewrite Prompt to Expand Ticket IDs (Start)
Expand ticket references like PROJ-123 into full task descriptions before the model sees the prompt:
HookInput JSON from stdin, looks up the ticket, and emits:
Recipe 5: Block Prompts on Startup if Environment Is Not Ready (Start)
Prevent agent runs from starting if required secrets or tooling are absent:
Recipe 6: Enforce Verification Tests Before Stopping (Stop)
Prevent the agent from completing its turn until test suites pass:
Recipe 7: AI Security Screening Hook (prompt)
Screen proposed database migrations or file writes with a lightweight LLM prompt hook:
Disabling & Bypassing Hooks
When troubleshooting, benchmarking, or running minimal scripts, you can control hook execution without modifying configuration files:1. Bare Mode (--bare)
The --bare CLI flag completely disables hooks, ambient instruction files (AGENTS.md), and persistent configurations for a single execution:
2. Project Isolation (disableGlobalHooks)
Add to .greg/config/hooks.json to prevent developer-local global scripts from firing in your repository:
3. Kill-Switch (disableAllHooks)
Temporarily disable all hooks in a project or globally:
Next Steps
Now that you know how to build event-driven guardrails and automation scripts:- Common Workflows: Explore real-world recipes for debugging, refactoring, and CI pipelines.
- How Greg Works: Inspect the complete agent execution loop and fail-closed permission engine.
- Managing Threads: Master session branching, checkpoints, and time-travel rollback workflows.