rewindagents 0.0.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ """rewindagents: a tamper-evident flight recorder for AI agent tool calls."""
2
+ from .log import GENESIS, Recorder, head, read, verify
3
+
4
+ __all__ = ["GENESIS", "Recorder", "head", "read", "verify"]
5
+ __version__ = "0.0.8"
@@ -0,0 +1,23 @@
1
+ """`python -m rewindagents ...`, and, from a clone, `python <clone>/src/rewindagents/__main__.py ...`.
2
+
3
+ The second form is what hook.hook_command writes for a Windows interpreter from an uninstalled clone: the hook
4
+ shells there (Git Bash, PowerShell, cmd.exe) share no syntax for a PYTHONPATH prefix, but all of them run
5
+ `<python> <file> hook`. Run as a file, this module has no package, so it makes the clone's src/ importable and
6
+ runs the package the normal way."""
7
+ import sys
8
+
9
+ if __package__:
10
+ from .cli import main
11
+
12
+ sys.exit(main())
13
+
14
+ import runpy # noqa: E402
15
+ from pathlib import Path # noqa: E402
16
+
17
+ _here = Path(__file__).resolve()
18
+ # Python put this package directory first on sys.path; src/ belongs there instead.
19
+ if sys.path and Path(sys.path[0] or ".").resolve() == _here.parent:
20
+ sys.path[0] = str(_here.parent.parent)
21
+ else:
22
+ sys.path.insert(0, str(_here.parent.parent))
23
+ runpy.run_module("rewindagents", run_name="__main__", alter_sys=True)
rewindagents/agents.py ADDED
@@ -0,0 +1,395 @@
1
+ """The coding agents rewindagents hooks into, and how each one's hook protocol differs.
2
+
3
+ The hook body (hook.py) is the same for all of them: record the call, checkpoint first, never block. This
4
+ module holds what differs: where the hook is configured, the shape of that file, the names of the fields in
5
+ the JSON the agent sends on stdin, what the hook must print, and which tools are known not to change files.
6
+
7
+ Sources, read on 2026-11-11 (every field name below is quoted from them):
8
+
9
+ - Cursor: https://cursor.com/docs/agent/hooks
10
+ Config: `.cursor/hooks.json` in the project (or `~/.cursor/hooks.json`), `{"version": 1, "hooks": {"<event>":
11
+ [{"command": "..."}]}}`; a hook with no "matcher" runs for every tool. Events `preToolUse` and `postToolUse`.
12
+ Common stdin fields: `conversation_id`, `generation_id`, `hook_event_name`, `workspace_roots`. preToolUse adds
13
+ `tool_name`, `tool_input`, `tool_use_id`, `cwd`; postToolUse adds `tool_output` ("JSON-stringified result
14
+ payload from the tool") and `duration`. Tool names: `Shell`, `Read`, `Write`, `Grep`, `Delete`, `Task`,
15
+ `MCP:<tool_name>`. The documented `tool_input` is Shell's: `{"command": ..., "working_directory": ...}`; the
16
+ input of `Write` is not documented, so this module never reads a file path out of a Cursor payload. Output:
17
+ preToolUse is a permission hook and "invalid JSON or a response that doesn't match the schema blocks the
18
+ action", so the hook prints `{"permission": "allow"}` (a deny from any other hook still wins: "deny beats ask
19
+ beats allow"); postToolUse prints `{}`. Exit 2 blocks; the hook exits 0.
20
+
21
+ - Codex: https://developers.openai.com/codex/hooks (served from https://learn.chatgpt.com/docs/hooks)
22
+ Config: `.codex/hooks.json` in the project (or `~/.codex/hooks.json`), the same shape as Claude Code's
23
+ settings: `{"hooks": {"PreToolUse": [{"matcher": "...", "hooks": [{"type": "command", "command": "..."}]}]}}`.
24
+ Stdin: `session_id`, `cwd`, `hook_event_name`, `tool_name`, `tool_use_id`, `tool_input`, and on PostToolUse
25
+ `tool_response`. Tool names: shell commands match as `Bash`, file edits as `apply_patch`, MCP tools as
26
+ `mcp__<server>__<tool>`, other local tools by their function name (for example `update_plan`). Plain text on
27
+ stdout is ignored for PreToolUse and PostToolUse and exit 0 with no output is success, so the hook prints
28
+ nothing. Codex asks the user to trust a hook before it runs (`/hooks`), and remembers the trust by the hook's
29
+ hash; project hooks load only when the project's `.codex/` layer is trusted.
30
+
31
+ - Claude Code: `.claude/settings.json`, events `PreToolUse` and `PostToolUse`, fields `session_id`, `cwd`,
32
+ `hook_event_name`, `tool_name`, `tool_input`, `tool_use_id`, `tool_response`; stdout empty. Built in R2 and
33
+ driven by a real Claude Code session; the fixtures in tests/test_hook.py are its payloads. A call that fails
34
+ goes to `PostToolUseFailure` ("After a tool call fails", code.claude.com/docs/en/hooks, read 2026-11-14), not
35
+ to PostToolUse: in a real session (ux-review/DOGFOOD.md, F11) a Bash command that exited 1 got no post event,
36
+ so its after-scan never ran and the files it changed were not checkpointed. The hook is installed there too.
37
+
38
+ Read on 2026-11-12 (same rule: every field name quoted from the vendor page named):
39
+
40
+ - Gemini CLI: https://geminicli.com/docs/hooks/ , https://geminicli.com/docs/hooks/reference/ and the tool list
41
+ https://geminicli.com/docs/reference/tools/
42
+ Config: `.gemini/settings.json` in the project (or `~/.gemini/settings.json`), `{"hooks": {"BeforeTool":
43
+ [{"matcher": "...", "hooks": [{"type": "command", "command": "..."}]}]}}`; `"*"` or `""` matches every tool.
44
+ Events `BeforeTool` and `AfterTool`. Stdin: `session_id`, `transcript_path`, `cwd`, `hook_event_name`,
45
+ `timestamp`; BeforeTool adds `tool_name`, `tool_input`, `mcp_context`, `original_request_name`; AfterTool adds
46
+ `tool_response` (`llmContent`, `returnDisplay`, `error`). No call id. Tools: `run_shell_command`; `write_file`
47
+ and `replace` (kind Edit); read-only: `read_file`, `read_many_files`, `list_directory`, `glob`, `grep_search`
48
+ (alias `search_file_content`), `google_web_search`, `web_fetch`. Output: on exit 0 "stdout is parsed as JSON"
49
+ and the script "must not print any plain text to stdout other than the final JSON"; only `"decision": "deny"`
50
+ (or `"block"`), `continue: false` and exit 2 stop anything. So the hook prints `{}` (no decision field) for
51
+ every event. The page notes Gemini CLI was replaced by Antigravity CLI on June 18th, 2026 for unpaid tier and
52
+ Google One users.
53
+
54
+ - GitHub Copilot CLI: https://docs.github.com/en/copilot/reference/hooks-configuration and
55
+ https://docs.github.com/en/copilot/how-tos/use-copilot-agents/coding-agent/use-hooks
56
+ Config: `.github/hooks/<NAME>.json` in the repository (or `~/.copilot/hooks/`), `{"version": 1, "hooks":
57
+ {"<event>": [{"type": "command", "bash": "..."}]}}`; no "matcher" = every tool. "Two payload formats are
58
+ supported, selected by the event name used in the hook configuration": camelCase `preToolUse` sends
59
+ `sessionId`/`toolName`/`toolArgs` and no event name; PascalCase `PreToolUse`/`PostToolUse` selects the VS Code
60
+ format with `hook_event_name`, `session_id`, `timestamp`, `cwd`, `tool_name`, `tool_input` and, after the call,
61
+ `tool_result` (`result_type`, `text_result_for_llm`). rewindagents installs the PascalCase events so the payload
62
+ names its event. Tools: `bash` (shell), `create`, `edit`; read and search: `view`, `grep`, `glob`; `web_fetch`.
63
+ Output: empty stdout "falls through to default behavior" (preToolUse) and "Return {} or empty output to keep
64
+ the original successful result" (postToolUse), so the hook prints nothing. A failed call goes to
65
+ `PostToolUseFailure` (`error` in place of `tool_result`); the hook is installed there too, to close the scan. But "Command preToolUse hooks are
66
+ fail-closed on errors": "a crash or non-zero exit (including exit 2) denies the tool call". The hook exits 0,
67
+ and the installed command ends in `|| true`, so even an interpreter that is missing (the cloud agent's sandbox
68
+ does not have this machine's Python) exits 0 and blocks nothing; there it records nothing.
69
+
70
+ - Factory Droid: https://docs.factory.com/reference/hooks-reference (was docs.factory.ai)
71
+ Config: `.factory/hooks.json` (keyed by event name at the top level) or, "if hooks.json is absent", the
72
+ `hooks` key of `.factory/settings.json`; groups of `{"matcher": ..., "hooks": [{"type": "command", "command":
73
+ ...}]}`, matcher optional, `*` matches everything. So install writes `.factory/hooks.json` when it exists and
74
+ `.factory/settings.json` otherwise: creating hooks.json would hide hooks the user keeps in settings.json.
75
+ Stdin: `session_id`, `transcript_path`, `cwd`, `permission_mode`, `hook_event_name`, `tool_name`, `tool_input`
76
+ and on PostToolUse `tool_response`. No call id. Tools: `Execute` (`tool_input.command`), `Create`
77
+ (`file_path`, `content`), `Edit`, `ApplyPatch`, `Task`; read-only: `Read`, `LS`, `Glob`, `Grep`, `FetchUrl`,
78
+ `WebSearch`. Exit 0 is success (stdout is shown in transcript views), exit 2 blocks PreToolUse, other codes
79
+ are non-blocking. The hook prints nothing.
80
+
81
+ - Qwen Code: https://github.com/QwenLM/qwen-code/blob/main/docs/users/features/hooks.md and the tool ids
82
+ https://github.com/QwenLM/qwen-code/blob/main/docs/developers/tools/file-system.md (the same pages the
83
+ project publishes as its docs site)
84
+ Config: `.qwen/settings.json`, `{"hooks": {"PreToolUse": [{"matcher": "...", "hooks": [{"type": "command",
85
+ "command": "..."}]}]}}`; a matcher entry of `*` or `.*` matches every tool. Stdin: `session_id`,
86
+ `transcript_path`, `cwd`, `hook_event_name`, `timestamp`, `permission_mode`; PreToolUse adds `tool_name`,
87
+ `tool_input`, `tool_use_id`, `tool_call_id`; PostToolUse ("after a tool completes successfully") adds
88
+ `tool_response` and `duration_ms`; PostToolUseFailure ("when a tool execution fails") has `tool_use_id`,
89
+ `tool_name`, `tool_input`, `error`, `is_interrupt`. A failed call can still have changed files, so the hook
90
+ is installed on PostToolUseFailure too and that event closes the scan like PostToolUse. Tools:
91
+ `run_shell_command`, `write_file`, `edit`, `notebook_edit`; read-only: `read_file`, `list_directory`, `glob`,
92
+ `grep_search`. Exit 0 with a JSON object controls behaviour, other stdout is "kept as a system message",
93
+ exit 2 blocks; the hook prints nothing.
94
+
95
+ Not supported, and why (same date): Windsurf's Cascade hooks page now redirects to Devin's
96
+ (docs.devin.ai/desktop/cascade/hooks); Devin's hooks (https://docs.devin.ai/cli/extensibility/hooks/overview.md)
97
+ document no `cwd` and not where the command runs, so the project cannot be found from the payload (Devin also
98
+ reads `.claude/settings.json` by default, so a Claude Code install fires there too, as the Claude Code hook).
99
+ Kiro (https://kiro.dev/docs/hooks/types/) documents the PreToolUse payload but not PostToolUse's. Cline
100
+ (https://docs.cline.bot/customization/hooks.md -> SDK plugins), OpenCode (https://opencode.ai/docs/plugins/) and
101
+ Amp (https://ampcode.com/docs/plugin-api) are JavaScript/TypeScript plugins, not command hooks. Roo Code, Zed,
102
+ Warp and Replit document no tool hooks.
103
+
104
+ What is and is not verified: the Codex, Cursor, Gemini CLI, Copilot CLI, Droid and Qwen Code payloads in
105
+ tests/test_agents*.py are the documented ones, and the hook has not yet run inside a live session of any of
106
+ them. The README says so.
107
+
108
+ Windows, read on 2026-11-14: which shell runs the hook command string there, per vendor page (this decides the
109
+ form hook.hook_command writes for a Windows interpreter path: Agent.win_shell and Agent.win_command_key). The
110
+ hook has not run on Windows; the README keeps "Windows is not supported".
111
+
112
+ - Claude Code (https://code.claude.com/docs/en/hooks): a command hook without `args` is in "shell form": "The
113
+ `command` string is passed to a shell: `sh -c` on macOS and Linux, Git Bash on Windows, or PowerShell when
114
+ Git Bash isn't installed." A `shell` field "Accepts `"bash"` or `"powershell"`. Defaults to `"bash"`, or to
115
+ `"powershell"` on Windows when Git Bash isn't installed." Without Git Bash, a quoted path alone is not run:
116
+ "A hook with this error ran in PowerShell, which prints a `command` that is only quoted strings"; the page's
117
+ fix is to "put `&` before the quoted path". win_shell = "bash" (the documented default).
118
+ - Cursor (https://cursor.com/docs/agent/hooks): "On Windows, the desktop app runs hook commands through
119
+ PowerShell and pipes the JSON into the command". win_shell = "powershell".
120
+ - Codex (https://learn.chatgpt.com/docs/hooks): the shell is not named; "`commandWindows` is an optional
121
+ Windows-only command override". win_shell unknown.
122
+ - Gemini CLI (https://geminicli.com/docs/hooks/reference/): nothing about Windows or the shell. Unknown.
123
+ - GitHub Copilot CLI (https://docs.github.com/en/copilot/reference/hooks-configuration): per-OS keys on a
124
+ command hook: `bash` is "Shell command for Unix.", `powershell` is "Shell command for Windows."; a `command`
125
+ key is "Copied to both `bash` and `powershell` when those fields are absent". So an entry holding only `bash`
126
+ never runs on Windows: a Windows command is written under `powershell` (win_command_key), and its fail-closed
127
+ guard is `; exit 0` there, since `|| true` is bash. win_shell = "powershell".
128
+ - Factory Droid (https://docs.factory.com/reference/hooks-reference): nothing about Windows or the shell. Unknown.
129
+ - Qwen Code (https://github.com/QwenLM/qwen-code/blob/main/docs/users/features/hooks.md): a per-hook `shell`
130
+ field, `"bash" | "powershell"`, "Shell to use"; no default is stated. Unknown.
131
+
132
+ For an unknown shell the Windows form is the one Git Bash and cmd.exe share (a bare forward-slash path, or
133
+ a double-quoted one); PowerShell would need `&` before a quoted path. The bare form runs in all three.
134
+ """
135
+ from __future__ import annotations
136
+
137
+ import json
138
+ import os
139
+ import re
140
+ from dataclasses import dataclass, field
141
+ from pathlib import Path
142
+ from typing import Any
143
+
144
+ CURSOR_DOCS = "https://cursor.com/docs/agent/hooks"
145
+ CODEX_DOCS = "https://developers.openai.com/codex/hooks"
146
+ DOCS_READ = "2026-11-11"
147
+ GEMINI_DOCS = "https://geminicli.com/docs/hooks/reference/"
148
+ COPILOT_DOCS = "https://docs.github.com/en/copilot/reference/hooks-configuration"
149
+ DROID_DOCS = "https://docs.factory.com/reference/hooks-reference"
150
+ QWEN_DOCS = "https://github.com/QwenLM/qwen-code/blob/main/docs/users/features/hooks.md"
151
+ DOCS_READ_2 = "2026-11-12"
152
+ DOCS_READ_3 = "2026-11-14" # the Windows shell of each agent (module docstring)
153
+
154
+
155
+ @dataclass(frozen=True)
156
+ class Agent:
157
+ name: str
158
+ settings: str # default config file, relative to the project
159
+ events: tuple[str, str] # the pre and post event names as the agent spells them
160
+ shape: str # "groups": {"hooks": {event: [{"matcher", "hooks": [...]}]}} (Claude Code, Codex,
161
+ # Gemini CLI, Droid, Qwen Code); "cursor": {"version": 1, "hooks": {event:
162
+ # [entry]}} (Cursor, Copilot CLI)
163
+ reply: dict[str, str] = field(default_factory=dict) # what to print on stdout per event ("" = nothing)
164
+ read_only: frozenset = frozenset() # tools the docs name that cannot change files: not scanned
165
+ file_tools: bool = False # True when the pre payload names the file an edit tool will change
166
+ entry: tuple = () # "cursor" shape: the documented keys of one entry before the command
167
+ command_key: str = "command" # "cursor" shape: the key that holds the command (Copilot: "bash")
168
+ fail_closed: bool = False # a non-zero exit counts as a deny: the command is written with `|| true`
169
+ prefer: str = "" # a config file used in place of `settings` when it exists (Droid)
170
+ flat: frozenset = frozenset() # file names whose top level IS the hooks object (Droid's hooks.json)
171
+ also_post: tuple = () # more events that end a call (a failed call): installed, and read as "post"
172
+ win_shell: str = "" # the shell that runs the command on Windows, as the docs name it: "bash" (Git
173
+ # Bash), "powershell", or "" when the docs do not say (module docstring)
174
+ win_command_key: str = "" # "cursor" shape: the key a Windows command goes under (Copilot: "powershell")
175
+
176
+
177
+ AGENTS: dict[str, Agent] = {
178
+ "claude": Agent("claude", ".claude/settings.json", ("PreToolUse", "PostToolUse"), "groups", file_tools=True,
179
+ win_shell="bash", also_post=("PostToolUseFailure",)),
180
+ "codex": Agent("codex", ".codex/hooks.json", ("PreToolUse", "PostToolUse"), "groups",
181
+ read_only=frozenset({"update_plan"})),
182
+ "cursor": Agent("cursor", ".cursor/hooks.json", ("preToolUse", "postToolUse"), "cursor",
183
+ reply={"pre": '{"permission": "allow"}', "post": "{}", "unknown": '{"permission": "allow"}'},
184
+ read_only=frozenset({"Read", "Grep"}), win_shell="powershell"),
185
+ "gemini": Agent("gemini", ".gemini/settings.json", ("BeforeTool", "AfterTool"), "groups",
186
+ reply={"pre": "{}", "post": "{}", "unknown": "{}"},
187
+ read_only=frozenset({"read_file", "read_many_files", "list_directory", "glob", "grep_search",
188
+ "search_file_content", "google_web_search", "web_fetch"})),
189
+ "copilot": Agent("copilot", ".github/hooks/rewindagents.json", ("PreToolUse", "PostToolUse"), "cursor",
190
+ read_only=frozenset({"view", "grep", "glob", "web_fetch"}),
191
+ entry=(("type", "command"),), command_key="bash", fail_closed=True,
192
+ also_post=("PostToolUseFailure",), win_shell="powershell", win_command_key="powershell"),
193
+ "droid": Agent("droid", ".factory/settings.json", ("PreToolUse", "PostToolUse"), "groups",
194
+ read_only=frozenset({"Read", "LS", "Glob", "Grep", "FetchUrl", "WebSearch"}),
195
+ prefer=".factory/hooks.json", flat=frozenset({"hooks.json"})),
196
+ "qwen": Agent("qwen", ".qwen/settings.json", ("PreToolUse", "PostToolUse"), "groups",
197
+ read_only=frozenset({"read_file", "list_directory", "glob", "grep_search"}),
198
+ also_post=("PostToolUseFailure",)),
199
+ }
200
+ DEFAULT = "claude"
201
+
202
+ # A Windows path at the start of a word: C:/..., C:\..., \\server\share\... (after a quote, a space, `=` or `&`).
203
+ _WIN_PATH = re.compile(r'(?:^|[\s"=])(?:[A-Za-z]:[\\/]|\\\\[^\\\s"]+\\)')
204
+
205
+
206
+ def windows_command(command: str) -> bool:
207
+ """True when the command names a Windows path. A hook command always names its interpreter by absolute path,
208
+ so this tells a Windows hook command from a POSIX one by its own shape, whatever OS is reading it."""
209
+ return bool(_WIN_PATH.search(command))
210
+
211
+
212
+ def command_key(agent: Agent, command: str) -> str:
213
+ """The key a "cursor"-shape entry holds this command under: `agent.win_command_key` for a Windows command when
214
+ the agent has one (Copilot: `powershell`, as its `bash` key is "Shell command for Unix."), else `agent.command_key`."""
215
+ if agent.win_command_key and windows_command(command):
216
+ return agent.win_command_key
217
+ return agent.command_key
218
+
219
+
220
+ def _command_keys(agent: Agent) -> tuple[str, ...]:
221
+ return (agent.command_key, agent.win_command_key) if agent.win_command_key else (agent.command_key,)
222
+
223
+
224
+ def normalize(payload: dict) -> dict[str, Any]:
225
+ """The fields the hook needs, under one set of names, whichever agent sent the payload.
226
+
227
+ Never raises on a field of the wrong type: an event name that is not a string is "unknown", a cwd that is
228
+ not a string counts as missing (the hook then uses the directory it runs in, where the agents start it),
229
+ and a tool name or session id that is not a string is recorded as its JSON text."""
230
+ raw = payload.get("hook_event_name")
231
+ raw = raw if isinstance(raw, str) else ""
232
+ event = {"pretooluse": "pre", "posttooluse": "post", "posttoolusefailure": "post",
233
+ "beforetool": "pre", "aftertool": "post"}.get(
234
+ raw.lower(), raw or "unknown")
235
+ cwd = payload.get("cwd")
236
+ if not (isinstance(cwd, str) and cwd):
237
+ roots = payload.get("workspace_roots")
238
+ cwd = roots[0] if isinstance(roots, list) and roots and isinstance(roots[0], str) and roots[0] \
239
+ else os.getcwd()
240
+ if "tool_response" in payload:
241
+ response = payload["tool_response"]
242
+ elif "tool_result" in payload: # Copilot CLI, VS Code format
243
+ response = payload["tool_result"]
244
+ elif "error" in payload: # PostToolUseFailure (Copilot CLI, Qwen Code)
245
+ response = {"error": payload["error"]}
246
+ else:
247
+ response = payload.get("tool_output") # Cursor: a JSON string; keep it as sent if it is not
248
+ if isinstance(response, str):
249
+ try:
250
+ response = json.loads(response)
251
+ except ValueError:
252
+ pass
253
+ return {"event": event, "session": _text(payload.get("session_id") or payload.get("conversation_id"), "unknown"),
254
+ "cwd": Path(cwd), "tool": _text(payload.get("tool_name"), "?"), "input": payload.get("tool_input") or {},
255
+ "response": response}
256
+
257
+
258
+ def _text(value: Any, default: str) -> str:
259
+ if value is None or value == "":
260
+ return default
261
+ return value if isinstance(value, str) else json.dumps(value, sort_keys=True, default=str)
262
+
263
+
264
+ def scans(agent: Agent, tool: str) -> bool:
265
+ """Whether the project is scanned before and after this call (bashscan.py).
266
+
267
+ Claude Code: Bash only (Write/Edit/MultiEdit/NotebookEdit name their file and are checkpointed directly).
268
+ Every other agent: every call except the tools the docs name that cannot change files, because the input
269
+ shape of some edit tools is not documented (Codex's apply_patch, Cursor's Write, Droid's Edit), a shell or
270
+ MCP call names no file at all, and a scan needs no shape.
271
+ """
272
+ if agent.file_tools:
273
+ return tool == "Bash"
274
+ return tool not in agent.read_only
275
+
276
+
277
+ def config_path(agent: Agent, root: str | Path = ".") -> str:
278
+ """The agent's config file in the project at `root`, relative to it: `agent.prefer` when that file exists
279
+ (Droid reads settings.json's hooks only when hooks.json is absent), else `agent.settings`."""
280
+ if agent.prefer and (Path(root) / agent.prefer).exists():
281
+ return agent.prefer
282
+ return agent.settings
283
+
284
+
285
+ def _hooks(agent: Agent, p: Path, settings: dict, create: bool) -> dict | None:
286
+ """The object keyed by event name: the file itself for a flat file, else its "hooks" key."""
287
+ if p.name in agent.flat:
288
+ return settings
289
+ if create:
290
+ return settings.setdefault("hooks", {})
291
+ h = settings.get("hooks")
292
+ return h if isinstance(h, dict) else None
293
+
294
+
295
+ def install(agent: Agent, settings_path: str | Path, command: str) -> bool:
296
+ """Add the hook command to the agent's config file. Keeps everything already there.
297
+
298
+ Returns True if the file changed, False if the hook was already installed.
299
+ """
300
+ p = Path(settings_path)
301
+ text = p.read_text(encoding="utf-8") if p.exists() else ""
302
+ settings = json.loads(text) if text.strip() else {}
303
+ if not isinstance(settings, dict):
304
+ raise ValueError(f"{p} does not hold a JSON object")
305
+ hooks = _hooks(agent, p, settings, create=True)
306
+ changed = False
307
+ if agent.shape == "cursor":
308
+ if settings.get("version") is None:
309
+ settings = {"version": 1, **settings}
310
+ changed = True
311
+ k = command_key(agent, command)
312
+ for event in agent.events + agent.also_post:
313
+ entries = hooks.setdefault(event, [])
314
+ if not any(isinstance(h, dict) and h.get(k) == command for h in entries):
315
+ entries.append({**dict(agent.entry), k: command})
316
+ changed = True
317
+ else:
318
+ for event in agent.events + agent.also_post:
319
+ groups = hooks.setdefault(event, [])
320
+ present = any(h.get("command") == command for g in groups for h in g.get("hooks", []))
321
+ if not present:
322
+ groups.append({"matcher": "*", "hooks": [{"type": "command", "command": command}]})
323
+ changed = True
324
+ if changed:
325
+ p.parent.mkdir(parents=True, exist_ok=True)
326
+ tmp = p.with_name(p.name + ".rewindagents.tmp")
327
+ tmp.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
328
+ os.replace(tmp, p)
329
+ return changed
330
+
331
+
332
+ def uninstall(agent: Agent, settings_path: str | Path, command: str) -> bool:
333
+ """Remove the hook entries whose command is exactly `command` (the one `install` writes). Keeps every other
334
+ hook and key; a group or event list is dropped only when removing our entry left it empty.
335
+
336
+ Returns True if the file changed. When nothing matches (or the file does not exist) the file is not
337
+ rewritten, so it stays byte-identical.
338
+ """
339
+ p = Path(settings_path)
340
+ if not p.exists():
341
+ return False
342
+ text = p.read_text(encoding="utf-8")
343
+ settings = json.loads(text) if text.strip() else {}
344
+ if not isinstance(settings, dict):
345
+ raise ValueError(f"{p} does not hold a JSON object")
346
+ hooks = _hooks(agent, p, settings, create=False)
347
+ if hooks is None:
348
+ return False
349
+ changed = False
350
+ k = command_key(agent, command)
351
+ for event in agent.events + agent.also_post:
352
+ entries = hooks.get(event)
353
+ if not isinstance(entries, list):
354
+ continue
355
+ kept = []
356
+ for e in entries:
357
+ if agent.shape == "cursor":
358
+ if isinstance(e, dict) and e.get(k) == command:
359
+ changed = True
360
+ continue
361
+ elif isinstance(e, dict) and isinstance(e.get("hooks"), list):
362
+ inner = [h for h in e["hooks"] if not (isinstance(h, dict) and h.get("command") == command)]
363
+ if len(inner) != len(e["hooks"]):
364
+ changed = True
365
+ if not inner:
366
+ continue
367
+ e = {**e, "hooks": inner}
368
+ kept.append(e)
369
+ if kept != entries:
370
+ if kept:
371
+ hooks[event] = kept
372
+ else:
373
+ del hooks[event]
374
+ if not changed:
375
+ return False
376
+ if not hooks and hooks is not settings:
377
+ del settings["hooks"]
378
+ tmp = p.with_name(p.name + ".rewindagents.tmp")
379
+ tmp.write_text(json.dumps(settings, indent=2) + "\n", encoding="utf-8")
380
+ os.replace(tmp, p)
381
+ return True
382
+
383
+
384
+ def commands_in(agent: Agent, settings_path: str | Path) -> dict[str, list[str]]:
385
+ """The hook commands a config file holds, per event. Used by the tests to read back what `install` wrote."""
386
+ settings = json.loads(Path(settings_path).read_text(encoding="utf-8"))
387
+ out: dict[str, list[str]] = {}
388
+ hooks = _hooks(agent, Path(settings_path), settings, create=False) or {}
389
+ for event in agent.events + agent.also_post:
390
+ entries = hooks.get(event, [])
391
+ if agent.shape == "cursor":
392
+ out[event] = [h[k] for h in entries if isinstance(h, dict) for k in _command_keys(agent) if k in h]
393
+ else:
394
+ out[event] = [h["command"] for g in entries for h in g.get("hooks", [])]
395
+ return out
@@ -0,0 +1,230 @@
1
+ """Checkpoints for files a Bash command changes (sed -i, rm, mv, a script that rewrites files).
2
+
3
+ A Bash command does not say which files it will touch, so the hook looks at the whole project instead:
4
+ - before the command (PreToolUse), every project file's bytes go into the object store and the list of
5
+ {path: sha256} is kept in .rewindagents/pending/<call>.json;
6
+ - after it (PostToolUse), the project is scanned again and only the files that differ are checkpointed in
7
+ the "post" record: changed or deleted files with their bytes from before, new files as absent.
8
+
9
+ Project files: in a git work tree, `git ls-files --cached` plus `--others --exclude-standard` (tracked plus
10
+ untracked, but not untracked files under SKIP_DIRS such as `__pycache__/`), plus the files git ignores one by one (`.env`, `config.local.json`, `*.log`) but not the directories
11
+ it ignores as a whole (`node_modules/`, `build/`, `.venv/`): a deleted `.env` is the one file neither git nor the
12
+ agent can bring back, while an ignored directory is usually rebuilt output. Elsewhere, a walk that skips
13
+ SKIP_DIRS. Symlinks are not followed or saved.
14
+ A stat cache (.rewindagents/index.json) means only files whose size, mtime or mode changed are read again.
15
+ In the pending scan a file is "<sha256>:<permission bits in octal>", so a `chmod` alone is a change too and a
16
+ deleted script comes back executable.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import subprocess
24
+ from pathlib import Path
25
+ from typing import Any
26
+
27
+ from .hook import MAX_CHECKPOINT_BYTES, checkpoint
28
+
29
+ SKIP_DIRS = {".git", ".rewindagents", "node_modules", ".venv", "venv", "__pycache__"}
30
+ MAX_SCAN_FILES = 20000
31
+
32
+
33
+ def _ls(root: Path, *args: str) -> list[str] | None:
34
+ try:
35
+ p = subprocess.run(["git", "-C", str(root), "ls-files", "-z", *args], capture_output=True, timeout=20)
36
+ except (OSError, subprocess.TimeoutExpired):
37
+ return None
38
+ if p.returncode != 0:
39
+ return None
40
+ return [r for r in p.stdout.decode("utf-8", "surrogateescape").split("\0") if r]
41
+
42
+
43
+ def project_files(root: Path, ignored_files: bool = False) -> list[str] | None:
44
+ """Relative paths of the project's regular files, or None when there are more than MAX_SCAN_FILES.
45
+
46
+ ignored_files=True adds the files git ignores one by one, never the contents of a directory it ignores as
47
+ a whole, nor anything under SKIP_DIRS (the Bash scan uses this; `fork` does not, as a fresh worktree
48
+ would not have them)."""
49
+ rels = _ls(root, "--cached")
50
+ if rels is not None:
51
+ # untracked files under SKIP_DIRS (a __pycache__ or venv the .gitignore does not name) are rebuilt
52
+ # output, as in the walk below: scanning them turned every `python` command into .pyc "changes"
53
+ others = _ls(root, "--others", "--exclude-standard")
54
+ rels += [r for r in others or [] if not set(Path(r).parts) & SKIP_DIRS]
55
+ if rels is not None and ignored_files:
56
+ extra = _ls(root, "--others", "--ignored", "--exclude-standard", "--directory")
57
+ rels += [r for r in extra or [] if not r.endswith("/") and not set(Path(r).parts) & SKIP_DIRS]
58
+ if rels is None:
59
+ rels = []
60
+ for dirpath, dirnames, filenames in os.walk(root):
61
+ dirnames[:] = [d for d in dirnames if d not in SKIP_DIRS]
62
+ for f in filenames:
63
+ rels.append(os.path.relpath(os.path.join(dirpath, f), root))
64
+ if len(rels) > MAX_SCAN_FILES:
65
+ return None
66
+ out = []
67
+ for r in rels:
68
+ if Path(r).parts[0] in (".git", ".rewindagents"):
69
+ continue
70
+ full = root / r
71
+ if full.is_symlink() or not full.is_file():
72
+ continue
73
+ out.append(r)
74
+ return None if len(out) > MAX_SCAN_FILES else sorted(out)
75
+
76
+
77
+ def _load_index(store: Path) -> dict:
78
+ try:
79
+ idx = json.loads((store / "index.json").read_text(encoding="utf-8"))
80
+ return idx if isinstance(idx, dict) else {}
81
+ except (OSError, ValueError):
82
+ return {}
83
+
84
+
85
+ def _save_index(store: Path, idx: dict) -> None:
86
+ tmp = store / f".index.{os.getpid()}.tmp"
87
+ tmp.write_text(json.dumps(idx), encoding="utf-8")
88
+ os.replace(tmp, store / "index.json")
89
+
90
+
91
+ def snapshot(root: Path, store: Path, save: bool) -> dict[str, Any] | None:
92
+ """{relative path: sha256, or {"skipped": why}} for every project file. None if the project is too big.
93
+
94
+ With save=True every file's bytes are put in the object store (unchanged files are already there).
95
+ """
96
+ rels = project_files(root, ignored_files=True)
97
+ if rels is None:
98
+ return None
99
+ idx, new_idx = _load_index(store), {}
100
+ objects = store / "objects"
101
+ out: dict[str, Any] = {}
102
+ for r in rels:
103
+ full = root / r
104
+ try:
105
+ st = full.stat()
106
+ except OSError:
107
+ continue
108
+ if st.st_size > MAX_CHECKPOINT_BYTES:
109
+ out[r] = {"skipped": f"larger than {MAX_CHECKPOINT_BYTES} bytes",
110
+ "stat": [st.st_mtime_ns, st.st_size]}
111
+ continue
112
+ mode = st.st_mode & 0o777
113
+ cached = idx.get(r)
114
+ sha = cached[3] if (isinstance(cached, list) and len(cached) == 4
115
+ and cached[:3] == [st.st_mtime_ns, st.st_size, mode]) else None
116
+ if sha and (not save or (objects / sha).is_file()):
117
+ out[r] = sha
118
+ else:
119
+ try:
120
+ if save:
121
+ sha = checkpoint(full, objects).get("sha256")
122
+ else:
123
+ sha = hashlib.sha256(full.read_bytes()).hexdigest()
124
+ except OSError:
125
+ continue
126
+ if sha is None:
127
+ continue
128
+ out[r] = sha
129
+ new_idx[r] = [st.st_mtime_ns, st.st_size, mode, out[r]]
130
+ out[r] = "%s:%o" % (out[r], mode)
131
+ _save_index(store, new_idx)
132
+ return out
133
+
134
+
135
+ def _split(v: str) -> tuple[str, int | None]:
136
+ sha, _, mode = v.partition(":")
137
+ return sha, (int(mode, 8) if mode else None)
138
+
139
+
140
+ def _key(payload: dict) -> str:
141
+ """Pairs a call's pre and post events: Claude Code's tool_use_id, else session + input."""
142
+ tid = payload.get("tool_use_id")
143
+ basis = str(tid) if tid else json.dumps([payload.get("session_id"), payload.get("tool_input")],
144
+ sort_keys=True, default=str)
145
+ return hashlib.sha256(basis.encode("utf-8")).hexdigest()[:32]
146
+
147
+
148
+ def before(payload: dict, root: Path, store: Path) -> dict:
149
+ """PreToolUse: save every project file and remember the list. Returns what goes in the pre record:
150
+ the file count and the pending scan's name, so `gc` can say which command a stale scan belongs to."""
151
+ snap = snapshot(root, store, save=True)
152
+ if snap is None:
153
+ return {"skipped": f"more than {MAX_SCAN_FILES} files"}
154
+ pending = store / "pending"
155
+ pending.mkdir(parents=True, exist_ok=True)
156
+ key = _key(payload)
157
+ tmp = pending / f".{key}.{os.getpid()}.tmp"
158
+ tmp.write_text(json.dumps(snap), encoding="utf-8")
159
+ os.replace(tmp, pending / f"{key}.json")
160
+ return {"files": len(snap), "pending": key}
161
+
162
+
163
+ def after(payload: dict, root: Path, store: Path, afters: list | None = None) -> tuple[dict, list[dict]]:
164
+ """PostToolUse: the checkpoints for files the command changed, created or deleted. When `afters` is a
165
+ list, one entry per such file is appended to it with its hash right after the command (hook.after_hash's
166
+ shape: {"path", "after": sha256 or None, with "sha256" and "mode" when a copy is stored}, or
167
+ {"path", "skipped"})."""
168
+ pend = store / "pending" / f"{_key(payload)}.json"
169
+ try:
170
+ old = json.loads(pend.read_text(encoding="utf-8"))
171
+ except (OSError, ValueError):
172
+ return {"skipped": "no scan from before the command"}, []
173
+ pend.unlink(missing_ok=True)
174
+ new = snapshot(root, store, save=False)
175
+ if new is None:
176
+ return {"skipped": f"more than {MAX_SCAN_FILES} files"}, []
177
+ cps: list[dict] = []
178
+ for r in sorted(set(old) | set(new)):
179
+ was, now = old.get(r), new.get(r)
180
+ if was == now:
181
+ continue
182
+ path = str(root / r)
183
+ if was is None:
184
+ cps.append({"path": path, "sha256": None}) # created by the command
185
+ elif isinstance(was, dict):
186
+ cps.append({"path": path, "sha256": None, "skipped": was["skipped"]})
187
+ else:
188
+ sha, mode = _split(was)
189
+ cp = {"path": path, "sha256": sha} # changed or deleted
190
+ if mode is not None:
191
+ cp["mode"] = mode
192
+ cps.append(cp)
193
+ if afters is not None:
194
+ if isinstance(now, dict):
195
+ afters.append({"path": path, "skipped": now["skipped"]})
196
+ elif now is None: # deleted by the command
197
+ afters.append({"path": path, "after": None})
198
+ else:
199
+ afters.append(_after_copy(Path(path), store / "objects", *_split(now)))
200
+ scan: dict[str, Any] = {"changed": len(cps)}
201
+ if background(payload):
202
+ scan["early"] = EARLY
203
+ return scan, cps
204
+
205
+
206
+ def _after_copy(path: Path, objects: Path, sha: str, mode: int | None) -> dict:
207
+ """The after entry for a file the command changed: its hash from the scan, plus a stored copy ("sha256",
208
+ "mode") when the bytes are still the scanned ones (`revert` merges from them). A file that changed again
209
+ between the scan and the copy keeps the scan's hash only."""
210
+ entry: dict[str, Any] = {"path": str(path), "after": sha}
211
+ try:
212
+ cp = checkpoint(path, objects)
213
+ except OSError:
214
+ return entry
215
+ if cp.get("sha256") == sha:
216
+ entry["sha256"] = sha
217
+ entry["mode"] = cp["mode"] if mode is None else mode
218
+ return entry
219
+
220
+
221
+ EARLY = "run_in_background: the after-scan may have run before the command finished"
222
+
223
+
224
+ def background(payload: dict) -> bool:
225
+ """Claude Code's Bash input carries `run_in_background` ("Whether to run the command in background",
226
+ https://code.claude.com/docs/en/hooks, read 2026-11-12). The same page documents no hook event for a
227
+ background shell finishing, so the after-scan of such a call may run while the command is still going:
228
+ files it changes later are missing from this step's checkpoints."""
229
+ ti = payload.get("tool_input")
230
+ return isinstance(ti, dict) and ti.get("run_in_background") is True