SuperAPI AI 工具集

cc-hook-authoring

通用与其它

查看项目

更新于 10-16 05:52

技能介绍

用途:本技能讲解如何设计、安装和调试 Claude Code 钩子。钩子是 Claude Code 的自动化入口,即在生命周期事件上触发的确定性 shell 脚本;每次执行从 stdin 读取 JSON,向 stdout 写回 JSON(如 {"decision":"approve"|"block","reason"?:"..."})。所有钩子还能读到 session_id、transcript_path、cwd、permission_mode、hook_event_name 等公共字段。

主要能力:覆盖多种事件。PreToolUse 在任何工具前触发,可返回 permissionDecision 为 allow|deny|ask|defer,并支持 updatedInput、additionalContext;PostToolUse 在工具成功后触发;PostToolUseFailure 在工具失败后触发;UserPromptSubmit、Notification、Stop、SessionStart、SessionEnd、PreCompact、SubagentStart、SubagentStop、TeammateIdle、PermissionRequest、Setup 也各有输入输出契约。其中可阻断的事件为 PreToolUse、Stop、UserPromptSubmit、SubagentStart、TeammateIdle、PermissionRequest,其余为只观察。

使用方式:可用 MCP 工具 cc_kb_hook_recipe(name) 获取加固过的钩子包,返回 script、script_path、settings_snippet、verify;先用 cc_docs_hook_pack_recommend(signals) 获取推荐。内置包包括 protect-sensitive-files、auto-format-after-edit、stop-until-tests-pass、post-compact-context-restoration、direnv-reload-on-cwd-change、task-created-governance、task-completed-quality-gate、teammate-idle-enforcement。新钩子以 bash 编写,需用 head -c 限制输入、用 jq 校验 JSON、realpath 与 PWD 前缀检查、拒绝以 - 开头的文件名、出错时默认返回 approve。在 .claude/settings.json 的 hooks 中按事件与正则 matcher 注册。

限制与注意事项:钩子不应调用 LLM(慢且不确定),不应做 rm -rf 等删除操作,不应吞错不返回 approve 以免会话挂起,同一事件多个钩子相互冲突时应顺序执行或用不同 matcher;PreToolUse 目标耗时小于 100ms,PostToolUse 小于 500ms。调试可检查 settings.json 的事件与 matcher、查看 stderr、用 time 测量、本地以 fixture.json 测试 JSON 解析。