# 事件与状态

规则读取状态，没有人手动维护它。它是事件流从空开始、逐条折叠的结果。

| 事件 | 读取的载荷 | 之后的 `SessionState` |
| --- | --- | --- |
| `user.prompt_submitted` |  | `turn_has_file_change`、`turn_has_verification` 重置为假 |
| `tool.before` | `tool`、`args.command` | 设置 `last_tool`；属于验证时 `turn_has_verification` 为真 |
| `file.changed` | `path` | `changed_files` 加入；`turn_has_file_change` 为真 |
| `tool.after`，`is_error` | `tool` | `tool_fail_count[tool]` 加 1 |
| `tool.after`，成功 | `tool` | `tool_fail_count[tool]` 归零 |

验证指工具名含 `pytest`、`test`、`chrome`、`browser`、`navigate`，或 `bash`、`test` 工具的命令含 `test`、`pytest`、`npm run`、`make`。

## 折叠

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

从头折叠是定义。`StateStore.apply` 增量更新，结果必须相同。

| 性质 | 规则 |
| --- | --- |
| 事件流 | 有序、只追加，任意时刻都能重新算出。事件定义见[事件层](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/event-layer.zh.html)。 |
| 并发 | 每个 `metadata["session"]` 一份状态。子 Agent 折叠在一起，会把一个的改动和另一个的情况配对。 |
| `origin` | 框架自己引起的事件不折叠，也不交给规则：[不变式](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/invariants.zh.html)。 |
| 深度 | 只有机械事实（L0）。启发式层和 LLM 层等规则需要时再加。 |

## 读取状态

```
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")
```

[规则与运行方式](https://fzkuji.github.io/OpenProgram/docs/reference/design/proactive/execution-model.zh.html)
