AI Summary: Claude Code automatically ingests
CLAUDE.mdand.claude/rules/*.mdinto its persistent context window. Optimizing Claude Code requires establishing a static, cache-friendly root manifest, delegating domain rules to scoped subdirectories, and deploying automated bash hooks to prevent destructive git actions and token-wasting command outputs.
The Hierarchical Scope Resolution in Claude Code
When Claude Code launches in a repository directory, it traverses the filesystem to construct its baseline context:
workspace-root/
├── CLAUDE.md <-- Root scope: Global commands, safety limits, CI gates
├── .claude/
│ ├── config.json <-- Environment flags, tool allowances, model selection
│ ├── hooks/
│ │ └── pre-bash.sh <-- Intercepts dangerous terminal commands before execution
│ └── rules/
│ ├── database.md <-- Scoped rule: Prisma / SQL migration protocols
│ └── frontend.md <-- Scoped rule: React Server Components & CSS conventions
As the agent traverses into a sub-package (e.g. services/payment-engine), it automatically discovers and appends services/payment-engine/CLAUDE.md to its working memory.
Engineering Prompt Caching for CLI Sessions
Claude Code relies on Anthropic's Prompt Caching architecture to keep turn-by-turn latency under 1 second. Every time a prompt is sent:
- If the initial tokens (system prompt, tool declarations, and
CLAUDE.md) match the previous turn's hash, Anthropic serves them from the edge KV cache at $0.30 per million tokens. - If a dynamic script alters
CLAUDE.mdmid-session or injects fluctuating timestamps, the entire prompt cache is invalidated, forcing a full write at $3.75 per million tokens and adding 5+ seconds of latency.
The Immutable Prefix Rule
Ensure your root CLAUDE.md is strictly static. Never include dynamic git commit hashes, real-time clock outputs, or session IDs in CLAUDE.md.
The Production Blueprint for Root CLAUDE.md
# Repository Architecture Guidelines for Claude Code
## Core Verification Commands (Fast Feedback Loop)
- Typecheck: `pnpm typecheck`
- Test Runner: `pnpm test`
- Build Verification: `pnpm build`
- Single Test: `pnpm test -t "<test-name>"`
## Strict Operational Invariants
- Language: TypeScript 5.7+ with strict null checks enabled.
- State: Favor React Server Components; minimize client-side hooks.
- Styling: Pure Vanilla CSS; use design tokens from `src/app/globals.css`.
- Network: Outbound fetches must use `src/lib/safe-fetch.ts` (SSRF protection).
## Absolute Safety Prohibitions
- NEVER run destructive commands: `git reset --hard`, `git push --force`, `rm -rf`.
- NEVER commit directly to `main` — work exclusively on feature branches.
- NEVER modify package lockfiles (`pnpm-lock.yaml`) without explicit developer consent.
- NEVER skip failing tests by commenting out assertions or adding `.skip()`.
Guardrail Hooks: Intercepting Destructive Terminal Calls
Claude Code supports local executable hooks inside .claude/hooks/. A production pre-bash.sh hook blocks accidental destructive operations before they hit the operating system shell:
#!/usr/bin/env bash
# .claude/hooks/pre-bash.sh
# Exit with non-zero to abort the agent's proposed terminal command.
CMD="$1"
# Block destructive git commands
if echo "$CMD" | grep -qE "git[[:space:]]+(reset[[:space:]]+--hard|push[[:space:]]+.*--force|clean[[:space:]]+-fd)"; then
echo "SECURITY BLOCKED: Destructive git operation prohibited in Claude Code." >&2
exit 1
fi
# Block unconstrained recursive deletion
if echo "$CMD" | grep -qE "rm[[:space:]]+-(rf|fr)[[:space:]]+(/|\.\.|\*)"; then
echo "SECURITY BLOCKED: Unconstrained recursive deletion prohibited." >&2
exit 1
fi
exit 0
Deploying this hook provides a hard, physical security boundary that prompt engineering alone cannot guarantee.
Comparative Optimization Matrix
| Metric | Unoptimized Claude Code | Optimized (.claude/rules + Caching) |
|---|---|---|
| Token Cost per 20-Turn Session | ~$1.80 – $3.50 | $0.25 – $0.45 (85% savings) |
| Time-to-First-Token (TTFT) | 4.5s – 8.0s per turn | 0.6s – 1.2s per turn |
| Context Window Longevity | Truncation after ~12 turns | Sustains 35+ turns before /compact |
| Hallucinated Package Installs | Common (installs missing utilities) | Zero (blocked by invariant rules) |
Related guidance
To understand how to operate Claude Code efficiently, read Claude Code Reviewing Machine Context, learn multi-agent standardization in AGENTS.md Best Practices, and compare with Cursor IDE Optimization.
References
- Anthropic Claude Code CLI Documentation: Official specifications for command-line subagents, permissions, and tool loops.
- Anthropic Prompt Caching Guide: Detailed technical breakdown of KV cache lifecycles and cost optimization.
Need to optimize your entire site for AI search visibility? Run a comprehensive audit with Geolify.ai.