# Hook Generation Flow

How Agenvoy builds and tests lifecycle hooks end-to-end when you ask the agent to create or update a hook.

## Flow

```mermaid
graph TB
    Start[User asks to create or edit a hook] --> Guide[read_guides hook_generate]
    Guide --> Pick[Pick state from 7 supported names + .py or .js]
    Pick --> ReadExisting[read_files existing hook if installed]
    ReadExisting --> Write[write_hook mode=write or patch<br/>Automatic syntax and contract validation on every write/patch]
    Write -->|Invalid| PatchVal[Fix issues via write_hook mode=patch]
    PatchVal --> Write
    Write -->|Valid| Test[test_script path with sample stdin JSON<br/>Sandbox execution, 60s limit]
    Test -->|Error or unexpected success value| PatchTest[Adjust script via write_hook mode=patch]
    PatchTest --> Test
    Test -->|Expected success 1 or 0 JSON| Done[Report hook path, state, and test result]
```

## Step-by-step sequence

1. **Load the guide** — Call `read_guides(topics=["hook_generate"])` first. It defines all seven states accepted by `write_hook` (`before_user_send`, `before_tool_call`, `after_tool_call`, `after_tool_error`, `after_ask_user`, `after_task_done`, `after_task_cancel`), the exact JSON fields passed on `stdin`, and the output contract.
2. **Inspect & write or patch** — Check `~/.config/agenvoy/hooks/<state>.py` (or `.js`; `.py` wins when both exist) with `read_files`. Use `write_hook(mode=patch)` if a hook already exists, or `write_hook(mode=write)` from the template if none is installed. Every `write` and `patch` runs automatic validation in-process before returning.
3. **Test with `test_script`** — Pass sample `stdin` JSON matching the target state to `test_script`. Fix any runtime error or unexpected `success` value with `write_hook(mode=patch)` and re-run `test_script` until the last stdout line returns the expected result.

## Output contract

- The last line on `stdout` must be a single JSON object with all three fields: `{"success": 1|0, "debug": "...", "error": "..."}` (`1` passes, `0` blocks with reason in `error`).
- Earlier `stdout` lines and `stderr` go only to the debug log.
- A crash, non-JSON last line, or execution past 30 seconds at runtime counts as a block.

## Version history

- v1.6.3: Added the dedicated hook generation flow page, reflecting automatic validation on `write_hook` `write`/`patch` and verification via `test_script`.
