claude-sentient / hooks
CLAUDE.md2 starsChanged 7 months agoMITView on GitHub
Context for working on hook scripts in .claude/hooks/. All hooks use shared utils.cjs for JSON I/O, state management, and logging. Hooks are configured in .claude/settings.json: Hook commands use simple relative paths. Claude Code runs hooks from the project root directory, so .claude/hooks/ resolves correctly. Each hook uses getProjectRoot() from utils.cjs internally for any file operations that need the project root path. Important: Do NOT use shell substitutions like $(...) in hook commands — Claude Code passes commands through cmd.exe on…
- Pipes a download into a shell
- Reads credentials
In this repository6 other files it gives its agents.
- .claude/commands/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- .cursor/rules/claude-sentient.mdcCursor rule
- profile-detectionSkill
- quality-gatesSkill
- team-orchestrationSkill
The file
We split this CLAUDE.md into the rules it gives an agent
3 rules. About 0 are common, 1 is distinctive, and 2 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 25
All hooks use shared utils.cjs for JSON I/O, state management, and logging.
- Distinctive: line 155
Use async for pure observer hooks where the result is not needed immediately:
- Very specific: line 167
Do NOT mark async: bash-validator, file-validator (PreToolUse must block), context-injector (must inject before response), session-start …
≈ “Common” is an estimate: at least 1 in 5 of the 28,029 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Hooks — Claude Sentient
Context for working on hook scripts in
.claude/hooks/.
Hook Scripts (15 hooks)
| Script | Event | Async | Purpose |
session-start.cjs | SessionStart | No | Initialize session, detect profile |
session-end.cjs | SessionEnd | Yes | Archive session, cleanup state |
context-injector.cjs | UserPromptSubmit | No | Detect topics, inject context |
bash-validator.cjs | PreToolUse (Bash) | No | Block dangerous commands |
file-validator.cjs | PreToolUse (Write/Edit) | No | Validate protected paths |
skill-tracker.cjs | PreToolUse (Skill) | Yes | Log skill invocations for usage tracking |
post-tool-observer.cjs | PostToolUse (Write/Edit/Bash) | Yes | Track changes, suggest lint, record gate results |
agent-tracker.cjs | SubagentStart | Yes | Track agent spawning |
agent-synthesizer.cjs | SubagentStop | Yes | Synthesize agent results |
pre-compact.cjs | PreCompact | No | Backup state before compaction |
dod-verifier.cjs | Stop | No | Verify DoD, save final state |
teammate-idle.cjs | TeammateIdle | No | Quality check before teammate goes idle |
task-completed.cjs | TaskCompleted | No | Validate deliverables, file ownership |
worktree-lifecycle.cjs | WorktreeCreate / WorktreeRemove | Yes | Write context into new worktrees; log removals |
config-watcher.cjs | ConfigChange | Yes | Log settings changes; alert on hooks section edits |
All hooks use shared utils.cjs for JSON I/O, state management, and logging.
Configuration
Hooks are configured in .claude/settings.json:
{
"hooks": {
"SessionStart": [{ "hooks": [{ "type": "command", "command": "node .claude/hooks/session-start.cjs", "timeout": 5000 }] }],
"PreToolUse": [
{ "matcher": "Bash", "hooks": [{ "type": "command", "command": "node .claude/hooks/bash-validator.cjs" }] },
{ "matcher": "Write|Edit", "hooks": [{ "type": "command", "command": "node .claude/hooks/file-validator.cjs" }] }
]
}
}Hook commands use simple relative paths. Claude Code runs hooks from the project root directory, so
.claude/hooks/resolves correctly. Each hook usesgetProjectRoot()fromutils.cjsinternally for any file operations that need the project root path.Important: Do NOT use shell substitutions like
$(...)in hook commands — Claude Code passes commands throughcmd.exeon Windows, which does not interpret bash syntax. Keep commands as plainnode <path>invocations.
Security Patterns
Bash Validator blocks dangerous patterns:
- Any
rmwith combined-r/-fflags (any path — named dirs,../traversal, absolute) > /dev/sd*— Direct disk writesmkfs— Filesystem creationchmod -R 777 /— Dangerous permissions- Fork bombs and reverse shells
curl|sh,wget|sh— Supply-chain attacks (pipe-to-interpreter)bash -c "$(curl ...)"— Supply-chain bypass via command substitutioncurl url > x.sh && bash x.sh— Download-then-execute chainsbase64 -d | sh— Encoded command injectioneval— Shell eval executionsudo bash/sh,sudo su— Privilege escalationfind / -exec rmorfind|xargs rm— Bulk deletion from root- Python/Perl/Ruby/Node one-liners with dangerous imports
- Oversized
HOOK_INPUT(>1MB) — fail-closed, blocks rather than allowing empty command through
File Validator protects sensitive paths:
- System directories (
/etc,/usr,C:\Windows) - SSH keys (
.ssh/) - Credentials (
.env.production,secrets.*) - Git internals (
.git/objects)
State Files
Hooks read/write to .claude/state/:
| File | Purpose |
session_start.json | Current session metadata |
file_changes.json | Files modified this session |
active_agents.json | Currently running subagents |
agent_history.json | Completed subagent history |
prompts.json | Recent prompt metadata |
last_verification.json | Last DoD verification (includes integrityChecks field) |
gate_history.json | Quality gate exit codes and durations |
compact-context.json | State snapshot before context compaction (includes contextManifest, sessionSummary with staleFileReads and recentActivitySummary) |
team-state.json | Agent Teams: teammate tracking, file ownership |
context_degradation.json | Context depth warning state (medium/high) |
gate-output/ | Large gate stdout saved as files (created on demand) |
worktree-context.json | Created inside new worktrees by WorktreeCreate hook |
config_changes.json | Rolling log of ConfigChange events (capped at 20) |
skill-usage.json | Skill invocation history: skill name + timestamp (capped at 200) |
Agent Teams Hooks
TeammateIdle (teammate-idle.cjs):
- Checks if teammate has completed any tasks before going idle
- Exit code 0: allow idle. Exit code 2: send feedback (keep working)
- Tracks idle count per teammate
TaskCompleted (task-completed.cjs):
- Validates file count per task (max 20 files)
- Detects file ownership conflicts between teammates
- Maintains file ownership map to prevent overwrites
- Exit code 0: allow completion. Exit code 2: reject with feedback
Hook Input/Output
Hooks receive input via HOOK_INPUT environment variable (JSON):
const input = JSON.parse(process.env.HOOK_INPUT || '{}');
// input.tool_input - the tool's parameters
// input.tool_name - which tool triggeredPreToolUse hooks output hookSpecificOutput to allow or deny (Claude Code v2.0.0+):
// Deny an operation (was: { decision: 'block', reason: '...' })
console.log(JSON.stringify({
hookSpecificOutput: {
permissionDecision: 'deny',
permissionDecisionReason: 'Why this is blocked'
}
}));
// Allow with optional warnings
console.log(JSON.stringify({
hookSpecificOutput: {
permissionDecision: 'allow',
permissionDecisionReason: 'Warning: doing X may cause Y' // optional
}
}));Note: The top-level
decision/reasonfields are deprecated as of v2.0.0. Always usehookSpecificOutput.permissionDecision('allow'or'deny') andhookSpecificOutput.permissionDecisionReason.
PostToolUse, SessionStart, SubagentStart, etc. are observe-only — no permission decision is meaningful. These hooks produce no stdout (or context-only output) and exit 0.
Async Hooks
Hooks marked "async": true in settings.json are fire-and-forget — Claude Code does not wait for their result before proceeding. The hook's output (if any) is delivered as a HookResult event on the next turn.
Use async for pure observer hooks where the result is not needed immediately:
| Hook | Rationale |
post-tool-observer.cjs | State tracking + gate observation; result not needed before next tool |
agent-tracker.cjs | Logging only; no immediate response needed |
agent-synthesizer.cjs | State persistence; fire-and-forget |
session-end.cjs | Archive cleanup; fire-and-forget |
worktree-lifecycle.cjs | Context bootstrap; parent session continues immediately |
config-watcher.cjs | Change logging; no synchronous response needed |
skill-tracker.cjs | Usage logging only; no blocking decision needed |
Do NOT mark async: bash-validator, file-validator (PreToolUse must block), context-injector (must inject before response), session-start (must init before first turn), pre-compact (must complete before compaction), dod-verifier (Stop hook — must run synchronously), teammate-idle, task-completed (need synchronous state writes for coordination).
Shared Utilities (utils.cjs)
| Function | Purpose |
getProjectRoot() | Resolve project root via git (cached per process) |
parseHookInput() | Parse from HOOK_INPUT env var or stdin (sanitized) |
loadState(filename) | Load from .claude/state/ |
saveState(filename, data) | Save to .claude/state/ (atomic write) |
loadJsonFile(path) | Low-level JSON file read |
saveJsonFile(path, data) | Low-level JSON file write (tmp+rename) |
appendCapped(file, entry, max) | Load-push-cap-save for state arrays |
logMessage(msg, level) | Append to .claude/session.log |
ensureStateDir() | Create state directory if missing (cached) |
sanitizeJson(obj) | Prototype pollution protection |
redactSecrets(str) | API key/token redaction in logs |
validateFilePath(path) | Path validation (control chars, traversal) |
pruneDirectory(dir, max, prefix) | Cap file count in a directory |
isInputTooLarge(input) | Check HOOK_INPUT size limit |
Key constants: MAX_PROMPT_HISTORY (50), MAX_FILE_CHANGES (100), MAX_AGENT_HISTORY (50), MAX_FILES_PER_TASK (20), LARGE_FILE_THRESHOLD (100KB), MAX_GATE_HISTORY (200), MAX_OBSERVATION_SIZE (8000), MAX_INPUT_SIZE (1MB), CONTEXT_DEGRADATION_THRESHOLD (20), CONTEXT_DEGRADATION_EARLY (15).
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

