Token导航 LogoToken导航TokenDH.com
研究检索敏感数据github未标认证来源可访问许可证需确认审计通过

enhance-hooks增强挂钩

Agent Skill

enhance-hooks 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

1,088

周安装

44

GitHub Stars

769

下载量

341
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:enhance-hooks(增强挂钩)
来源仓库:https://github.com/avifenesh/agentsys
仓库路径:skills/enhance-hooks
安装命令:
npx skills add https://github.com/avifenesh/agentsys --skill enhance-hooks
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/avifenesh/agentsys --skill enhance-hooks

简介

用于分析钩子定义与脚本安全性,确保事件响应正确可靠。

  • 适合在 .md、.sh、.json 等钩子文件中发现潜在风险与最佳实践偏差。
  • 自动检查命令注入、权限越界与资源泄漏等问题,并提供修复建议。
  • 仅对高确定性问题推荐自动修复,中低风险需人工介入确认。
  • enhance-hooks 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

enhance-hooks

Analyze hook definitions and scripts for safety, correctness, and best practices.

Parse Arguments

const args = '$ARGUMENTS'.split(' ').filter(Boolean);
const targetPath = args.find(a => !a.startsWith('--')) || '.';
const fix = args.includes('--fix');

Workflow

  1. Discover - Find hook files (.md,.sh,.json)
  2. Classify - Identify hook type and event
  3. Parse - Extract frontmatter and script content
  4. Check - Run all pattern checks against knowledge below
  5. Filter - Apply certainty filtering
  6. Report - Generate markdown output
  7. Fix - Apply auto-fixes if --fix flag present

Hook Knowledge Reference

What Are Hooks

Hooks are automated actions triggered at specific points in a Claude Code session. They enable validation, monitoring, and control of Claude's actions through bash commands or LLM-based evaluation.

Hook Lifecycle (Complete Reference)

Hooks fire in this sequence:

OrderEventDescriptionMatcher Required
1SessionStartSession begins or resumesNo
2UserPromptSubmitUser submits a promptNo
3PreToolUseBefore tool execution (can modify/block)Yes
4PermissionRequestWhen permission dialog appearsYes
5PostToolUseAfter tool succeedsYes
6SubagentStartWhen spawning a subagentNo
7SubagentStopWhen subagent finishesNo
8StopClaude finishes respondingNo
9PreCompactBefore context compactionNo
10SessionEndSession terminatesNo
11NotificationClaude Code sends notificationsNo

Hook Types

Command Hooks (type: "command"):

  • Execute bash commands with full stdin/stdout control
  • Available for all events

Prompt Hooks (type: "prompt"):

  • Use LLM evaluation for intelligent, context-aware decisions
  • Only supported for Stop and SubagentStop events

Configuration Locations

FileLocationScopeCommitted
User settings~/.claude/settings.jsonAll projectsNo
Project settings.claude/settings.jsonCurrent projectYes
Local settings.claude/settings.local.jsonCurrent projectNo

Configuration Structure

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/validate-bash.sh",
            "timeout": 30
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/format-code.sh"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Check if all requested tasks are complete.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Matcher Syntax

PatternDescription
WriteMatch exact tool name
`Edit\Write`Match multiple tools (regex OR)
Notebook.*Regex pattern matching
* or ""Match all tools
(omitted)Required for Stop, SubagentStop, UserPromptSubmit

Input Schema (JSON via stdin)

All hooks receive this JSON structure:

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript",
  "cwd": "/project/root",
  "permission_mode": "default",
  "hook_event_name": "PreToolUse",
  "tool_name": "Bash",
  "tool_input": {
    "command": "npm test",
    "description": "Run test suite"
  }
}

Exit Codes

Exit CodeBehavior
0Success - stdout shown to user or added as context
2Blocking error - stderr shown, action blocked
OtherNon-blocking error - stderr shown in verbose mode

Output Schemas

PreToolUse Decision Control:

{
  "hookSpecificOutput": {
    "hookEventName": "PreToolUse",
    "permissionDecision": "allow|deny|ask",
    "permissionDecisionReason": "Reason for decision",
    "updatedInput": {
      "command": "modified command"
    },
    "additionalContext": "Context for Claude"
  }
}

Stop/SubagentStop Control:

{
  "decision": "block",
  "reason": "Tasks incomplete: missing test coverage"
}

