# Events and state

Rules read state; nobody maintains it by hand. It is the event stream folded from empty, one event at a time.

| Event | Payload read | `SessionState` after |
| --- | --- | --- |
| `user.prompt_submitted` |  | `turn_has_file_change` and `turn_has_verification` reset to false |
| `tool.before` | `tool`, `args.command` | `last_tool` set; `turn_has_verification` true when it is a verification |
| `file.changed` | `path` | `changed_files` adds it; `turn_has_file_change` true |
| `tool.after`, `is_error` | `tool` | `tool_fail_count[tool]` + 1 |
| `tool.after`, success | `tool` | `tool_fail_count[tool]` = 0 |

A verification is a tool named with `pytest`, `test`, `chrome`, `browser` or `navigate`, or a `bash` or `test` tool whose command holds `test`, `pytest`, `npm run` or `make`.

## Fold

```
state = empty_state()
for event in stream:
    state = update(state, event)
```

From scratch is the definition. `StateStore.apply` updates incrementally and must give the same result.

| Property | Rule |
| --- | --- |
| Stream | Ordered and append-only, so any moment can be recomputed. The [event layer](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/event-layer.html) defines the event. |
| Concurrency | One state per `metadata["session"]`. Subagents folded together would pair one's changes with another's situation. |
| `origin` | Events the framework caused are not folded or shown to rules: [Invariants](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/invariants.html). |
| Depth | Mechanical facts only (L0). Heuristic and LLM layers are added when a rule needs them. |

## Reading state

```
class StuckToolWatcher(Policy):
    on = {"tool.after"}
    def evaluate(self, event, state):
        tool = event.payload["tool"]
        if state.tool_fail_count.get(tool, 0) >= 3:
            return Notify(f"{tool} has failed repeatedly, may be stuck")
```

[Rules and how they run](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/execution-model.html)
