agentleFS
thebiglaskowskithebiglaskowski/claude-sentient/.claude/hooks/CLAUDE.md

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

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
  1. Very specific:

    All hooks use shared utils.cjs for JSON I/O, state management, and logging.

    line 25
  2. Distinctive:

    Use async for pure observer hooks where the result is not needed immediately:

    line 155
  3. Very specific:

    Do NOT mark async: bash-validator, file-validator (PreToolUse must block), context-injector (must inject before response), session-start …

    line 167

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Hooks — Claude Sentient

Context for working on hook scripts in .claude/hooks/.

Hook Scripts (15 hooks)

ScriptEventAsyncPurpose
session-start.cjsSessionStartNoInitialize session, detect profile
session-end.cjsSessionEndYesArchive session, cleanup state
context-injector.cjsUserPromptSubmitNoDetect topics, inject context
bash-validator.cjsPreToolUse (Bash)NoBlock dangerous commands
file-validator.cjsPreToolUse (Write/Edit)NoValidate protected paths
skill-tracker.cjsPreToolUse (Skill)YesLog skill invocations for usage tracking
post-tool-observer.cjsPostToolUse (Write/Edit/Bash)YesTrack changes, suggest lint, record gate results
agent-tracker.cjsSubagentStartYesTrack agent spawning
agent-synthesizer.cjsSubagentStopYesSynthesize agent results
pre-compact.cjsPreCompactNoBackup state before compaction
dod-verifier.cjsStopNoVerify DoD, save final state
teammate-idle.cjsTeammateIdleNoQuality check before teammate goes idle
task-completed.cjsTaskCompletedNoValidate deliverables, file ownership
worktree-lifecycle.cjsWorktreeCreate / WorktreeRemoveYesWrite context into new worktrees; log removals
config-watcher.cjsConfigChangeYesLog 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 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 Windows, which does not interpret bash syntax. Keep commands as plain node <path> invocations.


Security Patterns

Bash Validator blocks dangerous patterns:

  • Any rm with combined -r/-f flags (any path — named dirs, ../ traversal, absolute)
  • > /dev/sd* — Direct disk writes
  • mkfs — Filesystem creation
  • chmod -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 substitution
  • curl url > x.sh && bash x.sh — Download-then-execute chains
  • base64 -d | sh — Encoded command injection
  • eval — Shell eval execution
  • sudo bash/sh, sudo su — Privilege escalation
  • find / -exec rm or find|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/:

FilePurpose
session_start.jsonCurrent session metadata
file_changes.jsonFiles modified this session
active_agents.jsonCurrently running subagents
agent_history.jsonCompleted subagent history
prompts.jsonRecent prompt metadata
last_verification.jsonLast DoD verification (includes integrityChecks field)
gate_history.jsonQuality gate exit codes and durations
compact-context.jsonState snapshot before context compaction (includes contextManifest, sessionSummary with staleFileReads and recentActivitySummary)
team-state.jsonAgent Teams: teammate tracking, file ownership
context_degradation.jsonContext depth warning state (medium/high)
gate-output/Large gate stdout saved as files (created on demand)
worktree-context.jsonCreated inside new worktrees by WorktreeCreate hook
config_changes.jsonRolling log of ConfigChange events (capped at 20)
skill-usage.jsonSkill 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 triggered

PreToolUse 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/reason fields are deprecated as of v2.0.0. Always use hookSpecificOutput.permissionDecision ('allow' or 'deny') and hookSpecificOutput.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:

HookRationale
post-tool-observer.cjsState tracking + gate observation; result not needed before next tool
agent-tracker.cjsLogging only; no immediate response needed
agent-synthesizer.cjsState persistence; fire-and-forget
session-end.cjsArchive cleanup; fire-and-forget
worktree-lifecycle.cjsContext bootstrap; parent session continues immediately
config-watcher.cjsChange logging; no synchronous response needed
skill-tracker.cjsUsage 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)

FunctionPurpose
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).

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.