Environment Variables

VariableDescriptionAvailable In
CLAUDE_PROJECT_DIRAbsolute path to project rootAll hooks
CLAUDE_CODE_REMOTE"true" if remote sessionAll hooks
CLAUDE_ENV_FILEPath to persist env varsSessionStart only
CLAUDE_FILE_PATHSSpace-separated file pathsPostToolUse (Write/Edit)

Practical Hook Examples

Security Firewall (PreToolUse):

#!/usr/bin/env bash
set -euo pipefail

cmd=$(jq -r '.tool_input.command // ""')

# Block dangerous patterns
if echo "$cmd" | grep -qE 'rm -rf|git reset --hard|curl.*\|.*sh'; then
  echo '{"decision": "block", "reason": "Dangerous command blocked"}' >&2
  exit 2
fi

exit 0

Auto-Formatter (PostToolUse):

#!/usr/bin/env bash
set -euo pipefail

files=$(jq -r '.tool_input.file_path // ""')

for file in $files; do
  case "$file" in
    *.py) black "$file" 2>/dev/null || true ;;
    *.js|*.ts) prettier --write "$file" 2>/dev/null || true ;;
  esac
done

exit 0

Command Logger (PreToolUse):

#!/usr/bin/env bash
set -euo pipefail
cmd=$(jq -r '.tool_input.command // ""')
printf '%s %s\n' "$(date -Is)" "$cmd" >> .claude/bash-commands.log
exit 0

Workflow Orchestration (SubagentStop - prompt type):

{
  "hooks": {
    "SubagentStop": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Review the subagent's work. Did it complete all tasks?"
          }
        ]
      }
    ]
  }
}

Detection Patterns

1. Frontmatter Validation (HIGH Certainty)

Required:

  • YAML frontmatter with --- delimiters
  • name field in frontmatter
  • description field in frontmatter

Recommended:

  • timeout for command hooks (default: 30s)
  • Hook type specification

Flag:

  • Missing frontmatter delimiters
  • Missing name or description

2. Script Safety (HIGH Certainty)

Required Safety Patterns:

  • set -euo pipefail at script start
  • Error handling for jq/JSON parsing
  • Proper quoting of variables

Dangerous Patterns to Flag:

PatternRiskCertainty
rm -rfDestructive without confirmationHIGH
git reset --hardData loss riskHIGH
`curl \sh`Remote code executionHIGH
eval "$input"Arbitrary code executionHIGH
rm -rRecursive delete (may be intentional)MEDIUM
git push --forceForce push (may be intentional)MEDIUM

3. Exit Code Handling (HIGH Certainty)

Check: Scripts use correct exit codes

Flag:

  • Missing exit 0 for success path
  • Using exit code 1 for blocking (should be 2)
  • No exit code at end of script

4. Hook Type Appropriateness (HIGH Certainty)

Check: Hook type matches event

Flag:

  • Prompt hooks used for events other than Stop/SubagentStop
  • Missing type specification

5. Lifecycle Event Appropriateness (MEDIUM Certainty)

EventAppropriate Use Cases
PreToolUseSecurity validation, command blocking, input modification
PostToolUseFormatting, logging, notifications
StopCompletion checks, cleanup, summary
SubagentStopWorkflow orchestration, result validation
SessionStartEnvironment setup, initialization

Flag:

  • PostToolUse hooks trying to block actions (too late)
  • PreToolUse hooks doing heavy processing (should be fast)
  • Prompt hooks on unsupported events

6. Timeout Configuration (MEDIUM Certainty)

Guidelines:

  • Default: 30 seconds for command hooks
  • Network operations: Always set explicit timeout
  • External service calls: Set timeout based on expected latency

Flag:

  • No timeout for network operations
  • Timeout missing for external service calls
  • Unreasonably long timeouts (>60s without justification)

7. Output Format (MEDIUM Certainty)

PreToolUse Output Fields:

  • permissionDecision: allow, deny, or ask
  • permissionDecisionReason: Explanation for decision
  • updatedInput: Modified tool input (optional)
  • additionalContext: Context for Claude (optional)

Flag:

  • Invalid permissionDecision values
  • Missing reason for deny decisions
  • Malformed JSON output

8. Matcher Patterns (MEDIUM Certainty)

