# Event layer

1. **Sources** agent loop, tools, dispatcher, job runner, auth, context, channels, memory
2. `emit`
3. **EventBus** one per process; imports nothing from the WebUI
4. `subscribe`
5. **Consumers** WebUI (ws.frame), plugins, config hooks, events.jsonl

## Dispatch

| Kind | Call | Effect | Subscriber raises |
| --- | --- | --- | --- |
| notify | `emit` / `subscribe(handler, types=…)` | Observed; the emitter never waits on the result | Logged; other subscribers still run |
| gate | `emit_gate(event, timeout_s=None)` / `subscribe_gate` | All run in registration order, in the emitter's thread. Any reason sets `allowed=False`; reasons aggregate. | Logged, treated as allow |
| transform | `emit_transform(event, value)` / `subscribe_transform` | Each receives the previous value and returns the next; `None` keeps it | Skipped; its input carries on |

- Gates are `tool.before` and `turn.stop`; the one transform is `tool.result`, which shell hooks cannot subscribe to. Everything else is notify: [Event reference](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/event-reference.html).
- Gates are fast: no LLM calls, no slow I/O.
- A nested `emit_gate` for the same type in the same thread allows at once, with a warning.
- `timeout_s` is a soft total; past it, remaining gates are skipped with a warning.
- `tool.before` sits outside the `permission_mode` approval wrapper, so `bypass` and subagents do not escape it.
- Notify handlers run in the emitter's thread too; async handlers are scheduled on the running loop when one exists.

## Event

```
@dataclass(frozen=True)
class Event:
    id: str
    ts: float
    type: str
    origin: str      # user / agent / tool / system / proactive
    payload: dict
    metadata: dict   # {"session": …, "turn": …, "lane": …}
```

`make_event` fills `id`, `ts` and session and turn from the store ContextVars; explicit `metadata` keys win. Session and turn are metadata because they are external correlations with no meaning for half the events, such as auth and channels. The framework has no Turn object.

## Admission

A type enters `EVENTS` only when a real consumer subscribes to it. Adding a type changes only its emit site; adding payload fields is safe; changing existing ones can break subscribers.

Emitting an unregistered type warns once per type and never raises. `test_every_emitted_type_is_registered` covers every `emit_safe` type.

| Source class | Connection |
| --- | --- |
| A: Agent activity | Emit sites in the turn, tool and job paths; metadata usually carries session and turn |
| B: system state, possibly with no Agent running | Auth keeps its own `subscribe`/`_emit`, with a one-way bridge in `events/bridges.py`. Context, channels, memory and the WebUI watchers tap with `emit_safe`. |

## Veto

| Subscriber | Protocol |
| --- | --- |
| Python gate | `None` allows; a string denies. `tool.before`: the reason becomes the model's error tool result. `turn.stop`: it becomes the continuation prompt, prefixed `[hook]`. |
| Shell, event as JSON on stdin | Exit `0` allows. Exit `2` denies with stderr as the reason. Anything else, or a timeout (default 60 s), fails open with a warning. |

```
{"hooks": {"turn.stop": [{"command": "python check_done.py", "timeout": 30}]}}
```

The top-level `hooks` key of `config.json`. `install_config_hooks()` registers gate kinds as synchronous shell gates and notify kinds as background runners (daemon thread, exit code ignored). Edits apply at the next worker restart.

The command runs in `/bin/sh` on macOS and Linux and in bash on Windows, falling back to PowerShell with one notice when there is none. An entry may say `"shell": "powershell"`, or give `args` to run `command` directly with no shell ([which shell runs a hook](https://fzkuji.github.io/OpenProgram/docs/reference/design/distribution/windows-command-shell.html#hook-shell)). The event arrives on standard input as UTF-8 JSON.

**The `turn.stop` continuation loop**

- `continue_stop_hook_turns` asks the gate after each completed top-level chat turn. Failed or cancelled turns return without asking.
- A denial launches one more ordinary turn (`dataclasses.replace`, `source="hook_continue"`, `INHERIT_PARENT`), then the gate runs again.
- No numeric cap: `stop_hook_active` is true on every ask after the first, so a hook knows to allow the stop, as in Claude Code and Codex.
- Goal rounds stay out of this path: `goal()` owns their completion judge and `/goal clear` can stop them.
- Head movement stays with the normal `TurnWriter` path.

## Event log

| Item | Value |
| --- | --- |
| Session whose directory exists | `~/.openprogram/projects/<project-id>/chats/<sid>/events.jsonl` |
| Otherwise | `~/.openprogram/logs/events.jsonl` |
| Rotation | Past 5 MB to `.1`, replacing the previous one |
| Gate verdict | `gate: {allowed, reasons, duration_ms, subscribers}` on the event's own line |
| Writer | Only the singleton; `create_event_bus()` buses stay silent |

**Gate events and the log row**

A gate event passed through `emit` for typed observers defers its disk write; the same Event must then reach `emit_gate`, which writes the one row with the verdict. `emit` alone writes none. `emit_gate` alone is complete, without observers, and is what `turn.stop` uses.

## Wiring

| Surface | Backed by |
| --- | --- |
| `register_tool_gate`, `decide_tool_gate`, `ToolGateDenied` | Thin shell over the `tool.before` gate (`tool_gate.py`) |
| Plugin `hooks` | `extensions/plugins/hooks.py` reads the manifest and mounts each command through the plugin's `ProgramContext`, so disabling unsubscribes. Accepts the `config.json` shape or Claude Code's `hooks/hooks.json`. |
| `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `Stop`, `SessionStart` | `tool.before`, `tool.after`, `chat.before_send`, `turn.stop`, `session.start` |
| `/goal` changes | `_emit_goal_update` emits `goal.update` |
| Worker start | `install_event_bridges()`, `install_config_hooks()` |

**Where each part lives**

| Part | Where, under `openprogram/runtime/events/` |
| --- | --- |
| Registry | `registry.py` |
| Event, dispatch, subscriptions, process singleton | `bus.py` (`get_event_bus()`, double-checked locking like `get_store()`) |
| Shell protocol | `shell_hooks.py` |
| Log | `event_log.py` |
| Bridges | `bridges.py` |

All relevant components are daemon threads in one worker process, so no cross-process bridge exists. Import from `openprogram.runtime.events`.

## Implementation status

Everything above is implemented. Registered without an emitter: `sessions.listed`, `branches.listed`. The proactive engine that would consume the bus is not installed at worker start: [Proactive layer](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/overview.html).

[Event reference](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/event-reference.html)
