Hooks let you run custom logic at key points during Agent execution in the Qoder IDE and JetBrains plugin — no source code changes required. Edit a JSON config file to:
The IDE / JB plugin currently supports twelve hook events:
Here is an example that blocks
The hook lifecycle comes down to three steps: write a script, register it in config, and it takes effect automatically.
When the Agent reaches a lifecycle event (such as "before a tool call"), the plugin checks whether any hooks are registered for it:
Start by deciding where to intervene and what to match:
A hook script is a standard shell script that follows this protocol:
Input: JSON event context delivered via
Script template:
Add the script path under the corresponding event in your settings file:
You can test your scripts directly from the terminal by piping JSON input:
Check the stderr output (the block message):
Hook configurations are loaded from the following files. When hooks are defined at multiple levels, they are merged and executed together (listed from lowest to highest priority):
You can define multiple matcher groups under a single event, and each group can contain multiple hook commands.
Qoder IDE supports two sets of tool names — native names and Claude Code-compatible names. You can use either in your matchers; the plugin maps them internally. For example,
Hook scripts receive JSON input via stdin and communicate results through their exit code and stdout. This section covers the input/output format common to all events. For event-specific fields, see Hook Events.
Your hook script receives JSON data via stdin. Every event includes these common fields:
Each event adds its own fields on top of these (see the individual event descriptions). Treat every field as optional — even when a field is declared, a given execution path may not populate it.
Parse the input with
Hooks communicate results through their exit code and stdout.
Exit code determines the basic behavior:
stdout JSON provides fine-grained control for certain events. See each event's description for the supported fields. The IDE attempts to parse stdout as JSON for both exit code 0 and exit code 2 — do not assume that exit-2 stdout is treated as plain text.
Beyond the event-specific fields inside
When a hook script runs, the plugin injects the following environment variables that your script can reference:
Fires when a session starts or resumes. Use it to inject startup context (project conventions, environment info) at the beginning of a session.
Matcher: None.
Extra input fields:
stdout JSON fields (on success):
Fires after the user submits a prompt in the IDE plugin panel, before the Agent begins processing it. Use it for prompt screening, content filtering, or auto-injecting context.
Matcher: None. This event fires for all user input.
Extra input fields:
Blocking the prompt: Exit with code 2. The stderr content is displayed to the user as an error, and the Agent does not process the prompt.
stdout JSON fields (when exit code is 0):
Example: Auto-append project conventions to every prompt
Fires before a tool executes. Can block tool execution. This is the most commonly used hook event — ideal for blocking dangerous commands, validating file paths, or enforcing permissions.
Matcher: Tool name (e.g.
Blocking tool execution: Exit with code 2. The stderr content is returned to the Agent as an error. See the Quick Start for a full example.
stdout JSON fields (when exit code is 0):
Fires when a tool call requires user authorization. Can decide the authorization automatically — use it to auto-approve safe operations or auto-deny policy violations without a user prompt.
Matcher: Tool name.
Extra input fields:
stdout JSON fields (on success):
Fires after a tool executes successfully. Not blockable. Use it for auto-linting, logging, or result analysis.
Matcher: Tool name.
Extra input fields:
stdout JSON fields (when exit code is 0):
Fires when a tool call fails. Not blockable. Use it for error monitoring, retry suggestions, or logging.
Matcher: Tool name.
Extra input fields:
Fires after the Agent completes its response (i.e. the Agent has no more tool calls to make). Can block the Agent from stopping. Use it for quality gates, desktop notifications, logging, task status reports, or Harness self-evolution.
Matcher: None. This event fires whenever the Agent stops.
Extra input fields:
Blocking the Agent from stopping: Exit with code 2. The block reason is injected into the conversation as a user message, and the Agent continues working.
stdout JSON fields (when exit code is 0):
Fires when a sub-agent starts. Not blockable. Use it for sub-agent auditing or injecting sub-agent context.
Matcher: None.
Extra input fields:
stdout JSON fields (on success):
Fires when a sub-agent stops. Not blockable in the IDE. Use it for logging sub-agent results.
Matcher: None.
Extra input fields:
Fires when a session ends. Not blockable — use it for cleanup or session archiving side effects.
Matcher: None.
Extra input fields:
Fires before context compaction. In the IDE this event is for notification and side effects — it cannot block compaction.
Matcher: Trigger method (
Fires when the plugin emits a user-facing notification. Not blockable. Use it to forward notifications to external channels (desktop, IM, etc.).
Matcher: Notification type.
Extra input fields:
stdout JSON fields (on success):
Hook value depends on your role. Here's a quick mapping:
Pain point: You have to manually specify a Skill every time, or forget to load project-specific context.
Solution: Use a
Script
Key points:
Pain point: Users may accidentally include passwords, keys, internal IPs, or personal data in their prompts, risking information leakage.
Solution: Use a
Script
Key points:
Pain point: Many Rules and Skills are configured but actual usage rates are unknown.
Solution: Use the Transcript system +
Script
Transcript auto-recorded metadata includes:
Pain point: Unclear which files the Agent modified in a session and how many times.
Solution: Use a
Script
Advanced usage:
Pain point: No quantitative data on overall Agent usage — can't assess AI-assisted coding efficiency and quality. This includes: what questions users ask, what text the model returns, which tools are called and their results.
Solution: Use a multi-event hook combo to build full-pipeline usage data collection.
Script
Data collection dimensions:
Pain point: The Agent may execute
Script
Key points:
Pain point: The Agent claims the task is done, but tests are failing or issues remain.
Solution: Use a
Script
Key points:
Pain point: Lessons and decisions from each task are scattered in conversation history with no automated sedimentation process.
Solution: Use a
Script
Key points:
Future direction:
Automatically run a linter every time the Agent writes or edits a file.
Script
Config: event
Write to a log file whenever one of the Agent's tool calls fails, making it easier to troubleshoot.
Script
Config: event
Show a system notification when the Agent finishes a task. Great for long-running tasks.
Script
Config: event
The Transcript is a session log file automatically generated by Qoder IDE, located at the path pointed to by
1.
Tool result (
Tool call (
A typical session's Transcript record order:
When a hook does not fire as expected, add debug logging at the very start of the script:
Then trigger an Agent operation and check the log:
Use the JSON captured in Step 1 to test the script outside of Qoder IDE:
Save the following to
Here is a complete configuration with hooks for five commonly used events:
- Block dangerous operations before a tool runs
- Auto-lint after every file write to enforce code style
- Send a desktop notification when the Agent finishes, so you don't have to watch the IDE
Hook capabilities differ per entry point: this page covers the Qoder IDE / JetBrains plugin (12 events,
command and http handler only). See Qoder CLI Hooks for CLI configuration. Config files are shared between the IDE and the CLI, but each entry point only runs the events it supports.Supported Events
The IDE / JB plugin currently supports twelve hook events:
| Event | When It Fires | Blockable |
|---|---|---|
| SessionStart | When a session starts or resumes | No |
| UserPromptSubmit | After the user submits a prompt, before the Agent processes it | Yes |
| PreToolUse | Before a tool executes | Yes |
| PermissionRequest | When a tool requires user authorization | Yes |
| PostToolUse | After a tool executes successfully | No |
| PostToolUseFailure | After a tool execution fails | No |
| SubagentStart | When a sub-agent starts | No |
| SubagentStop | When a sub-agent stops | No |
| Stop | When the Agent completes its response | Yes |
| SessionEnd | When a session ends | No |
| PreCompact | Before context compaction | No |
| Notification | When a user-facing notification is emitted | No |
Quick Start
Here is an example that blocks rm -rf commands:
1
Create the script
2
Add the config
Add the following to
~/.qoder/settings.json:3
Verify it works
Open your IDE and ask the Agent to run a command containing
rm -rf in the Qoder IDE plugin panel. The hook blocks execution and feeds the error message back to the Agent.Use Cases
| Scenario | Event | Description |
|---|---|---|
| Block dangerous commands | PreToolUse | Prevent the Agent from running rm -rf, DROP TABLE, etc. |
| Validate file paths | PreToolUse | Restrict the Agent to creating or editing files only within a designated directory |
| Auto-lint / format | PostToolUse | Run ESLint / Prettier automatically after every file write |
| Audit logging | PostToolUse | Record every tool invocation for security audits |
| Failure alerting | PostToolUseFailure | Send an alert or write an error log when a tool call fails |
| Prompt content screening | UserPromptSubmit | Detect sensitive data (passwords, keys, etc.) in user input |
| Auto-inject context | UserPromptSubmit | Automatically append project conventions or coding standards to every prompt |
| Desktop notification | Stop | Show a system notification when the Agent finishes |
How It Works
The hook lifecycle comes down to three steps: write a script, register it in config, and it takes effect automatically.
When the Agent reaches a lifecycle event (such as "before a tool call"), the plugin checks whether any hooks are registered for it:
- The plugin loads all hook configurations at startup.
- During Agent execution, the plugin encounters a lifecycle event (e.g.
PreToolUse). - The plugin iterates through every hook group registered for that event and evaluates the
matcheragainst the current context. - Hooks with a matching matcher run their shell scripts in order.
- Each script receives event context as JSON via
stdinand returns a decision through its exit code andstdout. - The plugin reads the result and decides what to do next — proceed or block.
Prerequisites
- jq: The example scripts use jq to parse JSON. Install it with
brew install jqon macOS orapt install jqon Linux. - Script permissions: Every hook script must be executable (
chmod +x).
Creating Hooks
1. Decide What You Need: Pick an Event and a Matcher
Start by deciding where to intervene and what to match:
| Requirement | Event | Matcher |
|---|---|---|
| Check before the Agent runs any shell command | PreToolUse | "Bash" |
| Process after the Agent writes or edits a file | PostToolUse | "Write|Edit" |
| Log when any tool call fails | PostToolUseFailure | "Bash" or omit |
| Screen every user prompt | UserPromptSubmit | Omit (matches all) |
| Trigger a notification when the Agent stops | Stop | Omit (matches all) |
| Intercept only MCP tools | PreToolUse | "mcp__.*" |
2. Write the Hook Script
A hook script is a standard shell script that follows this protocol:
Input: JSON event context delivered via stdin.
Output: Determined by the exit code.
3. Register the Script in Your Config
Add the script path under the corresponding event in your settings file:
4. Test and Debug
You can test your scripts directly from the terminal by piping JSON input:
Configuring Hooks
Config File Locations
Hook configurations are loaded from the following files. When hooks are defined at multiple levels, they are merged and executed together (listed from lowest to highest priority):
| Location | Scope | Priority | Shareable | Description |
|---|---|---|---|---|
~/.qoder/settings.json | User-level | 1 (lowest) | No | Personal config, applies to all projects |
.qoder/settings.json | Project-level | 2 | Yes | Commit to Git and share with your team |
.qoder/settings.local.json | Project-level (local) | 3 | No | Gitignored; for your personal dev setup |
The IDE / JB plugin and the CLI share the same config files. Hot reload is not yet supported — restart the IDE after editing hook configurations for changes to take effect.
Config Format
| Field | Required | Description |
|---|---|---|
type | Yes | "command" or "http" |
command | Yes | Shell command or path to the script to run |
timeout | No | Timeout in seconds (defaults to 30) |
matcher | No | Match condition. If omitted, the hook fires on every occurrence of that event |
if | No | Finer per-hook condition, e.g. "ToolName" or "ToolName(arg_pattern)" |
async | No | When true, the hook runs in the background without blocking the current operation |
asyncRewake | No | When true, runs in the background and can wake the model with its result — useful for long-running checks |
statusMessage | No | Custom description shown in the status line while the hook runs |
Matcher Rules
matcher determines when a hook fires. What it matches against depends on the event (see each event's description).
| Pattern | Meaning | Example |
|---|---|---|
Omit or "*" | Match everything | All tools trigger the hook |
| Exact value | Exact match | "Bash" fires only for the Bash tool |
|-separated | Match multiple values | "Write|Edit" fires for Write or Edit |
| Regex | Regex match | "mcp__.*" matches all MCP tools |
Tool Name Mapping
Qoder IDE supports two sets of tool names — native names and Claude Code-compatible names. You can use either in your matchers; the plugin maps them internally. For example, matcher: "Bash" is equivalent to matcher: "run_in_terminal".
| Qoder IDE native name | Compatible name | Description |
|---|---|---|
run_in_terminal | Bash | Execute shell commands |
read_file | Read | Read file contents |
create_file | Write | Create / write a file |
search_replace | Edit | Edit a file |
edit_file | - | Diff / code-block based editing |
get_terminal_output | - | Fetch background terminal output |
delete_file | - | Delete a file |
grep_code | Grep | Search file contents |
search_file | Glob | Match files by name |
list_dir | LS | List a directory |
Agent | Task | Launch a sub-agent (legacy name: task) |
Skill | - | Invoke a skill |
search_web | WebSearch | Web search |
fetch_content | WebFetch | Fetch web page content |
todo_write | TodoWrite | Write a TODO |
ask_user_question | - | Ask the user a question |
search_memory | - | Search memory |
update_memory | - | Update memory |
switch_mode | - | Switch mode |
create_plan | - | Create a plan |
run_preview | - | Preview a web app |
get_problems | - | Read IDE diagnostics |
fetch_rules | - | Load rules |
ImageGen | - | Generate an image |
mcp__<server>__<tool> | same | MCP tools |
Writing Hook Scripts
Hook scripts receive JSON input via stdin and communicate results through their exit code and stdout. This section covers the input/output format common to all events. For event-specific fields, see Hook Events.
Input
Your hook script receives JSON data via stdin. Every event includes these common fields:
| Field | Description | Always Present |
|---|---|---|
session_id | Current session ID | Yes |
cwd | Current working directory | Yes |
hook_event_name | Name of the event that triggered this hook | Yes |
transcript_path | Path to the session context JSONL file | Yes |
request_set_id | ID of the current IDE request round | No |
tool_name | Tool name (tool-related events only) | No |
tool_input | Tool input parameters | No |
tool_response | Tool execution result (PostToolUse only). Currently delivered as a string in the IDE | No |
extra.email | User's Git email | No |
extra.repo | Repository path (group/repo format) | No |
extra.branch | Current branch | No |
extra.request_time | Request time (RFC3339) | No |
extra.response_time | Response time (RFC3339) | No |
extra.full_diff_text | Full diff of the change (PostToolUse of edit tools only) | No |
jq:
Output
Hooks communicate results through their exit code and stdout.
Exit code determines the basic behavior:
| Exit code | Meaning | Behavior |
|---|---|---|
0 | Success | Continue execution; stdout JSON is parsed |
2 | Block | Stop the action; stderr is injected into the conversation (only for blockable events) |
| Other | Error | Non-blocking error; stderr is shown to the user; execution continues |
Common stdout fields
Beyond the event-specific fields inside hookSpecificOutput, the following top-level fields apply across events:
| Field | Description |
|---|---|
systemMessage | A message surfaced to the user |
continueWithPrompt | Whether the Agent should continue |
decision | "block" for a general block decision. Permission decisions use hookSpecificOutput.permissionDecision instead |
reason | Reason for the decision (some events define their own reason field) |
updatedToolOutput | Replaces the tool output |
hookSpecificOutput | Container for event-specific fields (see each event) |
Environment Variables
When a hook script runs, the plugin injects the following environment variables that your script can reference:
| Variable | Description |
|---|---|
QODER_SESSION_ID | Session ID |
QODER_TOOL_NAME | Current tool name |
QODER_CWD | Working directory |
QODER_TRANSCRIPT_PATH | Transcript file path |
QODER_TOOL_INPUT_FILE_PATH | File path the tool operates on (if applicable) |
Hook Events
SessionStart
Fires when a session starts or resumes. Use it to inject startup context (project conventions, environment info) at the beginning of a session.
Matcher: None.
Extra input fields:
| Field | Type | Description |
|---|---|---|
type | string | Session start type. The IDE currently passes "startup" |
model | string | The session's model setting |
UserPromptSubmit
Fires after the user submits a prompt in the IDE plugin panel, before the Agent begins processing it. Use it for prompt screening, content filtering, or auto-injecting context.
Matcher: None. This event fires for all user input.
Extra input fields:
| Field | Type | Description |
|---|---|---|
hookSpecificOutput.hookEventName | string | Fixed to "UserPromptSubmit" |
hookSpecificOutput.additionalContext | string | Additional context injected into the Agent's conversation |
PreToolUse
Fires before a tool executes. Can block tool execution. This is the most commonly used hook event — ideal for blocking dangerous commands, validating file paths, or enforcing permissions.
Matcher: Tool name (e.g. Bash, Write, Edit, Read, Glob, Grep, or MCP tool names like mcp__server__tool).
Extra input fields:
| Field | Type | Description |
|---|---|---|
hookSpecificOutput.hookEventName | string | Fixed to "PreToolUse" |
hookSpecificOutput.permissionDecision | string | "allow" (proceed), "deny" (reject), or "ask" (prompt the user) |
hookSpecificOutput.permissionDecisionReason | string | Reason for the decision, shown to the Agent / user when denying or asking |
hookSpecificOutput.updatedInput | object | Modified tool input parameters (optional; use this to rewrite the tool call) |
hookSpecificOutput.additionalContext | string | Additional context (optional) |
PermissionRequest
Fires when a tool call requires user authorization. Can decide the authorization automatically — use it to auto-approve safe operations or auto-deny policy violations without a user prompt.
Matcher: Tool name.
Extra input fields:
| Field | Type | Description |
|---|---|---|
hookSpecificOutput.permissionDecision | string | "allow" (approve), "deny" (reject), or "ask" (fall back to prompting the user) |
hookSpecificOutput.permissionDecisionReason | string | Reason for the decision |
hookSpecificOutput.updatedInput | object | Modified tool input parameters (optional) |
The IDE and the CLI use different output structures for this event — the CLI expects a nested
decision.behavior object. Do not reuse the same script across both products without adapting the output.PostToolUse
Fires after a tool executes successfully. Not blockable. Use it for auto-linting, logging, or result analysis.
Matcher: Tool name.
Extra input fields:
| Field | Type | Description |
|---|---|---|
hookSpecificOutput.hookEventName | string | Fixed to "PostToolUse" |
hookSpecificOutput.feedback | string | Feedback displayed to the user (e.g. a lint results summary) |
PostToolUseFailure
Fires when a tool call fails. Not blockable. Use it for error monitoring, retry suggestions, or logging.
Matcher: Tool name.
Extra input fields:
| Field | Type | Description |
|---|---|---|
error | string | The error message from the failed tool execution |
is_interrupt | boolean | Whether the failure was caused by an interruption |
Stop
Fires after the Agent completes its response (i.e. the Agent has no more tool calls to make). Can block the Agent from stopping. Use it for quality gates, desktop notifications, logging, task status reports, or Harness self-evolution.
Matcher: None. This event fires whenever the Agent stops.
Extra input fields:
| Field | Type | Description |
|---|---|---|
stop_hook_active | boolean | true when the Agent is retrying after a previous Stop hook block. Your script must check this field and exit 0 when it is true to prevent infinite loops. |
last_assistant_message | string | The Agent's last text response |
| Field | Type | Description |
|---|---|---|
decision | string | "block" (prevent the Agent from stopping and make it continue working) |
reason | string | Reason for blocking; injected into the conversation as a message |
SubagentStart
Fires when a sub-agent starts. Not blockable. Use it for sub-agent auditing or injecting sub-agent context.
Matcher: None.
Extra input fields:
hookSpecificOutput.additionalContext — context injected into the sub-agent's conversation.
SubagentStop
Fires when a sub-agent stops. Not blockable in the IDE. Use it for logging sub-agent results.
Matcher: None.
Extra input fields:
| Field | Type | Description |
|---|---|---|
agent_id | string | Sub-agent ID |
agent_type | string | Sub-agent type |
stop_hook_active | boolean | Whether the stop is being retried after a hook block |
agent_transcript_path | string | Path to the sub-agent's transcript file |
last_assistant_message | string | The sub-agent's last text response |
SessionEnd
Fires when a session ends. Not blockable — use it for cleanup or session archiving side effects.
Matcher: None.
Extra input fields:
Read the end reason from the
reason input field. (Historical matcher metadata used the name exit_reason; scripts should rely on the actual reason field in stdin.)PreCompact
Fires before context compaction. In the IDE this event is for notification and side effects — it cannot block compaction.
Matcher: Trigger method (manual for user-initiated compaction, auto for automatic compaction near the context limit).
Extra input fields:
Notification
Fires when the plugin emits a user-facing notification. Not blockable. Use it to forward notifications to external channels (desktop, IM, etc.).
Matcher: Notification type.
Extra input fields:
hookSpecificOutput.additionalContext.
Things to Keep in Mind
- Timeout handling: Hook scripts have a default timeout of 30 seconds, configurable per hook with the
timeoutfield. If a script times out, it is killed and treated as an allow (proceed). - Error handling: If a script exits with an unexpected code (anything other than 0 or 2), the error message is shown to the user but the Agent continues without interruption.
- Script permissions: Make sure your scripts are executable (
chmod +x). - Config merging: When the same event has hooks defined at multiple config levels, they execute in order from lowest to highest priority. If any hook blocks (exit 2), the remaining hooks for that event are skipped.
- jq dependency: The example scripts rely on
jqto parse JSON. Make sure it is installed on your system (brew install jqon macOS,apt install jqon Linux).
Best Practice Scenarios
Who Should Use Hooks
Hook value depends on your role. Here's a quick mapping:
For Individual Developers
| Scenario | Description | Practice |
|---|---|---|
| Prompt Enhancement | Auto-inject project-specific skills and coding standards — no manual input each time | Scenario 1 |
| Sensitive Data Interception | Prevent passwords, keys, internal IPs from being sent to the model | Scenario 2 |
| Dangerous Command Blocking | Block rm -rf, git push --force, and other destructive commands | Scenario 6 |
| Harness Self-Evolution | Auto-detect reusable lessons at session end and trigger a retrospective | Scenario 8 |
For Teams / Enterprises
| Scenario | Description | Practice |
|---|---|---|
| Rule/Skill Usage Analytics | Track which Rules and Skills fire across the team, assess asset quality | Scenario 3 |
| File Edit Tracking | Record which files the Agent modifies, for change audits and impact analysis | Scenario 4 |
| Global Usage Analytics | Collect conversation content, tool calls, model replies — full pipeline for efficiency analysis | Scenario 5 |
| Safety Controls | Enforce a team-wide dangerous-command blocklist | Scenario 6 |
| Quality Gates | Auto-run build/tests before the Agent finishes; block and fix if they fail | Scenario 7 |
Scenario 1: Prompt Enhancement — Auto-Inject Skills
Pain point: You have to manually specify a Skill every time, or forget to load project-specific context.
Solution: Use a UserPromptSubmit hook to auto-inject a prompt hint guiding the Agent to use a specific Skill.
Config:
.qoder/hooks/inject-skill-hint.sh:
additionalContextis appended to the user prompt as a system-reminder injected into the Agent- Uses
session_id+ temp files for session-level deduplication to avoid injecting the same hint every turn - The script can read project config files for project-specific Skill recommendations
exit 0allows the prompt through;exit 2blocks it (e.g. for non-compliant prompts)
Scenario 2: Sensitive Prompt Blocking
Pain point: Users may accidentally include passwords, keys, internal IPs, or personal data in their prompts, risking information leakage.
Solution: Use a UserPromptSubmit hook to detect sensitive content and block the prompt.
Config:
.qoder/hooks/block-sensitive-prompt.sh:
UserPromptSubmitis a blockable event;exit 2directly prevents the prompt from reaching the Agent- Sensitive patterns support regular expressions for flexible matching (e.g. AWS AKIA prefix, internal IP ranges)
- Consider extracting patterns to a separate config file (e.g.
.qoder/hooks/sensitive-patterns.txt) for team-wide maintenance - For more precise detection, call external tools like
gitleaksortrufflehog
Difference from Scenario 1:Scenario 1 uses
exit 0 + additionalContext for prompt enhancement (injecting context), while this scenario uses exit 2 for prompt blocking (rejecting non-compliant input). Both can coexist under the same UserPromptSubmit event and execute in config order.Scenario 3: Rule/Skill Usage Analytics
Pain point: Many Rules and Skills are configured but actual usage rates are unknown.
Solution: Use the Transcript system + Stop hook to automatically analyze and record Rule/Skill trigger data after each conversation.
Config:
.qoder/hooks/analyze-rule-skill-usage.sh:
- session_meta(rules): All Rules loaded in this session (name, trigger type, file path)
- session_meta(slash_command): Skills used in this session (name, type, file path)
- session_meta(session_info): Session mode (agent/plan) and type
Advanced usage:Write a periodic summary script to read
~/.qoder/stats/ JSONL files and generate Rule/Skill usage reports.Scenario 4: File Edit Tracking
Pain point: Unclear which files the Agent modified in a session and how many times.
Solution: Use a PostToolUse hook matching file-edit tools to log every file change in real time.
Config:
.qoder/hooks/track-file-changes.sh:
- Use
additionalContextto feed change statistics back to the Agent (e.g. "15 files modified in this session") - Integrate with your team's code analytics system to track AI-assisted change volume
Scenario 5: Global Usage Analytics
Pain point: No quantitative data on overall Agent usage — can't assess AI-assisted coding efficiency and quality. This includes: what questions users ask, what text the model returns, which tools are called and their results.
Solution: Use a multi-event hook combo to build full-pipeline usage data collection. UserPromptSubmit captures user questions, PostToolUse captures tool call results, Stop analyzes the complete session summary via Transcript (model replies, tool call distribution, etc.).
Config:
~/.qoder/hooks/usage-tracker.sh:
| Event | Collected Data | Source |
|---|---|---|
UserPromptSubmit | User question (first 200 chars) | prompt field in stdin JSON |
PostToolUse | Tool name + result (first 500 chars) | tool_name and tool_response fields in stdin JSON |
Stop | Full session summary: user questions, model replies, tool call distribution, success/failure rate | JSONL file at transcript_path |
Why analyze via Transcript in Stop?
UserPromptSubmit and PostToolUse only capture data from the current interaction, while the Transcript file at Stop time contains the complete session history — enabling extraction of model reply text, tool call distribution, and success/failure rates in one pass. See Transcript File Format for details.Scenario 6: Safety Controls — Dangerous Command Blocking
Pain point: The Agent may execute rm -rf, git push --force, or other dangerous commands.
Solution: Use a PreToolUse hook matching Bash|run_in_terminal to intercept dangerous commands before execution.
Config:
.qoder/hooks/block-dangerous-commands.sh:
exit 2immediately blocks execution; stderr content is fed back to the Agent as the block reason- The Agent will attempt an alternative (e.g. a safer command) after being blocked
- For richer feedback, return JSON on stdout:
Scenario 7: Quality Gate Before Agent Completion
Pain point: The Agent claims the task is done, but tests are failing or issues remain.
Solution: Use a Stop hook (blockable) to run quality checks before the Agent finishes; block and force the Agent to keep working if checks fail.
Config:
.qoder/hooks/quality-gate.sh:
stop_hook_activeis used to prevent infinite loops (it istruewhen the Agent retries after being blocked)- After a Stop hook blocks, the block reason is injected as a user message and the Agent continues working
- Set a longer
timeout(e.g. 120 seconds) since builds and tests may take time
Scenario 8: Harness Self-Evolution — Automated Knowledge Sedimentation
Pain point: Lessons and decisions from each task are scattered in conversation history with no automated sedimentation process.
Solution: Use a Stop hook to automatically trigger a Harness self-evolution flow, analyzing whether the conversation produced reusable lessons and driving the asset lifecycle.
Config:
.qoder/hooks/harness-evolution.sh:
- Preventing infinite loops (mandatory): Stop hook scripts must check
stop_hook_active. When the Agent retries after being blocked by a Stop hook, this field istrue— exit 0 immediately to avoid an infinite loop - Use
exit 2+decision:"block"to block the Agent from completing and force a retrospective pending-review.jsonllogs sessions for later batch review- Can be combined with a
/retroSkill (custom retrospective skill) to form an auto-detect → remind → sediment closed loop
Hooks currently only support
command and http type handlers (no prompt / agent), so Harness self-evolution has two implementation paths: (A) call an external analysis service, or (B) block the Agent and trigger a retrospective Skill.The hook system plans to support
prompt type and agent type handlers. Once available, Harness self-evolution will upgrade from "script-driven" to "Agent-driven", enabling true end-to-end automated knowledge sedimentation.Scenario 9: Auto-Lint After File Writes
Automatically run a linter every time the Agent writes or edits a file.
Script ${project}/.qoder/hooks/auto-lint.sh:
PostToolUse, matcher Write|Edit, command .qoder/hooks/auto-lint.sh.
Scenario 10: Log Tool Failures
Write to a log file whenever one of the Agent's tool calls fails, making it easier to troubleshoot.
Script ~/.qoder/hooks/log-failure.sh:
PostToolUseFailure, no matcher (matches all tools), command ~/.qoder/hooks/log-failure.sh.
Scenario 11: Desktop Notification on Completion
Show a system notification when the Agent finishes a task. Great for long-running tasks.
Script ~/.qoder/hooks/notify-done.sh (macOS):
Stop, no matcher, command ~/.qoder/hooks/notify-done.sh.
Transcript File Format
The Transcript is a session log file automatically generated by Qoder IDE, located at the path pointed to by transcript_path (e.g. ~/.qoder/projects/<project>/transcript/<session-id>.jsonl). Each line is an independent JSON object appended in chronological order, recording the complete session interaction.
Common Fields Per Line
| Field | Type | Description |
|---|---|---|
type | string | Record type: session_meta / user / assistant / progress |
sessionId | string | Session ID |
uuid | string | Unique ID for this record |
timestamp | string | ISO 8601 timestamp |
cwd | string | Current working directory |
message | object | Message content (present for user/assistant types) |
data | object | Metadata (present for session_meta/progress types) |
Record Types
1. session_meta — Session metadata (first line)
The first line of every Transcript file records the session's basic information:
data.content.mode: Session mode (agent/plan/ask/debug)data.content.session_type: Session type (assistant/inline_chat, etc.)
user — User messages
User messages come in two forms:
User question (message.content is a string):
message.content is an array containing tool_result):
is_error: Whether the tool execution failedtoolUseResult: Shortcut field for the tool result (same ascontent[0].content)
assistant — Model replies
Model reply message.content is always an array containing two element types:
Text reply (type: "text"):
type: "tool_use"):
name: Tool name (e.g.read_file,search_replace,run_in_terminal,Skill)input: Tool call parametersid: Corresponds totool_use_idin the subsequenttool_result
progress — Hook trigger records
Records when hook scripts fire and which commands run:
Session Timeline Example
A typical session's Transcript record order:
Common jq Extraction Commands
Design Principles
| Principle | Description |
|---|---|
| Fail fast | Hook scripts should be lightweight to avoid blocking the Agent's main flow |
| Graceful degradation | Abnormal exit codes (not 0 or 2) do not block the Agent, ensuring fault tolerance |
| Single responsibility | Each script does one thing; combine multiple hooks for complex logic |
| Idempotent design | The same event may fire multiple times; scripts should be idempotent |
| Loop prevention | Stop hooks must check stop_hook_active to prevent infinite retries |
Recommended Hook Combinations
| Goal | Recommended Combination |
|---|---|
| Safety controls | PreToolUse(Bash) dangerous command blocking |
| Quality assurance | Stop quality gate |
| Data-driven insights | UserPromptSubmit + PostToolUse + Stop full-pipeline collection |
| Harness self-evolution | Stop sedimentation detection + UserPromptSubmit Skill guidance |
| Team collaboration | Project-level .qoder/settings.json with unified config, shared via Git |
Debugging Guide
Step 1: Confirm the Hook Fires
When a hook does not fire as expected, add debug logging at the very start of the script:
Troubleshooting:If no output appears, the hook is not firing. Check your config file location, event name, matcher pattern, and script path.
Step 2: Reproduce Locally with Real Input
Use the JSON captured in Step 1 to test the script outside of Qoder IDE:
Tip:Save common test cases as files for repeated validation.
Step 3: Other Debugging Methods
- Check the Transcript:
~/.qoder/projects/<encoded-path>/transcript/<session>.jsonl— parse withjqline by line - Check Hook logs: Search for
[hook]prefix in Qoder IDE logs for execution results and timing - Start simple: First verify the hook fires with a bare
exit 0, then add business logic incrementally - Clean up: Remove debug code (
/tmp/hook-debug.logwrites) after debugging to avoid performance impact
Quick Start Template
Minimal Config
Save the following to ~/.qoder/settings.json (user-level) or <project>/.qoder/settings.json (project-level):