Check: Matcher syntax is valid

Flag:

  • Invalid regex patterns
  • Too broad matchers (* without justification)
  • Matcher on events that don't support it (Stop, SubagentStop)

9. Anti-Patterns (LOW Certainty)

  • Complex logic in hooks (should be simple and fast)
  • Missing documentation/comments
  • Hardcoded paths (should use $CLAUDE_PROJECT_DIR)
  • Network calls without error handling
  • Secrets/credentials in hook scripts

Auto-Fix Implementations

1. Missing safety header

#!/usr/bin/env bash
set -euo pipefail

2. Missing exit code

Add exit 0 at end of script

3. Missing frontmatter fields

---
name: hook-name
description: Hook description
timeout: 30
---

4. Wrong blocking exit code

Replace exit 1 with exit 2 for blocking errors


Output Format

## Hook Analysis: {hook-name}

**File**: {path}
**Type**: {command|prompt|config}
**Event**: {PreToolUse|PostToolUse|Stop|...}

### Summary
- HIGH: {count} issues
- MEDIUM: {count} issues

### Frontmatter Issues ({n})
| Issue | Fix | Certainty |

### Safety Issues ({n})
| Issue | Fix | Certainty |

### Exit Code Issues ({n})
| Issue | Fix | Certainty |

### Lifecycle Issues ({n})
| Issue | Fix | Certainty |

### Output Format Issues ({n})
| Issue | Fix | Certainty |

Pattern Statistics

CategoryPatternsAuto-Fixable
Frontmatter32
Safety62
Exit Code32
Hook Type20
Lifecycle50
Timeout30
Output30
Matcher30
Anti-Pattern50
Total336

<bad_example>

#!/usr/bin/env bash
cmd=$(jq -r '.tool_input.command // ""')

Why it's bad: Missing set -euo pipefail means errors may silently pass. </bad_example>

<good_example>

#!/usr/bin/env bash
set -euo pipefail
cmd=$(jq -r '.tool_input.command // ""')

Why it's good: Fails fast on errors, unset variables, and pipe failures. </good_example>

Example: Wrong Exit Code for Blocking

<bad_example>

if [[ "$cmd" == *"rm -rf"* ]]; then
  echo "Blocked dangerous command" >&2
  exit 1  # Wrong!
fi

Why it's bad: Exit code 1 is non-blocking. Action will still proceed. </bad_example>

<good_example>

if [[ "$cmd" == *"rm -rf"* ]]; then
  echo '{"decision": "block", "reason": "Dangerous command"}' >&2
  exit 2  # Correct blocking exit code
fi

Why it's good: Exit code 2 blocks the action. JSON output provides context. </good_example>

Example: Prompt Hook on Wrong Event

<bad_example>

{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [{ "type": "prompt", "prompt": "Is this safe?" }]
      }
    ]
  }
}

Why it's bad: Prompt hooks only work for Stop and SubagentStop events. </bad_example>

<good_example>

{
  "hooks": {
    "PreToolUse": [
      {
        "hooks": [{ "type": "command", "command": "./validate.sh" }]
      }
    ]
  }
}

Why it's good: Command hooks work for all events. </good_example>

Example: Dangerous Command Pattern

<bad_example>

if echo "$cmd" | grep -q 'rm'; then
  exit 2
fi

Why it's bad: Too broad - blocks legitimate rm file.tmp. </bad_example>

<good_example>

if echo "$cmd" | grep -qE 'rm\s+(-rf|-fr)\s+/'; then
  exit 2
fi

Why it's good: Specific pattern targets actual dangerous commands. </good_example>

Example: Hardcoded Path

<bad_example>

log_file="/home/user/project/.claude/commands.log"

Why it's bad: Hardcoded path breaks on other machines. </bad_example>

<good_example>

log_file="$CLAUDE_PROJECT_DIR/.claude/commands.log"

Why it's good: Uses environment variable for portability. </good_example>


Constraints

  • Only apply auto-fixes for HIGH certainty issues
  • Be cautious about security patterns - false negatives worse than false positives
  • Never remove content, only suggest improvements
  • Validate against embedded knowledge reference above

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.53%
按下载量换算118

Claude

32.83%
按下载量换算112

Cursor

18.16%
按下载量换算62

Gemini CLI

9.92%
按下载量换算34

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills