> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_15_oh-my-opencode_deep_dive/15.5_hook_system.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 15.5 Hook System (53 Hooks in Detail)

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-17

***

The Hook system of oh-my-opencode is one of its most sophisticated subsystems. The 53 Hooks form a dense "safety net" that covers every aspect of Agent behavior -- from context window management to error recovery, from continuous task execution to Agent behavior correction.

## 15.5.1 Hook Classification

The 53 Hooks can be categorized into 8 major groups:

### Context Injection (4 Hooks)

| Hook                          | Function                                                                                        |
| ----------------------------- | ----------------------------------------------------------------------------------------------- |
| `directory-agents-injector`   | Injects the project's `AGENTS.md` file content into Agent messages                              |
| `directory-readme-injector`   | Injects the project's `README.md` into the Agent context                                        |
| `rules-injector`              | Injects rule files from the `.opencode/rules/` directory                                        |
| `compaction-context-injector` | Injects critical context after context compaction (prevents information loss due to compaction) |

The core idea behind these Hooks is: **automatically provide project-specific context information to the Agent**, eliminating the need for users to manually paste it each time.

### Error Recovery (4 Hooks)

| Hook                                      | Function                                                           |
| ----------------------------------------- | ------------------------------------------------------------------ |
| `edit-error-recovery`                     | Injects recovery instructions when the edit tool fails             |
| `json-error-recovery`                     | Injects correction instructions on JSON parsing errors             |
| `anthropic-context-window-limit-recovery` | Automatic recovery when the Anthropic API context window overflows |
| `session-recovery`                        | Recovery mechanism for abnormal session interruptions              |

### Agent Management (3 Hooks)

| Hook                        | Function                                                                   |
| --------------------------- | -------------------------------------------------------------------------- |
| `agent-usage-reminder`      | Reminds the Agent to correctly use delegation protocols and tools          |
| `category-skill-reminder`   | Reminds the Agent to select the correct Category and Skill when delegating |
| `unstable-agent-babysitter` | Monitors unstable sub-Agents and intervenes on timeout or anomalies        |

### Session Management (4 Hooks)

| Hook                        | Function                                                                     |
| --------------------------- | ---------------------------------------------------------------------------- |
| `context-window-monitor`    | Monitors context window usage and issues warnings                            |
| `preemptive-compaction`     | Preemptively triggers compaction when the context window approaches capacity |
| `compaction-todo-preserver` | Preserves Todo state during compaction                                       |
| `session-notification`      | Notifications for session state changes                                      |

### Output Control (3 Hooks)

| Hook                       | Function                                              |
| -------------------------- | ----------------------------------------------------- |
| `tool-output-truncator`    | Truncates excessively long tool output to save tokens |
| `thinking-block-validator` | Validates the format of thinking blocks               |
| `think-mode`               | Controls enabling/disabling of extended thinking mode |

### Task Management (4 Hooks)

| Hook                         | Function                                                        |
| ---------------------------- | --------------------------------------------------------------- |
| `todo-continuation-enforcer` | Forces the Agent to continue executing incomplete Todo tasks    |
| `task-reminder`              | Reminds the Agent of the current task's status and requirements |
| `task-resume-info`           | Provides context information needed for task resumption         |
| `tasks-todowrite-disabler`   | Disables the TodoWrite tool in specific scenarios               |

### Automation (4 Hooks)

| Hook                      | Function                                                      |
| ------------------------- | ------------------------------------------------------------- |
| `auto-slash-command`      | Automatically detects and executes slash commands             |
| `ralph-loop`              | Self-driven continuous work loop                              |
| `start-work`              | Launches workflow from a Prometheus plan                      |
| `stop-continuation-guard` | Prevents accidental termination of the continuation mechanism |

### Environment Adaptation (2 Hooks)

| Hook                       | Function                                            |
| -------------------------- | --------------------------------------------------- |
| `non-interactive-env`      | Adaptation for non-interactive environments (CI/CD) |
| `interactive-bash-session` | Management of interactive Bash sessions             |

### Miscellaneous

