Codex 规则与钩子:命令范围、事件和脚本结果
区分 AGENTS.md、命令规则与生命周期钩子,并检查真实注册、信任和脚本返回。
学完这一章,你能够
- 区分 AGENTS.md、命令规则与生命周期钩子,并检查真实注册、信任和脚本返回。
给项目约定、命令与事件选合适的配置
缩进、代码风格、公开函数注释、调试输出、测试位置和提交约定可写入 AGENTS.md,或者链接到适用的项目规范。把项目测试命令写清,交给用户、持续集成或适用的运行脚本执行。
Codex 的 .rules 是命令执行决策。用户级与信任的项目配置层可有 rules/ 目录,具体加载与管理措施按当前客户端核对。命令前缀、审批和沙箱各作用于所配置的权限范围。
Hooks 面向生命周期事件,并接受命令或受支持的 MCP 处理器。历史的 features.codex_hooks 和 event/action 数组样例应按当前版本对照。当前 JSON 通常用 hooks 对象按事件分组,组中指定可用的 matcher 和处理器。也可按当前文档写入 TOML。
按实际事件确定何时执行
PreToolUse 可在受支持工具运行前检查输入。PostToolUse 发生在调用已完成后,可记录或反馈结果。验收测试可设计在适当的工具后事件或 Stop,由脚本选择实际覆盖的变更。SessionStart 表示会话开始或恢复,UserPromptSubmit 处理用户提交的提示而非任意消息。
本站从独立临时配置列出 PreToolUse 与 Stop,并观测两个新条目都是 untrusted。新配置需要按客户端检查信任和授权。下图的事件名和信任状态来自真实本机查询。

