Skip to main content
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.
This page covers:

How Hooks Work

Hooks integrate directly into greg’s execution engine via Hernex’s AgentHooks interface (onBeforeTurn, onAuthorizeTool, onPostTool, and onShouldStop).

Core Design Guarantees

  1. Non-Blocking Warnings: Unlike strict exit code protocols where any non-zero exit fails the process, greg treats generic non-zero exit codes (like 1 or 127) as non-blocking warnings—logging diagnostics to stderr without crashing your agent turn. Only exit code 2 or an explicit JSON decision: "block" halts execution.
  2. Process Group Isolation: Every shell command hook executes in an isolated process group. When greg exits or a hook exceeds its timeout, child subprocesses and their descendants are forcefully terminated (SIGKILL), preventing runaway background tasks.
  3. 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 the type 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 specify timeoutMs.
  • statusMessage: Optional text displayed on stderr while the hook executes.
  • once: When true, automatically unregisters after running once.
  • env: Extra environment variables with $VAR and ${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. $ARGUMENTS is automatically replaced with the serialized HookInput JSON.
  • appendSystemPrompt: Optional instructions appended to the base safety evaluator system prompt.
  • model: Target model in provider/modelId format (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 specify timeoutMs.

Configuration Files & Locations

Hooks are declared in standard JSON configuration files:

Precedence & Scoping Rules

  1. Project Precedence: Project-level hook matchers execute before global hook matchers.
  2. Project Isolation (disableGlobalHooks): To prevent developer-local global scripts from interfering with a shared project, add "disableGlobalHooks": true to your project’s .greg/config/hooks.json.
  3. Master Kill Switch (disableAllHooks): Set "disableAllHooks": true to suspend all hook execution without deleting the file.

Subprocess Communication Protocol

Command hooks communicate with greg over standard process boundaries:

Standard Input Payload (HookInput)

greg serializes a minimal JSON payload to the hook’s stdin:
For 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 on stdout to 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’s stderr is 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 to stderr and recorded in metrics.

Standard Output Payload (HookOutput)

To mutate parameters or inject text, emit JSON on stdout with exit code 0:
For Start hooks, emit updatedPrompt to rewrite the user’s prompt before the model sees it:
If 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 only Bash.
  • "Write|Edit": Pipe-separated list matching either Write or Edit.
  • "^(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:
If 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:
The script reads the 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:
If any test fails, the agent is prevented from stopping and receives the error message, automatically continuing to fix the broken assertions.

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.