| Hook                           | Function                                              |
| ------------------------------ | ----------------------------------------------------- |
| `keyword-detector`             | Detects keywords in user messages (e.g., "ultrawork") |
| `comment-checker`              | Checks for excessive comments in AI-generated code    |
| `hashline-read-enhancer`       | Appends line number hashes to Read tool output        |
| `write-existing-file-guard`    | Prevents accidental overwriting of existing files     |
| `question-label-truncator`     | Truncates overly long question labels                 |
| `background-notification`      | Notification on background task completion            |
| `delegate-task-retry`          | Retry logic for failed delegated tasks                |
| `anthropic-effort`             | Anthropic API effort level injection                  |
| `prometheus-md-only`           | Restricts Prometheus to editing only `.md` files      |
| `sisyphus-junior-notepad`      | Notepad functionality for Sisyphus Junior             |
| `atlas`                        | Special handling for the Atlas Agent                  |
| `claude-code-hooks`            | Hooks for the Claude Code compatibility layer         |
| `auto-update-checker`          | Automatic update checking                             |
| `startup-toast`                | Startup notification                                  |
| `empty-task-response-detector` | Detects empty task responses                          |

## 15.5.2 Core Hook Implementation Analysis

### `preemptive-compaction`: Preemptive Context Compaction

This is one of the most critical Hooks in oh-my-opencode. It solves a fundamental problem: when the Agent's context window is nearly full, failure to compact in time will cause the next API call to fail.

```typescript
// oh-my-opencode/src/hooks/preemptive-compaction.ts
const PREEMPTIVE_COMPACTION_THRESHOLD = 0.78  // Triggered at 78% usage

export function createPreemptiveCompactionHook(ctx, modelCacheState) {
  const compactionInProgress = new Set<string>()  // Sessions currently being compacted
  const compactedSessions = new Set<string>()      // Sessions already compacted
  const tokenCache = new Map<string, CachedCompactionState>()  // Token usage cache

  // Hook point: check after each tool execution
  const toolExecuteAfter = async (input, output) => {
    const { sessionID } = input
    if (compactedSessions.has(sessionID) || compactionInProgress.has(sessionID)) return

    const cached = tokenCache.get(sessionID)
    if (!cached) return

    // Calculate actual context limit (accounting for Anthropic's 1M context special case)
    const actualLimit = isAnthropicProvider(cached.providerID)
      ? getAnthropicActualLimit(modelCacheState)
      : DEFAULT_ACTUAL_LIMIT

    // Calculate usage ratio
    const totalInputTokens = (cached.tokens.input ?? 0) + (cached.tokens.cache?.read ?? 0)
    const usageRatio = totalInputTokens / actualLimit

    // Return if threshold not reached
    if (usageRatio < PREEMPTIVE_COMPACTION_THRESHOLD) return

    // Trigger compaction
    compactionInProgress.add(sessionID)
    try {
      await ctx.client.session.summarize({
        path: { id: sessionID },
        body: { providerID: cached.providerID, modelID: cached.modelID, auto: true },
      })
      compactedSessions.add(sessionID)
    } finally {
      compactionInProgress.delete(sessionID)
    }
  }

  // Update token cache via event listener
  const eventHandler = async ({ event }) => {
    if (event.type === "message.updated") {
      const info = event.properties?.info
      if (info?.role === "assistant" && info?.finish && info?.tokens) {
        tokenCache.set(info.sessionID, {
          providerID: info.providerID,
          modelID: info.modelID,
          tokens: info.tokens,
        })
      }
    }
  }

  return { "tool.execute.after": toolExecuteAfter, event: eventHandler }
}
```

How it works:

1. **Token cache updates**: The `event` Hook listens for `message.updated` events. Each time the LLM completes a response, the session's token usage is cached.
2. **Threshold checking**: After each tool execution (`tool.execute.after`), it checks whether the current session's token usage exceeds 78%.
3. **Triggering compaction**: If the threshold is exceeded, it calls the OpenCode SDK's `session.summarize()` method, which has the LLM compress the conversation history into a summary.
4. **Deduplication protection**: Two Sets, `compactionInProgress` and `compactedSessions`, prevent duplicate compaction operations.

### `context-window-monitor`: Context Window Monitoring

Unlike preemptive compaction, the context window monitor's role is to **inform the Agent** about the current context usage status:

```typescript
// oh-my-opencode/src/hooks/context-window-monitor.ts
const CONTEXT_WARNING_THRESHOLD = 0.70  // Warning at 70% usage

export function createContextWindowMonitorHook(ctx, modelCacheState) {
  const remindedSessions = new Set<string>()

  const toolExecuteAfter = async (input, output) => {
    if (remindedSessions.has(sessionID)) return

    const cached = tokenCache.get(sessionID)
    if (!cached || !isAnthropicProvider(cached.providerID)) return

    const usageRatio = totalInputTokens / getAnthropicActualLimit(modelCacheState)
    if (usageRatio < CONTEXT_WARNING_THRESHOLD) return

    remindedSessions.add(sessionID)

    // Append context status reminder to tool output
    output.output += `\n\n[SYSTEM REMINDER - CONTEXT WINDOW MONITOR]