工具事件可用支持的匹配表达式,按实际工具名区分 Bash、受支持编辑和 MCP 调用。旧 on_error 泛化写法需要按错误来源处理,例如检查调用结果或脚本退出状态。事件与通知不意味着会替任务决定是否提交。
实际测试脚本输入、输出及失败路径
命令处理器通过标准输入读取 JSON,按事件约定返回结果或退出。本站独立运行处理脚本。普通样例命令返回空结果,保护目标返回拒绝。Stop 首次可以请求补充验收,在已处理过的条件下结束。脚本结果由本机进程实测,Codex 真实回合内的执行仍待验。
提交前检查可用 Git hook 或可信 CI 保护,Codex 的工具前钩子可另行匹配提交命令并给出原因。CLI 的 /review 是交互入口。自动审查流程可用独立的 API 或命令入口及相应授权。
最小化记录字段,分开保存事件、输入摘要和结果,避免日志携带秘密。通知和日志由脚本明确实现并接受实际安装环境验证。设置合理超时,按事件核对脚本退出值、失败反馈与工具能否继续。同一事件的多个处理器可能并发启动。
旧事件名与现代选项
| 旧写法 | 要验证的实际行为 |
|---|---|
| on_tool_call | 改用相应 PreToolUse 或 PostToolUse,区别调用前和完成后。 |
| on_task_start | 会话启动与用户本次提交分别考虑 SessionStart 和 UserPromptSubmit。 |
| on_task_complete | 按当前回合所需验收使用 Stop,或按会话结束场景检查 SessionEnd。 |
| on_error | 用支持事件的失败反馈或实际错误结果处置,旧通用事件需核对。 |
| on_message | 用 UserPromptSubmit 处理用户提交的提示。 |
旧动作名与脚本返回
| 旧写法 | 当前核对 |
|---|---|
| allow | 按事件协议允许继续,检查实际有效决定。 |
| deny | PreToolUse 可按协议拒绝并给原因,实际调度仍按信任条件。 |
| notify | 可由脚本处理授权通知,先独立验证输入和副作用。 |
| log | 用自编脚本记录适用字段及其访问边界。 |
| custom | 用支持的 command 等处理器,核对真实退出码与返回体。 |
规则、指令和钩子
| 维度 | 适用位置 |
|---|---|
| 作用时机 | 项目指令在会话使用,.rules 在命令决策时应用,钩子按事件执行。 |
| 主要用途 | 项目指令提供约定,规则决定命令,钩子运行事件处置。 |
| 配置位置 | 项目指令用 AGENTS.md,命令规则用 rules/,事件用 hooks.json 或支持的内联配置。 |
核对已注册的事件并实际运行脚本
"""Check the installed Codex hook registry and test an independent policy handler."""
from hashlib import sha256
import json
import os
from pathlib import Path
from queue import Queue
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from threading import Thread
from time import monotonic
HANDLER = '''import json
import sys
data = json.load(sys.stdin)
if data.get("hook_event_name") == "PreToolUse":
command = data.get("tool_input", {}).get("command", "")
if command == "fixture-write protected":
result = {"hookSpecificOutput":{"hookEventName":"PreToolUse",
"permissionDecision":"deny","permissionDecisionReason":"Protected fixture."}}
else:
result = {}
print(json.dumps(result))
elif data.get("hook_event_name") == "Stop":
print(json.dumps({"decision":"block","reason":"Verify the fixture once more."}
if not data.get("stop_hook_active") else {}))
else:
print("{}")
'''
class Server:
def __init__(self, process):
self.process = process
self.messages = Queue()
self.reader = Thread(target=self.receive, daemon=True)
self.reader.start()
def receive(self):
for line in self.process.stdout:
self.messages.put(json.loads(line))
self.messages.put(None)
def request(self, method, params=None, request_id=None):
message = {"method":method,"jsonrpc":"2.0"}
if params is not None:
message["params"] = params
if request_id is not None:
message["id"] = request_id
self.process.stdin.write(json.dumps(message) + "\n")
self.process.stdin.flush()
if request_id is None:
return None
deadline = monotonic() + 8
while True:
result = self.messages.get(timeout=max(0, deadline - monotonic()))
if result is None:
raise RuntimeError("Local app server closed its stream.")
if result.get("id") == request_id:
assert "error" not in result, result
return result["result"]
def close(self):
self.process.stdin.close()
try:
self.process.wait(timeout=5)
except subprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
self.reader.join(timeout=2)
def main():
codex = shutil.which("codex.exe") or shutil.which("codex")
if not codex:
raise SystemExit("Put Codex CLI on PATH.")
cases = []
def check(name, inputs, action, expect, actual):
assert actual==expect,(name,expect,actual)
cases.append(dict(name="hooks_"+name,input=inputs,operation=action,expected=expect,actual=actual))
with TemporaryDirectory(prefix="mbsky-hooks-check-") as temporary:
root = Path(temporary)
home = root / "local-profile"
home.mkdir()
handler = root / "fixture_hook.py"
handler.write_bytes(HANDLER.encode())
command = f'python "{handler}"'
config = {"hooks":{
"PreToolUse":[{"matcher":"^Bash$","hooks":[{"type":"command","command":command,"timeout":5}]}],
"Stop":[{"hooks":[{"type":"command","command":command,"timeout":4}]}],
}}
(home/"hooks.json").write_bytes(json.dumps(config).encode())
env = dict(os.environ,CODEX_HOME=str(home))
version = subprocess.run([codex,"--version"],cwd=root,env=env,encoding="utf8",
capture_output=True,check=True,timeout=10).stdout.strip()
with subprocess.Popen([codex,"app-server","--stdio"],cwd=root,env=env,stdin=subprocess.PIPE,
stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,encoding="utf8") as process:
client=Server(process)
try:
client.request("initialize",{"clientInfo":{"name":"mbsky-hook-lab","version":"1"}},1)
client.request("initialized")
response=client.request("hooks/list",{"cwd":str(root)},2)
group,=response["data"]
assert not group["errors"] and not group["warnings"]
registered = {hook["eventName"]:hook for hook in group["hooks"]}
check("registry", {"events":list(config["hooks"]),"timeouts":[5,4]},
"List the actual temporary hook registry over stdio",
[["preToolUse","command",5,"^Bash$"],["stop","command",4,None]],
[[row["eventName"],row["handlerType"],row["timeoutSec"],row["matcher"]]
for row in (registered["preToolUse"],registered["stop"])])
check("trust","New hooks in a fresh profile",
"Read the real trust state without sending a turn request",
["untrusted","untrusted"],[registered[name]["trustStatus"] for name in ("preToolUse","stop")])
finally:
client.close()
assert process.returncode == 0
def run_hook(data):
result=subprocess.run([sys.executable,"-I","-B",str(handler)],cwd=root,input=json.dumps(data),
capture_output=True,text=True,encoding="utf8",check=True,timeout=5)
return json.loads(result.stdout)
data = [{"hook_event_name":"PreToolUse","tool_input":{"command":command}}
for command in ("fixture-read","fixture-write protected")]
outputs=[run_hook(item) for item in data]
check("script_filter",data,"Feed a real child process two locally generated tool events",
["继续","拒绝"],["拒绝" if row.get("hookSpecificOutput",{}).get("permissionDecision")=="deny" else "继续"
for row in outputs])
data = [{"hook_event_name":"Stop","stop_hook_active":active} for active in (False,True)]
outputs=[run_hook(item) for item in data]
check("script_stop",data,"Exercise the script once before and once after an earlier continuation",
["补充检查","结束"],["补充检查" if row.get("decision")=="block" else "结束" for row in outputs])
print(json.dumps(dict(version={"python":sys.version.split()[0],"codex":version},
codex_sha256=sha256(Path(codex).read_bytes()).hexdigest(),
handler_sha256=sha256(HANDLER.encode()).hexdigest(),cases=cases)))
if __name__=="__main__":
main()
- 临时配置的两个条目都已列出且未受信。独立脚本拒绝指定保护目标,Stop 仅请求一次补充检查。
所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
当前源码 SHA256:2544ca461591c8f6cf4f1907ccc87cf6a21499d0350a1d75760f7e3e0ff32471
本机钩子练习 ZIP
含临时配置与脚本运行检查、说明及浏览器观测。
所需环境:Windows、Python 3.12.14、codex-cli 0.167.0-alpha.4.1。
ZIP SHA256:6795573cfb8f9f2c289f63ddd95b240964e5d92617074c02256a1ed9bf043dc9
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
增加一组保护命令变体,并为它定义预期。
展开参考解答
确认临时配置不变时,脚本的明确输入会得到对应结果。