Skip to content

Commit 1c5cab0

Browse files
authored
Share Claude and Codex hook scripts (#19755)
## Summary - add repo-local Codex hooks matching the existing Claude hooks - move the hook implementations into `scripts/hooks` so both agents share one implementation - handle Codex `apply_patch` payloads in the post-edit formatter - keep other repo-local `.codex` state ignored while tracking `.codex/hooks.json` ## Validation - `python3 -m json.tool .claude/settings.json` - `python3 -m json.tool .codex/hooks.json` - `bash -n scripts/hooks/session-start.sh` - `bash -n scripts/hooks/session-start-web.sh` - exercised `uv run scripts/hooks/post-edit-format.py` with Claude `Write` and Codex `apply_patch` payloads
1 parent 535643a commit 1c5cab0

7 files changed

Lines changed: 142 additions & 80 deletions

File tree

‎.claude/hooks/post-edit-format.py‎

Lines changed: 0 additions & 77 deletions
This file was deleted.

‎.claude/settings.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
"hooks": [
77
{
88
"type": "command",
9-
"command": ".claude/hooks/session-start.sh"
9+
"command": "bash scripts/hooks/session-start.sh"
1010
}
1111
]
1212
}
@@ -17,7 +17,7 @@
1717
"hooks": [
1818
{
1919
"type": "command",
20-
"command": "uv run .claude/hooks/post-edit-format.py"
20+
"command": "uv run scripts/hooks/post-edit-format.py"
2121
}
2222
]
2323
}

‎.codex/hooks.json‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
{
2+
"hooks": {
3+
"SessionStart": [
4+
{
5+
"matcher": "startup",
6+
"hooks": [
7+
{
8+
"type": "command",
9+
"command": "bash scripts/hooks/session-start.sh"
10+
}
11+
]
12+
}
13+
],
14+
"PostToolUse": [
15+
{
16+
"matcher": "Edit|Write|MultiEdit",
17+
"hooks": [
18+
{
19+
"type": "command",
20+
"command": "uv run scripts/hooks/post-edit-format.py"
21+
}
22+
]
23+
}
24+
]
25+
}
26+
}

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,7 @@ profile.json.gz
5151
# IDE
5252
.idea
5353
.vscode
54+
55+
# Codex
56+
.codex/*
57+
!.codex/hooks.json

‎scripts/hooks/post-edit-format.py‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
# /// script
2+
# requires-python = ">=3.12"
3+
# dependencies = []
4+
# ///
5+
6+
"""Post-edit hook to auto-format files after agent edits."""
7+
8+
import json
9+
import os
10+
import subprocess
11+
import sys
12+
from pathlib import Path
13+
14+
15+
def format_rust(file_path: str, cwd: str) -> None:
16+
"""Format Rust files with cargo fmt."""
17+
try:
18+
subprocess.run(
19+
["cargo", "fmt", "--", file_path],
20+
cwd=cwd,
21+
capture_output=True,
22+
)
23+
except FileNotFoundError:
24+
pass
25+
26+
27+
def format_python(file_path: str, cwd: str) -> None:
28+
"""Format Python files with ruff."""
29+
try:
30+
subprocess.run(
31+
["uvx", "ruff", "format", file_path],
32+
cwd=cwd,
33+
capture_output=True,
34+
)
35+
except FileNotFoundError:
36+
pass
37+
38+
39+
def format_prettier(file_path: str, cwd: str) -> None:
40+
"""Format files with prettier."""
41+
try:
42+
subprocess.run(
43+
["npx", "prettier", "--write", file_path], cwd=cwd, capture_output=True
44+
)
45+
except FileNotFoundError:
46+
pass
47+
48+
49+
def patch_file_paths(command: str) -> list[str]:
50+
"""Return added or updated file paths from an `apply_patch` payload."""
51+
file_paths: list[str] = []
52+
current_update_index: int | None = None
53+
54+
for line in command.splitlines():
55+
if line.startswith("*** Add File: "):
56+
file_paths.append(line.removeprefix("*** Add File: "))
57+
current_update_index = None
58+
elif line.startswith("*** Update File: "):
59+
file_paths.append(line.removeprefix("*** Update File: "))
60+
current_update_index = len(file_paths) - 1
61+
elif line.startswith("*** Move to: ") and current_update_index is not None:
62+
file_paths[current_update_index] = line.removeprefix("*** Move to: ")
63+
current_update_index = None
64+
elif line.startswith("*** Delete File: "):
65+
current_update_index = None
66+
67+
return list(dict.fromkeys(file_paths))
68+
69+
70+
def edited_file_paths(input_data: dict[str, object]) -> list[str]:
71+
tool_name = input_data.get("tool_name")
72+
tool_input = input_data.get("tool_input")
73+
if not isinstance(tool_input, dict):
74+
return []
75+
76+
if tool_name in ("Write", "Edit", "MultiEdit"):
77+
file_path = tool_input.get("file_path")
78+
return [file_path] if isinstance(file_path, str) and file_path else []
79+
80+
if tool_name == "apply_patch":
81+
command = tool_input.get("command")
82+
return patch_file_paths(command) if isinstance(command, str) else []
83+
84+
return []
85+
86+
87+
def format_file(file_path: str, cwd: str) -> None:
88+
ext = Path(file_path).suffix
89+
90+
if ext == ".rs":
91+
format_rust(file_path, cwd)
92+
elif ext in (".py", ".pyi"):
93+
format_python(file_path, cwd)
94+
elif ext in (".json5", ".yaml", ".yml", ".md"):
95+
format_prettier(file_path, cwd)
96+
97+
98+
def main() -> None:
99+
input_data = json.load(sys.stdin)
100+
cwd = input_data.get("cwd")
101+
if not isinstance(cwd, str) or not cwd:
102+
cwd = os.environ.get("CLAUDE_PROJECT_DIR", os.getcwd())
103+
104+
for file_path in edited_file_paths(input_data):
105+
format_file(file_path, cwd)
106+
107+
108+
if __name__ == "__main__":
109+
main()
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@ set -euo pipefail
33

44
# Dispatch to web hook if running remotely
55
if [ "${CLAUDE_CODE_REMOTE:-}" = "true" ]; then
6-
exec "$(dirname "$0")/session-start-web.sh"
6+
exec bash "$(dirname "$0")/session-start-web.sh"
77
fi

0 commit comments

Comments
 (0)