You are using Anthropic Claude with 1M context window.
You have plenty of context remaining - do NOT rush or skip tasks.
[Context Status: ${usedPct}% used, ${remainingPct}% remaining]`
  }
}
```

Note the different thresholds between the two Hooks: the monitor issues a warning at **70%**, while the compactor triggers at **78%**. This 8% buffer provides the Agent with an "early warning period" -- it first learns that the context is filling up, then has a chance to reduce context consumption before compaction is actually triggered.

### `ralph-loop`: Self-Driven Continuous Work Loop

Ralph Loop is the most iconic feature of oh-my-opencode. It implements a **self-driven work loop** -- after the Agent completes a response, if the task is not finished, the system automatically sends a continuation prompt to keep the Agent working.

```typescript
// oh-my-opencode/src/hooks/ralph-loop/types.ts
export interface RalphLoopState {
  active: boolean           // Whether the loop is active
  iteration: number         // Current iteration count
  max_iterations: number    // Maximum iteration count
  completion_promise: string // Completion promise (used to detect task completion)
  started_at: string        // Start time
  prompt: string            // Original user prompt
  session_id?: string       // Session ID
  ultrawork?: boolean       // Whether in ultrawork mode
}
```

The Ralph Loop architecture consists of 6 submodules:

```
ralph-loop/
├── ralph-loop-hook.ts          # Hook entry point
├── ralph-loop-event-handler.ts # Event handler
├── loop-state-controller.ts    # Loop state management
├── loop-session-recovery.ts    # Session recovery
├── continuation-prompt-builder.ts  # Continuation prompt builder
├── continuation-prompt-injector.ts # Continuation prompt injector
├── completion-promise-detector.ts  # Completion detector
├── storage.ts                  # State persistence
├── with-timeout.ts             # Timeout handling
└── types.ts                    # Type definitions
```

Workflow:

1. The user types "ultrawork" or executes the `/ralph-loop` command
2. `startLoop()` activates the loop and records the initial state
3. The Agent begins executing the task
4. When the Agent completes a response (`session.idle` event)
5. `completion-promise-detector` checks whether the response contains a "completion promise"
6. If not complete, `continuation-prompt-builder` constructs a continuation prompt
7. The continuation prompt is sent via the API, and the Agent continues working
8. Steps 4-7 repeat until the task is complete or the maximum iteration count is reached

### `todo-continuation-enforcer`: Todo Task Continuation Guarantee

This is the core mechanism for "keeping Sisyphus pushing the boulder." When the Agent stops working while there are incomplete Todos, this Hook forces the Agent to continue.

```typescript
// oh-my-opencode/src/hooks/todo-continuation-enforcer/index.ts
export function createTodoContinuationEnforcer(ctx, options) {
  const sessionStateStore = createSessionStateStore()

  const handler = createTodoContinuationHandler({
    ctx,
    sessionStateStore,
    backgroundManager,
    skipAgents,                    // Certain Agents are exempt from forced continuation (e.g., Explore)
    isContinuationStopped,         // Check if manually stopped by user
  })

  return {
    handler,
    markRecovering,              // Mark session as recovering (pause forced continuation)
    markRecoveryComplete,        // Mark recovery as complete
    cancelAllCountdowns,         // Cancel all countdowns
  }
}
```

How it works:

1. When an Agent's Session enters the `idle` state
2. The Hook checks whether the Session has incomplete Todo items
3. If so, it starts a countdown
4. When the countdown expires, a system reminder message is injected:

```
[SYSTEM REMINDER - TODO CONTINUATION]

You have incomplete todos. Do NOT stop here.
Continue working on the next pending todo item.
```

5. This message triggers the Agent to continue execution

### `edit-error-recovery`: Automatic Edit Failure Recovery

This Hook is concise yet highly effective -- when the Edit tool fails, it injects recovery instructions into the output:

