"""Check config data, a hook handler contract and real command-rule matching."""
from hashlib import sha256
import json
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
import tomllib
CONFIG = """
approval_policy = "on-request"
sandbox_mode = "read-only"
[agents]
max_threads = 3
max_depth = 1
[[hooks.PostToolUse]]
matcher = "^Bash$"
[[hooks.PostToolUse.hooks]]
type = "command"
command = "python hook_observer.py"
timeout = 5
"""
ROLE = '''
name = "test_reader"
description = "Check test evidence"
developer_instructions = "Report failing assertions and the command used."
'''
RULES = """prefix_rule(pattern=["fixture", "inspect"], decision="allow")
prefix_rule(pattern=["fixture", "change"], decision="prompt")
prefix_rule(pattern=["fixture", "change", "production"], decision="forbidden")
"""
HOOK = """import json
import sys
data = json.load(sys.stdin)
if data.get("hook_event_name") == "PostToolUse" and data.get("tool_name") == "Bash":
print(json.dumps({"systemMessage":"Check the exit status and output."}))
"""
def case(name, input_data, operation, expected, actual):
assert actual == expected, (name, actual)
return dict(name=name, input=input_data, operation=operation, expected=expected, actual=actual)
def cli(args, root):
executable = shutil.which("codex.exe") or shutil.which("codex")
if not executable:
raise RuntimeError("Install Codex CLI before running the rule examples")
result = subprocess.run([executable, *args], cwd=root, capture_output=True,
encoding="utf-8", timeout=15, check=True)
return result.stdout.strip()
def exercise(root):
cfg = tomllib.loads(CONFIG)
role = tomllib.loads(ROLE)
actual = [cfg["approval_policy"], cfg["sandbox_mode"], cfg["agents"]["max_threads"],
cfg["agents"]["max_depth"], role["name"]]
cases = [case("config_profile_fields", ["CONFIG","ROLE"], "Parse separate TOML examples",
["on-request","read-only",3,1,"test_reader"], actual)]
hook = root / "hook_observer.py"
hook.write_bytes(HOOK.encode("utf-8"))
command = cfg["hooks"]["PostToolUse"][0]["hooks"][0]
assert command["command"] == "python hook_observer.py"
for tool, expected in (("Bash", {"systemMessage":"Check the exit status and output."}), ("Read", None)):
payload = {"hook_event_name": "PostToolUse", "tool_name": tool}
process = subprocess.run([sys.executable, "-I", str(hook)], cwd=root, input=json.dumps(payload),
capture_output=True, encoding="utf-8", check=True, timeout=command["timeout"])
actual = json.loads(process.stdout) if process.stdout else None
cases.append(case(f"config_hook_{tool}", payload, "Run our handler with an explicit event payload",
expected, actual))
rules = root / "exercise.rules"
rules.write_bytes(RULES.encode("utf-8"))
for tokens, expected in ((["fixture","inspect"], "allow"),
(["fixture","change","draft"], "prompt"),
(["fixture","change","production"], "forbidden")):
actual = json.loads(cli(["execpolicy","check","--rules",str(rules),"--",*tokens], root))["decision"]
cases.append(case("config_rule_"+expected, tokens, "Run Codex rule checker on command tokens",
expected, actual))
return dict(version={"python":sys.version.split()[0],"codex":cli(["--version"],root)}, cases=cases,
hook_sha256=sha256(hook.read_bytes()).hexdigest(),
codex_sha256=sha256(Path(shutil.which("codex.exe") or shutil.which("codex")).read_bytes()).hexdigest())
if __name__ == "__main__":
with TemporaryDirectory(prefix="mbsky-config-training-") as directory:
print(json.dumps(exercise(Path(directory))))
本例需在 Windows,CPython 3.12.14,codex-cli 0.167.0-alpha.4.1。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows,CPython 3.12.14,codex-cli 0.167.0-alpha.4.1。
入口文件:projects/codex-config/config_lab.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
config_lab.py,或下载右侧课程工程包。 - 确认本地已准备 Windows,CPython 3.12.14,codex-cli 0.167.0-alpha.4.1。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a90.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a102.zip