Internal Hook Modules
Relevant source files
The following files were used as context for generating this wiki page:
Internal Hook Modules within the Token Optimizer project are specialized scripts and configuration points that intercept the Claude Code lifecycle to manage token consumption and preserve context. These hooks allow the system to automate maintenance tasks—such as analytics collection, state preservation, and code formatting—without requiring manual user intervention during a session.
By integrating directly with the environment's settings.json, these modules execute at specific lifecycle events (e.g., session end, pre-compaction, post-tool use) to ensure that the AI's "memory" remains efficient and high-quality. This infrastructure is critical for the "Smart Compaction" feature, which prevents the loss of important architectural decisions when the context window becomes saturated.
Sources: skills/token-optimizer/references/implementation-playbook.md:144-162, skills/token-optimizer/references/optimization-checklist.md:329-354
Hook Architecture and Lifecycle Events
The project utilizes several standard lifecycle hooks supported by the Claude Code environment. These hooks are defined in the env block of the configuration and triggered by the underlying platform.
The diagram shows the standard progression of hooks from session initiation through to termination.
Sources: skills/token-optimizer/references/agent-prompts.md:278-292, skills/token-optimizer/references/optimization-checklist.md:342-346
Key Lifecycle Hooks
| Hook Name | Trigger Point | Primary Purpose in Token Optimizer |
|---|---|---|
SessionStart | Immediately after session initiation | Re-injects critical state after a compaction event or resume. |
PreCompact | Just before the system compresses context | Snapshots decisions, files, and agent states to prevent loss. |
PostCompact | After context compaction is complete | Tracks compaction analytics and success/failure status. |
PostToolUse | After any tool (Bash, Read, etc.) finishes | Triggers auto-formatters to save tokens on style explanations. |
SessionEnd | Upon closing the session | Executes measure.py collect to finalize session analytics. |
| Sources: skills/token-optimizer/references/implementation-playbook.md:144-162, skills/token-optimizer/references/agent-prompts.md:278-292, skills/token-optimizer/references/optimization-checklist.md:342-346 |
Smart Compaction Logic
The most complex implementation of the hook modules is the Smart Compaction system. Standard compaction is often lossy, dropping nuanced reasoning or specific error-fix sequences. The hook modules mitigate this by creating structured "checkpoints."
This sequence ensures continuity of state even when the conversation history is aggressively summarized.
Sources: skills/token-optimizer/references/optimization-checklist.md:329-354, skills/token-optimizer/SKILL.md:144-162
Checkpoint Data Structures
When the PreCompact hook fires, it captures several data points:
- Decisions: Key architectural choices made during the session.
- Files: Modified file paths and their current state.
- Errors: Recent error messages and the sequences used to fix them.
- Agent State: Information regarding active sub-agents.
Sources: skills/token-optimizer/references/optimization-checklist.md:342-346
Implementation Details
Hooks are typically configured in ~/.claude/settings.json (global) or .claude/settings.json (project-level). The project recommends project-level configuration to avoid side effects in unrelated repositories.
Conditional Execution
Version 2.1.85+ introduced the if field for hooks. The Token Optimizer utilizes this to reduce overhead. For example, the PostToolUse hook can be configured with "if": "tool_uses" to ensure it only runs when a tool was actually invoked, rather than after every simple chat message.
Sources: skills/token-optimizer/references/implementation-playbook.md:204-206, skills/token-optimizer/references/agent-prompts.md:282-284
Analytics Collection (measure.py)
The SessionEnd hook is specifically tied to the measure.py script. It runs python3 measure.py collect --quiet once per session close. This process typically takes approximately 1 second and is responsible for backfilling the local SQLite trends database used for historical coaching.
Sources: skills/token-optimizer/references/implementation-playbook.md:146-152, skills/token-coach/SKILL.md:44-65
Version-Specific Hook Optimizations
The behavior and necessity of certain hooks depend on the version of the underlying AI environment:
- v2.1.86+: The
read_cache.pyPreToolUse hook becomes redundant because the platform handles native deduplication of re-reads. - v2.1.85+: Supports the
PostCompacthook with a payload containing thetrigger("manual" or "auto") and acompact_summary. - v2.1.83+: An auto-compact circuit breaker was introduced; if compaction fails three times, the
PreCompacthook will no longer fire until a new session is started.
Sources: skills/token-optimizer/references/implementation-playbook.md:190-202, skills/token-optimizer/references/agent-prompts.md:278-283
Summary
Internal Hook Modules serve as the automated backbone of the Token Optimizer. By leveraging the PreCompact, SessionStart, and SessionEnd lifecycle events, the project transforms a standard AI session into a managed environment where context quality is maintained through structured checkpoints and analytics collection. This automation is essential for long-running, complex development tasks where manual context management is insufficient.
Sources: skills/token-optimizer/references/optimization-checklist.md:329-354, skills/token-optimizer/SKILL.md:144-162