```typescript
// oh-my-opencode/src/hooks/edit-error-recovery/hook.ts
const EDIT_ERROR_PATTERNS = [
  "oldString and newString must be different",
  "oldString not found",
  "oldString found multiple times",
]

const EDIT_ERROR_REMINDER = `
[EDIT ERROR - IMMEDIATE ACTION REQUIRED]

You made an Edit mistake. STOP and do this NOW:
1. READ the file immediately to see its ACTUAL current state
2. VERIFY what the content really looks like (your assumption was wrong)
3. APOLOGIZE briefly to the user for the error
4. CONTINUE with corrected action based on the real file content
`

export function createEditErrorRecoveryHook(ctx) {
  return {
    "tool.execute.after": async (input, output) => {
      if (input.tool.toLowerCase() !== "edit") return

      const hasEditError = EDIT_ERROR_PATTERNS.some((pattern) =>
        output.output.toLowerCase().includes(pattern.toLowerCase())
      )

      if (hasEditError) {
        output.output += `\n${EDIT_ERROR_REMINDER}`
      }
    },
  }
}
```

This Hook addresses a common LLM problem: **blind retries after edit failures**. Without this Hook, an LLM might attempt the same operation after an edit failure, leading to repeated failures. By injecting the instruction "re-read the file before retrying," it forces the LLM to update its understanding of the file's state.

### `unstable-agent-babysitter`: Babysitter for Unstable Sub-Agents

This is a "supervisor-level" Hook -- it monitors background sub-Agents, and if a sub-Agent has been inactive for too long or produces empty responses, the babysitter Hook intervenes:

```typescript
// oh-my-opencode/src/hooks/unstable-agent-babysitter/unstable-agent-babysitter-hook.ts
const DEFAULT_TIMEOUT_MS = 120000   // 2-minute timeout
const COOLDOWN_MS = 5 * 60 * 1000  // 5-minute cooldown period

export function createBabysitterHook(ctx, options) {
  // When a background task completes, check its response quality
  // If the response is empty or meaningless, send a reminder to the main Agent
  // ...
}
```

How the babysitter Hook works:

1. Listens for background task completion events
2. Retrieves the sub-Agent's last few messages
3. Analyzes whether the response is "unstable" (empty response, timeout, abnormal termination)
4. If unstable, constructs a reminder message and sends it to the main Session's Agent
5. Enters a cooldown period (no repeated reminders within 5 minutes)

> **Extended Explanation: What is Defensive Programming?**
>
> Defensive programming is a programming paradigm whose core philosophy is: **assume that everything can go wrong, and prepare recovery strategies for every possible failure in advance.**
>
> In traditional software engineering, defensive programming manifests as: input validation, exception handling, boundary checking, error logging, etc. In AI Agent systems, defensive programming takes on new meaning:
>
> * **The Agent might "forget" what it was doing** -> Todo Continuation Enforcer forces it to continue
> * **The Agent might edit a file based on incorrect assumptions** -> Edit Error Recovery forces a re-read
> * **The Agent might exhaust its context window** -> Preemptive Compaction compacts proactively
> * **A sub-Agent might time out or return empty responses** -> Unstable Agent Babysitter intervenes
> * **The Agent might add excessive comments** -> Comment Checker detects and warns
>
> The 53 Hooks of oh-my-opencode are essentially a **defensive programming framework for AI Agent behavior**. Each Hook assumes a specific failure mode will occur and predefines a recovery strategy.
>
> This is also the philosophical foundation of oh-my-opencode's naming -- Sisyphus's boulder will roll back, but he will keep pushing. The Agent's tasks will fail, but the Hook system ensures it will recover and continue.

## Section Summary

The 53 Hooks of oh-my-opencode form a dense behavior control and fault recovery network. They are divided into 8 major categories, covering context management, error recovery, continuous task execution, Agent behavior monitoring, and more.

Design principles of the six core Hooks:

1. **Preemptive Compaction** (78% threshold): Proactively compacts before the context window overflows, more reliable than passively waiting for errors
2. **Context Window Monitor** (70% threshold): Issues warnings earlier than the compactor, giving the Agent an early warning period
3. **Ralph Loop**: Achieves self-driven continuous execution through the "response -> detect -> continuation prompt -> response" cycle
4. **Todo Continuation Enforcer**: Checks for incomplete tasks when the Agent is idle and forces continuation
5. **Edit Error Recovery**: Intercepts edit errors and injects "read first, then retry" recovery instructions
6. **Unstable Agent Babysitter**: Monitors sub-Agent health and intervenes on anomalies
