Guest User

Untitled

a guest
Jan 4th, 2026
7,723
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 45.25 KB | None | 1 0
  1. # Claude Code Mastery: Advanced Patterns for 10x Productivity
  2.  
  3. **A comprehensive guide to the patterns that actually move the needle**
  4.  
  5. *Reverse-engineered from 2000+ hours of LLM-assisted coding*
  6.  
  7. -----
  8.  
  9. ## Table of Contents
  10.  
  11. 1. [Core Philosophy: Context Engineering](#1-core-philosophy-context-engineering)
  12. 1. [Pattern 1: Error Logging System](#2-pattern-1-error-logging-system)
  13. 1. [Pattern 2: Slash Commands as Lightweight Local Apps](#3-pattern-2-slash-commands-as-lightweight-local-apps)
  14. 1. [Pattern 3: Hooks for Deterministic Safety](#4-pattern-3-hooks-for-deterministic-safety)
  15. 1. [Pattern 4: Context Hygiene](#5-pattern-4-context-hygiene)
  16. 1. [Pattern 5: Subagent Control](#6-pattern-5-subagent-control)
  17. 1. [Pattern 6: The Reprompter System](#7-pattern-6-the-reprompter-system)
  18. 1. [Subagent Monitoring Dashboard](#8-subagent-monitoring-dashboard)
  19. 1. [Quick Reference Table](#9-quick-reference-table)
  20.  
  21. -----
  22.  
  23. ## 1. Core Philosophy: Context Engineering
  24.  
  25. ### The Fundamental Mindset Shift
  26.  
  27. **Any issue in LLM-generated code is solely due to YOU.**
  28.  
  29. This isn’t blame—it’s empowerment. Every error traces back to:
  30.  
  31. - **Improper prompting**: Vague instructions, missing constraints, unclear success criteria
  32. - **Improper context engineering**: Wrong files loaded, stale context, missing architectural knowledge
  33. - **Context rot**: Degraded quality as the context window fills with irrelevant information
  34. - **Lost in the middle**: The well-documented phenomenon where LLMs pay less attention to middle-of-context information
  35.  
  36. ### The Context Quality Curve
  37.  
  38. ```
  39. Quality of Output
  40. │
  41. 100%├────────╮
  42. │ │╲
  43. 80%│ │ ╲
  44. │ │ ╲ ← "Lost in the Middle" begins
  45. 60%│ │ ╲
  46. │ │ ╲____
  47. 40%│ │ ╲___
  48. │ │ ╲___
  49. 20%│ │ ╲
  50. └────────┴───────────────────────► Context Usage %
  51. 20% 40% 60% 80% 100%
  52. ```
  53.  
  54. **Key insight**: Quality degrades non-linearly. The last 20% of context is poison.
  55.  
  56. -----
  57.  
  58. ## 2. Pattern 1: Error Logging System
  59.  
  60. ### The Problem
  61.  
  62. Agentic coding hides the input-output loop from you. Claude makes decisions, executes tools, and you only see the final result. When things go wrong, you don’t know *why*.
  63.  
  64. ### The Solution: Reconstruct the Feedback Loop
  65.  
  66. Create a systematic log of failures with:
  67.  
  68. 1. **The exact triggering prompt**
  69. 1. **The context state** (what files were loaded, % used)
  70. 1. **The failure mode** (wrong output, hallucination, refusal, loop)
  71. 1. **Your diagnosis** (what did YOU do wrong?)
  72.  
  73. ### Implementation
  74.  
  75. #### Error Log Template (`~/.claude/error-log.md`)
  76.  
  77. ```markdown
  78. # Claude Code Error Log
  79.  
  80. ## Entry Format
  81. - **Date**:
  82. - **Prompt**: [exact text]
  83. - **Context %**:
  84. - **Files Loaded**:
  85. - **Failure Mode**: [wrong-output | hallucination | refusal | infinite-loop | context-rot]
  86. - **What Claude Did**:
  87. - **What I Expected**:
  88. - **Root Cause**: [prompting | context | model-limitation]
  89. - **Fix Applied**:
  90. - **Pattern Identified**:
  91.  
  92. ---
  93.  
  94. ## 2025-01-03 | Context Rot in Auth Refactor
  95.  
  96. **Prompt**: "Now refactor the auth module to use the new pattern"
  97.  
  98. **Context %**: 78%
  99.  
  100. **Files Loaded**: 12 files from src/auth/, 3 config files, previous conversation
  101.  
  102. **Failure Mode**: wrong-output
  103.  
  104. **What Claude Did**: Used old pattern despite being shown new one 30 messages ago
  105.  
  106. **What I Expected**: Apply the new auth pattern from message #4
  107.  
  108. **Root Cause**: context - the new pattern was in "lost middle" zone
  109.  
  110. **Fix Applied**: /clear → re-stated pattern → pointed to specific file with pattern
  111.  
  112. **Pattern Identified**: ALWAYS re-state critical patterns before asking for implementation if >50% context used
  113.  
  114. ---
  115. ```
  116.  
  117. #### Slash Command for Quick Logging
  118.  
  119. Create `~/.claude/commands/log-error.md`:
  120.  
  121. ```markdown
  122. ---
  123. description: Log a Claude Code error for pattern analysis
  124. argument-hint: [failure-mode] [brief-description]
  125. ---
  126.  
  127. I need to log an error for my learning system. Please help me fill out this template:
  128.  
  129. **Failure Mode**: $1
  130. **Brief Description**: $2
  131.  
  132. Ask me the following questions one at a time:
  133. 1. What was the exact prompt that triggered this?
  134. 2. What was the context % when this happened?
  135. 3. What files were loaded?
  136. 4. What did you expect vs what happened?
  137. 5. What do you think the root cause was?
  138.  
  139. Then format it as a markdown entry I can append to my error log.
  140. ```
  141.  
  142. ### Error Categories & Common Fixes
  143.  
  144. |Failure Mode |Common Causes |Standard Fixes |
  145. |-----------------|-------------------------------------|-----------------------------------|
  146. |**Wrong Output** |Vague prompt, missing constraints |Add explicit constraints, examples |
  147. |**Hallucination**|Asked about code Claude hasn’t seen |@-mention specific files first |
  148. |**Refusal** |Triggered safety, ambiguous request |Rephrase, provide more context |
  149. |**Infinite Loop**|Unclear success criteria |Define exit conditions explicitly |
  150. |**Context Rot** |>70% context, stale information |/clear, restart with fresh context |
  151. |**Regression** |Fixed something, broke something else|Require tests before implementation|
  152.  
  153. -----
  154.  
  155. ## 3. Pattern 2: Slash Commands as Lightweight Local Apps
  156.  
  157. ### The Mental Model
  158.  
  159. Think of slash commands as **Claude-as-a-Service workflows**. They’re like SaaS products you can build in 5 minutes:
  160.  
  161. - Pre-configured prompts with best practices baked in
  162. - Argument handling for dynamic behavior
  163. - Tool restrictions for safety
  164. - Model selection for cost/quality tradeoffs
  165.  
  166. ### Command Architecture
  167.  
  168. ```
  169. ~/.claude/commands/ # Personal commands (available everywhere)
  170. ├── quick/ # Fast, simple commands
  171. │ ├── commit.md
  172. │ ├── pr.md
  173. │ └── review.md
  174. ├── research/ # Investigation commands
  175. │ ├── deep-dive.md
  176. │ ├── compare.md
  177. │ └── audit.md
  178. └── workflows/ # Multi-step processes
  179. ├── feature.md
  180. ├── debug.md
  181. └── refactor.md
  182.  
  183. .claude/commands/ # Project commands (team-shared)
  184. ├── test.md
  185. ├── deploy.md
  186. └── docs.md
  187. ```
  188.  
  189. ### Essential Slash Commands Collection
  190.  
  191. #### 1. Smart Commit (`~/.claude/commands/commit.md`)
  192.  
  193. ```markdown
  194. ---
  195. description: Create a semantic commit with conventional format
  196. allowed-tools: Bash(git diff:*), Bash(git status:*), Bash(git add:*), Bash(git commit:*)
  197. model: claude-3-5-haiku-20241022
  198. ---
  199.  
  200. Analyze my staged changes and create a commit:
  201.  
  202. 1. Run `git diff --cached` to see staged changes
  203. 2. Run `git status` to understand the scope
  204. 3. Generate a commit message following Conventional Commits:
  205. - feat: new feature
  206. - fix: bug fix
  207. - refactor: code restructuring
  208. - docs: documentation
  209. - test: adding tests
  210. - chore: maintenance
  211.  
  212. 4. Format: `type(scope): brief description`
  213. - Keep under 72 characters
  214. - Use imperative mood ("add" not "added")
  215.  
  216. 5. Ask me to confirm, then commit
  217.  
  218. If no changes are staged, help me stage relevant files first.
  219. ```
  220.  
  221. #### 2. PR Creator (`~/.claude/commands/pr.md`)
  222.  
  223. ```markdown
  224. ---
  225. description: Create a comprehensive pull request
  226. allowed-tools: Bash(git:*), Bash(gh:*)
  227. argument-hint: [base-branch]
  228. ---
  229.  
  230. Create a pull request against $ARGUMENTS (default: main):
  231.  
  232. 1. Run `git log main..HEAD --oneline` to see commits
  233. 2. Run `git diff main...HEAD --stat` for change summary
  234. 3. Generate PR with:
  235. - Title: conventional format matching primary change
  236. - Description:
  237. ## Summary
  238. [2-3 sentences on what and why]
  239.  
  240. ## Changes
  241. - [bullet list of key changes]
  242.  
  243. ## Testing
  244. - [how this was tested]
  245.  
  246. ## Screenshots
  247. [if UI changes, note that screenshots should be added]
  248.  
  249. 4. Use `gh pr create` with generated content
  250. 5. Output the PR URL when complete
  251. ```
  252.  
  253. #### 3. Deep Investigation (`~/.claude/commands/investigate.md`)
  254.  
  255. ```markdown
  256. ---
  257. description: Deep dive into a bug or behavior
  258. allowed-tools: Read, Grep, Glob, Bash(git log:*), Bash(git blame:*)
  259. argument-hint: [issue-description]
  260. ---
  261.  
  262. Investigate: $ARGUMENTS
  263.  
  264. Follow this systematic process:
  265.  
  266. ## Phase 1: Understand
  267. - What is the expected behavior?
  268. - What is the actual behavior?
  269. - When did this start? (check git log if relevant)
  270.  
  271. ## Phase 2: Locate
  272. - Search for relevant code with Grep
  273. - Trace the code path from entry point
  274. - Identify all files involved
  275.  
  276. ## Phase 3: Analyze
  277. - Use git blame to understand history
  278. - Look for recent changes that might have caused this
  279. - Check for related issues/patterns elsewhere
  280.  
  281. ## Phase 4: Report
  282. Provide a structured report:
  283. 1. **Root Cause**: [one sentence]
  284. 2. **Affected Files**: [list]
  285. 3. **Recommended Fix**: [approach]
  286. 4. **Risk Assessment**: [what could break]
  287. 5. **Test Plan**: [how to verify]
  288.  
  289. Do NOT make any changes. Investigation only.
  290. ```
  291.  
  292. #### 4. Test Generator (`~/.claude/commands/test.md`)
  293.  
  294. ```markdown
  295. ---
  296. description: Generate comprehensive tests for a file or function
  297. allowed-tools: Read, Write, Bash(npm test:*), Bash(pytest:*)
  298. argument-hint: [file-or-function]
  299. ---
  300.  
  301. Generate tests for: $ARGUMENTS
  302.  
  303. ## Process:
  304.  
  305. 1. **Read the target code** - understand all paths and edge cases
  306. 2. **Identify test framework** - check existing tests, package.json, pytest.ini
  307. 3. **Generate tests covering**:
  308. - Happy path (normal usage)
  309. - Edge cases (empty, null, boundary values)
  310. - Error cases (invalid input, exceptions)
  311. - Integration points (mocks for external deps)
  312.  
  313. 4. **Follow existing patterns** - match style of existing tests
  314. 5. **Run the tests** - ensure they pass
  315. 6. **Report coverage gaps** - what's still untested?
  316.  
  317. Output format: Create test file(s) following project conventions.
  318. ```
  319.  
  320. #### 5. Security Audit (`~/.claude/commands/security-audit.md`)
  321.  
  322. ```markdown
  323. ---
  324. description: Security-focused code review
  325. allowed-tools: Read, Grep, Glob
  326. argument-hint: [file-or-directory]
  327. ---
  328.  
  329. Perform security audit on: $ARGUMENTS
  330.  
  331. ## Check for:
  332.  
  333. ### Input Validation
  334. - [ ] SQL injection vulnerabilities
  335. - [ ] XSS (Cross-Site Scripting)
  336. - [ ] Command injection
  337. - [ ] Path traversal
  338.  
  339. ### Authentication & Authorization
  340. - [ ] Hardcoded credentials
  341. - [ ] Weak session handling
  342. - [ ] Missing auth checks
  343. - [ ] Privilege escalation paths
  344.  
  345. ### Data Handling
  346. - [ ] Sensitive data in logs
  347. - [ ] Unencrypted secrets
  348. - [ ] PII exposure
  349. - [ ] Insecure deserialization
  350.  
  351. ### Dependencies
  352. - [ ] Known vulnerable packages
  353. - [ ] Outdated dependencies
  354. - [ ] Unused dependencies
  355.  
  356. ## Output Format:
  357. For each finding:
  358. - **Severity**: Critical / High / Medium / Low
  359. - **Location**: file:line
  360. - **Issue**: description
  361. - **Recommendation**: how to fix
  362. - **Reference**: CWE or OWASP link if applicable
  363. ```
  364.  
  365. #### 6. Refactor Planner (`~/.claude/commands/refactor-plan.md`)
  366.  
  367. ```markdown
  368. ---
  369. description: Plan a refactoring without executing it
  370. allowed-tools: Read, Grep, Glob
  371. argument-hint: [what-to-refactor]
  372. ---
  373.  
  374. Plan refactoring for: $ARGUMENTS
  375.  
  376. ## DO NOT MAKE ANY CHANGES - PLANNING ONLY
  377.  
  378. ### Analysis Phase:
  379. 1. Read all relevant files
  380. 2. Map dependencies (what imports this? what does this import?)
  381. 3. Identify test coverage
  382. 4. Note potential breaking changes
  383.  
  384. ### Output a Refactoring Plan:
  385.  
  386. ```markdown
  387. # Refactoring Plan: [title]
  388.  
  389. ## Current State
  390. [Describe the current architecture/code]
  391.  
  392. ## Desired State
  393. [Describe the target architecture/code]
  394.  
  395. ## Steps (in order)
  396. 1. [ ] Step 1 - [description] - Risk: Low/Med/High
  397. 2. [ ] Step 2 - [description] - Risk: Low/Med/High
  398. ...
  399.  
  400. ## Files to Modify
  401. - `path/to/file.ts` - [what changes]
  402. - `path/to/other.ts` - [what changes]
  403.  
  404. ## Files to Create
  405. - `path/to/new.ts` - [purpose]
  406.  
  407. ## Files to Delete
  408. - `path/to/old.ts` - [why safe to delete]
  409.  
  410. ## Tests to Add/Update
  411. - [list of test changes needed]
  412.  
  413. ## Rollback Plan
  414. [How to undo if something goes wrong]
  415.  
  416. ## Estimated Effort
  417. [Time estimate]
  418. ```
  419.  
  420. When I approve, I’ll run a separate command to execute each step.
  421.  
  422. ```
  423. ---
  424.  
  425. ## 4. Pattern 3: Hooks for Deterministic Safety
  426.  
  427. ### The Problem with --dangerously-skip-permissions
  428.  
  429. The `--dangerously-skip-permissions` flag is seductive. It eliminates the constant "Can I run X?" prompts and enables true flow state. But it's called "dangerous" for a reason—Claude can:
  430. - Delete files with `rm -rf`
  431. - Push to git without review
  432. - Run arbitrary shell commands
  433. - Modify system files
  434.  
  435. ### The Solution: Guardrails via Hooks
  436.  
  437. Hooks let you intercept Claude's actions at various lifecycle points and apply your own rules. The pattern:
  438. ```
  439.  
  440. ┌─────────────────────────────────────────────────────────────┐
  441. │ │
  442. │ –dangerously-skip-permissions + Safety Hooks │
  443. │ │
  444. │ (Flow State) (Guardrails) │
  445. │ │
  446. │ = Safe YOLO Mode │
  447. │ │
  448. └─────────────────────────────────────────────────────────────┘
  449.  
  450. ```
  451. ### Hook Configuration
  452.  
  453. Location: `~/.claude/settings.json` or `.claude/settings.json`
  454.  
  455. #### Complete Safety Hook Configuration
  456.  
  457. ```json
  458. {
  459. "hooks": {
  460. "PreToolUse": [
  461. {
  462. "matcher": "Bash",
  463. "hooks": [
  464. {
  465. "type": "command",
  466. "command": "~/.claude/hooks/bash-safety.sh"
  467. }
  468. ]
  469. },
  470. {
  471. "matcher": "Write",
  472. "hooks": [
  473. {
  474. "type": "command",
  475. "command": "~/.claude/hooks/write-safety.sh"
  476. }
  477. ]
  478. }
  479. ],
  480. "PostToolUse": [
  481. {
  482. "matcher": "Write(*.py)",
  483. "hooks": [
  484. {
  485. "type": "command",
  486. "command": "python -m black \"$CLAUDE_FILE_PATHS\""
  487. }
  488. ]
  489. },
  490. {
  491. "matcher": "Write(*.ts)",
  492. "hooks": [
  493. {
  494. "type": "command",
  495. "command": "npx prettier --write \"$CLAUDE_FILE_PATHS\""
  496. }
  497. ]
  498. },
  499. {
  500. "matcher": "Write(*.tsx)",
  501. "hooks": [
  502. {
  503. "type": "command",
  504. "command": "npx prettier --write \"$CLAUDE_FILE_PATHS\" && npx tsc --noEmit \"$CLAUDE_FILE_PATHS\" 2>&1 || echo '⚠️ TypeScript errors'"
  505. }
  506. ]
  507. }
  508. ],
  509. "Stop": [
  510. {
  511. "matcher": "*",
  512. "hooks": [
  513. {
  514. "type": "command",
  515. "command": "~/.claude/hooks/session-summary.sh"
  516. }
  517. ]
  518. }
  519. ]
  520. }
  521. }
  522. ```
  523.  
  524. #### Bash Safety Hook (`~/.claude/hooks/bash-safety.sh`)
  525.  
  526. ```bash
  527. #!/bin/bash
  528.  
  529. # Read the tool input from stdin
  530. INPUT=$(cat)
  531. COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
  532.  
  533. # Define dangerous patterns
  534. DANGEROUS_PATTERNS=(
  535. "rm -rf /"
  536. "rm -rf ~"
  537. "rm -rf \$HOME"
  538. "rm -rf \*"
  539. "> /dev/sd"
  540. "mkfs"
  541. "dd if="
  542. ":(){:|:&};:" # Fork bomb
  543. "chmod -R 777 /"
  544. "chown -R"
  545. "curl.*| bash"
  546. "wget.*| bash"
  547. "curl.*| sh"
  548. "wget.*| sh"
  549. "git push.*--force"
  550. "git push.*-f"
  551. "DROP TABLE"
  552. "DROP DATABASE"
  553. "DELETE FROM.*WHERE 1"
  554. "npm publish"
  555. "pip upload"
  556. )
  557.  
  558. # Check each pattern
  559. for pattern in "${DANGEROUS_PATTERNS[@]}"; do
  560. if echo "$COMMAND" | grep -qE "$pattern"; then
  561. echo '{"decision": "block", "reason": "Blocked dangerous command pattern: '"$pattern"'"}'
  562. exit 0
  563. fi
  564. done
  565.  
  566. # Block operations outside project directory (optional)
  567. PROJECT_DIR=$(pwd)
  568. if echo "$COMMAND" | grep -qE "cd\s+[^.]|cd\s+/(?!home)" ; then
  569. echo '{"decision": "ask", "reason": "Command navigates outside project directory"}'
  570. exit 0
  571. fi
  572.  
  573. # Allow command to proceed
  574. exit 0
  575. ```
  576.  
  577. #### Write Safety Hook (`~/.claude/hooks/write-safety.sh`)
  578.  
  579. ```bash
  580. #!/bin/bash
  581.  
  582. INPUT=$(cat)
  583. FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
  584.  
  585. # Protected paths
  586. PROTECTED_PATTERNS=(
  587. "^/etc/"
  588. "^/usr/"
  589. "^/bin/"
  590. "^/sbin/"
  591. "^\\.env$"
  592. "^\\.env\\."
  593. "^.*\\.pem$"
  594. "^.*\\.key$"
  595. "^.*_rsa$"
  596. "^package-lock\\.json$"
  597. "^yarn\\.lock$"
  598. "^pnpm-lock\\.yaml$"
  599. )
  600.  
  601. for pattern in "${PROTECTED_PATTERNS[@]}"; do
  602. if echo "$FILE_PATH" | grep -qE "$pattern"; then
  603. echo '{"decision": "ask", "reason": "Protected file: '"$FILE_PATH"'"}'
  604. exit 0
  605. fi
  606. done
  607.  
  608. exit 0
  609. ```
  610.  
  611. #### Session Summary Hook (`~/.claude/hooks/session-summary.sh`)
  612.  
  613. ```bash
  614. #!/bin/bash
  615.  
  616. # Log session end with summary
  617. TIMESTAMP=$(date +%Y-%m-%d_%H:%M:%S)
  618. LOG_FILE="$HOME/.claude/session-logs/$TIMESTAMP.log"
  619.  
  620. mkdir -p "$HOME/.claude/session-logs"
  621.  
  622. # Get git diff if in a repo
  623. if git rev-parse --git-dir > /dev/null 2>&1; then
  624. echo "=== Session End: $TIMESTAMP ===" >> "$LOG_FILE"
  625. echo "" >> "$LOG_FILE"
  626. echo "=== Files Changed ===" >> "$LOG_FILE"
  627. git diff --name-only >> "$LOG_FILE"
  628. echo "" >> "$LOG_FILE"
  629. echo "=== Diff Summary ===" >> "$LOG_FILE"
  630. git diff --stat >> "$LOG_FILE"
  631. fi
  632.  
  633. exit 0
  634. ```
  635.  
  636. ### Making Hooks Executable
  637.  
  638. ```bash
  639. chmod +x ~/.claude/hooks/*.sh
  640. ```
  641.  
  642. ### The “Safe YOLO” Alias
  643.  
  644. Add to your shell config (`~/.bashrc` or `~/.zshrc`):
  645.  
  646. ```bash
  647. # Safe YOLO mode - permissions skipped but hooks protect you
  648. alias claude-yolo="claude --dangerously-skip-permissions"
  649.  
  650. # Extra safe - also run in Docker
  651. alias claude-sandbox="docker run -it -v $(pwd):/workspace anthropic/claude-code --dangerously-skip-permissions"
  652. ```
  653.  
  654. -----
  655.  
  656. ## 5. Pattern 4: Context Hygiene
  657.  
  658. ### Understanding Context Degradation
  659.  
  660. Context isn’t just about running out of tokens—quality degrades long before you hit limits:
  661.  
  662. |Context %|Quality |Recommendation |
  663. |---------|---------|-----------------------------------------|
  664. |0-40% |Excellent|Full attention, great recall |
  665. |40-60% |Good |Start being selective about new context |
  666. |60-80% |Degraded |“Lost in the middle” effects begin |
  667. |80-95% |Poor |Frequent mistakes, forgotten instructions|
  668. |95-100% |Critical |Auto-compact triggers, context lost |
  669.  
  670. ### Disable Auto-Compact
  671.  
  672. Auto-compact is convenient but opaque. You don’t control what gets summarized, and critical details can be lost.
  673.  
  674. **Recommendation**: Manage compaction manually.
  675.  
  676. Add to your `CLAUDE.md`:
  677.  
  678. ```markdown
  679. ## Context Management Rules
  680.  
  681. - NEVER auto-compact. I will manage context manually.
  682. - When context exceeds 70%, warn me immediately.
  683. - Include a "Context: XX%" note in your responses when above 50%.
  684. ```
  685.  
  686. ### The /context Status Pattern
  687.  
  688. Create `~/.claude/commands/status.md`:
  689.  
  690. ```markdown
  691. ---
  692. description: Show current context status and recommendations
  693. ---
  694.  
  695. Provide a context status report:
  696.  
  697. ## Context Status
  698. - **Current Usage**: [X]% of context window
  699. - **Estimated Tokens**: [X]k / 200k
  700. - **Files in Context**: [list main files]
  701. - **Conversation Turns**: [X]
  702.  
  703. ## Health Assessment
  704. - [ ] Under 50%: ✅ Healthy
  705. - [ ] 50-70%: ⚠️ Consider clearing soon
  706. - [ ] Over 70%: 🔴 Clear recommended
  707.  
  708. ## Recommendations
  709. [If over 50%, suggest what could be cleared or compacted]
  710.  
  711. ## Key Context to Preserve
  712. [List the most important things that should survive a /clear]
  713. ```
  714.  
  715. ### The “Double-Escape Time Travel” Pattern
  716.  
  717. This is the most underutilized feature in Claude Code:
  718.  
  719. 1. **Press Escape once**: Interrupts current Claude operation
  720. 1. **Press Escape twice**: Opens the **Rewind** interface
  721.  
  722. The Rewind interface lets you:
  723.  
  724. - See your full conversation history with diffs
  725. - Select ANY previous point to restore to
  726. - Restore BOTH code AND conversation state
  727. - Explore alternative approaches without losing work
  728.  
  729. ### Context Management Workflow
  730.  
  731. ```
  732. ┌─────────────────────────────────────────────────────────────┐
  733. │ │
  734. │ 1. Start Fresh: /clear │
  735. │ └── Begin with clean context │
  736. │ │
  737. │ 2. Work Phase: Write code, iterate │
  738. │ └── Monitor: "what's my context usage?" │
  739. │ │
  740. │ 3. Checkpoint (at 50%): Document state │
  741. │ └── Save important decisions to CLAUDE.md or notes │
  742. │ │
  743. │ 4. Continue or Clear (at 70%): │
  744. │ ├── Option A: /compact with specific instructions │
  745. │ └── Option B: /clear + restore from notes │
  746. │ │
  747. │ 5. Emergency: Double-Escape │
  748. │ └── Rewind to any previous state │
  749. │ │
  750. └─────────────────────────────────────────────────────────────┘
  751. ```
  752.  
  753. ### Smart Compaction Command
  754.  
  755. Create `~/.claude/commands/smart-compact.md`:
  756.  
  757. ```markdown
  758. ---
  759. description: Compact context with explicit preservation rules
  760. ---
  761.  
  762. Perform a smart compaction:
  763.  
  764. ## MUST PRESERVE (never summarize away):
  765. 1. Current task/goal
  766. 2. All file paths mentioned in last 10 messages
  767. 3. Any explicit decisions or constraints I stated
  768. 4. Error messages and their solutions
  769. 5. The current plan/checklist if one exists
  770.  
  771. ## CAN SUMMARIZE:
  772. 1. Exploration that led to dead ends
  773. 2. Verbose output from commands (keep just the conclusion)
  774. 3. File contents that haven't been modified
  775. 4. General discussion that led to decisions (keep just decisions)
  776.  
  777. ## FORMAT:
  778. After compaction, start your next message with:
  779. ```
  780.  
  781. 📦 Context compacted. Preserved:
  782.  
  783. - [key item 1]
  784. - [key item 2]
  785. - [current goal]
  786.  
  787. ```
  788. Now perform /compact with these rules in mind.
  789. ```
  790.  
  791. -----
  792.  
  793. ## 6. Pattern 5: Subagent Control
  794.  
  795. ### The Default Problem
  796.  
  797. Claude Code spawns subagents for various tasks, but by default may use cheaper/faster models (Sonnet, Haiku) even when you’re paying for Opus. This leads to:
  798.  
  799. - Lower quality analysis for “research” tasks
  800. - Inconsistent code quality between main agent and subagents
  801. - Wasted context when subagent returns poor results
  802.  
  803. ### Force Opus Subagents
  804.  
  805. Add to your global `~/.claude/CLAUDE.md`:
  806.  
  807. ```markdown
  808. ## Subagent Rules
  809.  
  810. - **ALWAYS use Opus for subagents** unless I explicitly request otherwise
  811. - Subagents should be used for:
  812. - Research and investigation tasks
  813. - Parallel analysis of multiple files
  814. - Code review of changes
  815. - Test generation
  816. - Documentation writing
  817. - Before spawning a subagent, tell me what it will do
  818. - After subagent completes, summarize its findings concisely
  819. ```
  820.  
  821. ### Custom Subagent Collection
  822.  
  823. Create specialized subagents in `~/.claude/agents/`:
  824.  
  825. #### Code Reviewer (`~/.claude/agents/code-reviewer.md`)
  826.  
  827. ```markdown
  828. ---
  829. name: code-reviewer
  830. description: Expert code review focusing on bugs, security, and maintainability
  831. tools: Read, Grep, Glob
  832. model: opus
  833. ---
  834.  
  835. You are a senior code reviewer with expertise in:
  836. - Security vulnerabilities
  837. - Performance issues
  838. - Code maintainability
  839. - Testing gaps
  840.  
  841. When reviewing code:
  842.  
  843. 1. **First Pass - Critical Issues**
  844. - Security vulnerabilities (injection, auth, data exposure)
  845. - Logic errors that could cause bugs
  846. - Race conditions or concurrency issues
  847.  
  848. 2. **Second Pass - Quality Issues**
  849. - Code duplication
  850. - Complex functions that need refactoring
  851. - Missing error handling
  852. - Unclear naming
  853.  
  854. 3. **Third Pass - Suggestions**
  855. - Performance improvements
  856. - Better patterns/abstractions
  857. - Documentation needs
  858.  
  859. Output format:
  860. ```
  861.  
  862. ## Critical 🔴
  863.  
  864. - [file:line] Issue description
  865.  
  866. ## Important 🟡
  867.  
  868. - [file:line] Issue description
  869.  
  870. ## Suggestions 🟢
  871.  
  872. - [file:line] Suggestion
  873.  
  874. ```
  875. Be specific. Include line numbers. Suggest fixes.
  876. ```
  877.  
  878. #### Test Writer (`~/.claude/agents/test-writer.md`)
  879.  
  880. ```markdown
  881. ---
  882. name: test-writer
  883. description: Writes comprehensive tests with edge case coverage
  884. tools: Read, Write, Bash
  885. model: opus
  886. ---
  887.  
  888. You are a testing expert. When writing tests:
  889.  
  890. ## Principles
  891. 1. **Test behavior, not implementation**
  892. 2. **One assertion per test** (when practical)
  893. 3. **Descriptive test names**: "should_return_empty_array_when_input_is_null"
  894. 4. **Arrange-Act-Assert** structure
  895. 5. **Cover edge cases systematically**
  896.  
  897. ## Edge Case Checklist
  898. - [ ] Null/undefined inputs
  899. - [ ] Empty strings/arrays/objects
  900. - [ ] Boundary values (0, -1, MAX_INT)
  901. - [ ] Invalid types
  902. - [ ] Unicode/special characters
  903. - [ ] Concurrent access (if applicable)
  904. - [ ] Error conditions
  905.  
  906. ## Test Structure
  907. ```
  908.  
  909. describe(’[Unit Under Test]’, () => {
  910. describe(’[Method/Function]’, () => {
  911. describe(‘when [condition]’, () => {
  912. it(‘should [expected behavior]’, () => {
  913. // Arrange
  914. // Act
  915. // Assert
  916. });
  917. });
  918. });
  919. });
  920.  
  921. ```
  922. Match existing test patterns in the codebase.
  923. ```
  924.  
  925. #### Architecture Analyst (`~/.claude/agents/architect.md`)
  926.  
  927. ```markdown
  928. ---
  929. name: architect
  930. description: Analyzes codebase architecture and suggests improvements
  931. tools: Read, Grep, Glob
  932. model: opus
  933. ---
  934.  
  935. You are a software architect. When analyzing code:
  936.  
  937. ## Analysis Framework
  938.  
  939. ### 1. Dependency Analysis
  940. - Map module dependencies
  941. - Identify circular dependencies
  942. - Find highly-coupled components
  943. - Locate god objects/modules
  944.  
  945. ### 2. Pattern Recognition
  946. - What architectural patterns are used?
  947. - Are they applied consistently?
  948. - What patterns are missing that would help?
  949.  
  950. ### 3. Scalability Assessment
  951. - Bottleneck identification
  952. - Horizontal scaling readiness
  953. - Database/storage patterns
  954.  
  955. ### 4. Maintainability Score
  956. Rate 1-10 with justification:
  957. - Code organization
  958. - Separation of concerns
  959. - Test coverage
  960. - Documentation
  961.  
  962. ## Output Format
  963. ```markdown
  964. # Architecture Analysis: [Component/System]
  965.  
  966. ## Current State
  967. [Diagram or description]
  968.  
  969. ## Strengths
  970. -
  971.  
  972. ## Concerns
  973. -
  974.  
  975. ## Recommendations
  976. 1. [Priority] Description
  977. 2. [Priority] Description
  978.  
  979. ## Suggested Refactoring Roadmap
  980. Phase 1: [Quick wins]
  981. Phase 2: [Medium effort]
  982. Phase 3: [Major refactoring]
  983. ```
  984.  
  985. ```
  986. ### Orchestrator Pattern
  987.  
  988. For complex tasks, use a main agent + specialized subagents:
  989. ```
  990.  
  991. ┌─────────────────────────────────────────────────────────────┐
  992. │ Main Agent (Opus) │
  993. │ - Task planning │
  994. │ - Decision making │
  995. │ - Result synthesis │
  996. └─────────────────────────────────────────────────────────────┘
  997. │
  998. ┌───────────────────┼───────────────────┐
  999. │ │ │
  1000. ▼ ▼ ▼
  1001. ┌─────────────┐ ┌─────────────┐ ┌─────────────┐
  1002. │ code-reviewer│ │ test-writer │ │ architect │
  1003. │ (Opus) │ │ (Opus) │ │ (Opus) │
  1004. └─────────────┘ └─────────────┘ └─────────────┘
  1005.  
  1006. ```
  1007. ### Subagent Monitoring Dashboard
  1008.  
  1009. See [Section 8](#8-subagent-monitoring-dashboard) for complete implementation.
  1010.  
  1011. ---
  1012.  
  1013. ## 7. Pattern 6: The Reprompter System
  1014.  
  1015. ### The Problem with Typing Prompts
  1016.  
  1017. - High-quality prompts take time to type
  1018. - Typing interrupts flow state
  1019. - Easy to forget important constraints
  1020. - Inconsistent prompt quality
  1021.  
  1022. ### The Solution: Voice → Structure Pipeline
  1023. ```
  1024.  
  1025. ┌──────────────┐ ┌──────────────┐ ┌──────────────┐
  1026. │ Voice │────▶│ Clarifying │────▶│ Structured │
  1027. │ Dictation │ │ Questions │ │ Prompt │
  1028. └──────────────┘ └──────────────┘ └──────────────┘
  1029. │ │ │
  1030. │ │ │
  1031. Raw idea Refinement XML-tagged
  1032. (messy) (dialog) (optimal)
  1033.  
  1034. ```
  1035. ### Implementation
  1036.  
  1037. #### 1. Voice Input Setup
  1038.  
  1039. Use your OS dictation or a tool like:
  1040. - macOS: Built-in dictation (Fn Fn)
  1041. - Windows: Windows Speech Recognition
  1042. - Cross-platform: Whisper API, Talon
  1043.  
  1044. #### 2. Reprompter Command (`~/.claude/commands/reprompt.md`)
  1045.  
  1046. ```markdown
  1047. ---
  1048. description: Convert rough voice input into a structured prompt
  1049. argument-hint: [rough-idea]
  1050. ---
  1051.  
  1052. I'm going to give you a rough, voice-dictated idea. Your job is to:
  1053.  
  1054. ## Step 1: Understand
  1055. Ask me clarifying questions to understand:
  1056. - What is the specific goal?
  1057. - What are the constraints?
  1058. - What does success look like?
  1059. - What context do I need to provide?
  1060.  
  1061. Ask ONE question at a time. Wait for my answer.
  1062.  
  1063. ## Step 2: Structure
  1064. Once you understand, create a structured prompt using this format:
  1065.  
  1066. ```xml
  1067. <task>
  1068. <goal>[Clear, specific objective]</goal>
  1069.  
  1070. <context>
  1071. <files>[Relevant files to read]</files>
  1072. <background>[Key context]</background>
  1073. </context>
  1074.  
  1075. <constraints>
  1076. <must>[Required elements]</must>
  1077. <must_not>[Forbidden elements]</must_not>
  1078. </constraints>
  1079.  
  1080. <output>
  1081. <format>[Expected output format]</format>
  1082. <success_criteria>[How to verify success]</success_criteria>
  1083. </output>
  1084. </task>
  1085. ```
  1086.  
  1087. ## Step 3: Confirm
  1088.  
  1089. Show me the structured prompt and ask if it captures my intent correctly.
  1090.  
  1091. -----
  1092.  
  1093. My rough idea: $ARGUMENTS
  1094.  
  1095. ```
  1096. #### 3. Quick Reprompt for Simple Tasks
  1097.  
  1098. Create `~/.claude/commands/qr.md` (quick reprompt):
  1099.  
  1100. ```markdown
  1101. ---
  1102. description: Quick reprompt - one clarifying question, then execute
  1103. argument-hint: [task]
  1104. ---
  1105.  
  1106. Task: $ARGUMENTS
  1107.  
  1108. Before executing, ask me ONE clarifying question to ensure you understand the most critical aspect of this task.
  1109.  
  1110. After I answer, proceed with execution.
  1111. ```
  1112.  
  1113. ### Example Session
  1114.  
  1115. ```
  1116. You: /reprompt I need to like refactor the auth thing to use that new pattern we discussed, you know the one with the middleware
  1117.  
  1118. Claude: I want to make sure I understand correctly. When you say "the new pattern with middleware," are you referring to:
  1119. 1. A specific middleware pattern we discussed earlier in this session?
  1120. 2. A pattern documented somewhere in your codebase?
  1121. 3. A general middleware authentication pattern (like JWT validation middleware)?
  1122.  
  1123. You: Number 2, it's in docs/auth-v2.md
  1124.  
  1125. Claude: Got it. One more question: Should this refactoring:
  1126. A) Replace the existing auth system entirely
  1127. B) Run alongside it temporarily (migration path)
  1128. C) Just update specific components?
  1129.  
  1130. You: A, full replacement
  1131.  
  1132. Claude: Here's your structured prompt:
  1133.  
  1134. <task>
  1135. <goal>Refactor authentication system to use the pattern defined in docs/auth-v2.md</goal>
  1136.  
  1137. <context>
  1138. <files>docs/auth-v2.md, src/auth/**, src/middleware/**</files>
  1139. <background>Full replacement of existing auth - no parallel running</background>
  1140. </context>
  1141.  
  1142. <constraints>
  1143. <must>Follow patterns exactly as documented in auth-v2.md</must>
  1144. <must>Maintain all existing auth-protected routes</must>
  1145. <must>Include migration for existing user sessions</must>
  1146. <must_not>Leave any deprecated auth code active</must_not>
  1147. </constraints>
  1148.  
  1149. <output>
  1150. <format>Modified files with new auth implementation</format>
  1151. <success_criteria>All existing tests pass, new auth tests added, documented in CHANGELOG</success_criteria>
  1152. </output>
  1153. </task>
  1154.  
  1155. Does this capture your intent? Ready to proceed?
  1156. ```
  1157.  
  1158. -----
  1159.  
  1160. ## 8. Subagent Monitoring Dashboard
  1161.  
  1162. A simple React-based dashboard for monitoring subagent activity.
  1163.  
  1164. ### Installation
  1165.  
  1166. ```bash
  1167. # Create the monitoring directory
  1168. mkdir -p ~/.claude/monitoring
  1169. cd ~/.claude/monitoring
  1170.  
  1171. # Create package.json
  1172. npm init -y
  1173. npm install react react-dom next tailwindcss
  1174. ```
  1175.  
  1176. ### Dashboard Code (`~/.claude/monitoring/pages/index.tsx`)
  1177.  
  1178. ```tsx
  1179. import React, { useState, useEffect } from 'react';
  1180.  
  1181. interface SubagentLog {
  1182. timestamp: string;
  1183. agentName: string;
  1184. task: string;
  1185. model: string;
  1186. tokensUsed: number;
  1187. duration: number;
  1188. status: 'running' | 'completed' | 'failed';
  1189. result?: string;
  1190. }
  1191.  
  1192. interface SessionStats {
  1193. totalTokens: number;
  1194. totalDuration: number;
  1195. agentBreakdown: Record<string, number>;
  1196. }
  1197.  
  1198. export default function Dashboard() {
  1199. const [logs, setLogs] = useState<SubagentLog[]>([]);
  1200. const [stats, setStats] = useState<SessionStats | null>(null);
  1201.  
  1202. useEffect(() => {
  1203. // Poll for updates every 2 seconds
  1204. const interval = setInterval(() => {
  1205. fetchLogs();
  1206. }, 2000);
  1207.  
  1208. fetchLogs();
  1209. return () => clearInterval(interval);
  1210. }, []);
  1211.  
  1212. const fetchLogs = async () => {
  1213. try {
  1214. const res = await fetch('/api/logs');
  1215. const data = await res.json();
  1216. setLogs(data.logs);
  1217. setStats(data.stats);
  1218. } catch (e) {
  1219. console.error('Failed to fetch logs:', e);
  1220. }
  1221. };
  1222.  
  1223. const getStatusColor = (status: string) => {
  1224. switch (status) {
  1225. case 'running': return 'bg-yellow-500';
  1226. case 'completed': return 'bg-green-500';
  1227. case 'failed': return 'bg-red-500';
  1228. default: return 'bg-gray-500';
  1229. }
  1230. };
  1231.  
  1232. return (
  1233. <div className="min-h-screen bg-gray-900 text-white p-8">
  1234. <h1 className="text-3xl font-bold mb-8">🤖 Subagent Monitor</h1>
  1235.  
  1236. {/* Stats Panel */}
  1237. {stats && (
  1238. <div className="grid grid-cols-3 gap-4 mb-8">
  1239. <div className="bg-gray-800 p-4 rounded-lg">
  1240. <h3 className="text-gray-400 text-sm">Total Tokens</h3>
  1241. <p className="text-2xl font-bold">{stats.totalTokens.toLocaleString()}</p>
  1242. </div>
  1243. <div className="bg-gray-800 p-4 rounded-lg">
  1244. <h3 className="text-gray-400 text-sm">Total Duration</h3>
  1245. <p className="text-2xl font-bold">{(stats.totalDuration / 1000).toFixed(1)}s</p>
  1246. </div>
  1247. <div className="bg-gray-800 p-4 rounded-lg">
  1248. <h3 className="text-gray-400 text-sm">Active Agents</h3>
  1249. <p className="text-2xl font-bold">
  1250. {logs.filter(l => l.status === 'running').length}
  1251. </p>
  1252. </div>
  1253. </div>
  1254. )}
  1255.  
  1256. {/* Agent Breakdown */}
  1257. {stats && (
  1258. <div className="bg-gray-800 p-4 rounded-lg mb-8">
  1259. <h3 className="text-lg font-semibold mb-4">Token Usage by Agent</h3>
  1260. <div className="space-y-2">
  1261. {Object.entries(stats.agentBreakdown).map(([agent, tokens]) => (
  1262. <div key={agent} className="flex items-center">
  1263. <span className="w-32 text-sm">{agent}</span>
  1264. <div className="flex-1 bg-gray-700 rounded h-4">
  1265. <div
  1266. className="bg-blue-500 h-4 rounded"
  1267. style={{ width: `${(tokens / stats.totalTokens) * 100}%` }}
  1268. />
  1269. </div>
  1270. <span className="w-24 text-right text-sm">
  1271. {tokens.toLocaleString()}
  1272. </span>
  1273. </div>
  1274. ))}
  1275. </div>
  1276. </div>
  1277. )}
  1278.  
  1279. {/* Activity Log */}
  1280. <div className="bg-gray-800 rounded-lg overflow-hidden">
  1281. <h3 className="text-lg font-semibold p-4 border-b border-gray-700">
  1282. Activity Log
  1283. </h3>
  1284. <div className="divide-y divide-gray-700 max-h-96 overflow-y-auto">
  1285. {logs.map((log, i) => (
  1286. <div key={i} className="p-4 hover:bg-gray-750">
  1287. <div className="flex items-center justify-between mb-2">
  1288. <div className="flex items-center space-x-3">
  1289. <span className={`w-2 h-2 rounded-full ${getStatusColor(log.status)}`} />
  1290. <span className="font-medium">{log.agentName}</span>
  1291. <span className="text-gray-400 text-sm">({log.model})</span>
  1292. </div>
  1293. <span className="text-gray-400 text-sm">{log.timestamp}</span>
  1294. </div>
  1295. <p className="text-sm text-gray-300 mb-2">{log.task}</p>
  1296. <div className="flex space-x-4 text-xs text-gray-500">
  1297. <span>⏱ {log.duration}ms</span>
  1298. <span>📊 {log.tokensUsed} tokens</span>
  1299. </div>
  1300. {log.result && log.status === 'completed' && (
  1301. <div className="mt-2 p-2 bg-gray-900 rounded text-sm">
  1302. {log.result.substring(0, 200)}...
  1303. </div>
  1304. )}
  1305. </div>
  1306. ))}
  1307. </div>
  1308. </div>
  1309. </div>
  1310. );
  1311. }
  1312. ```
  1313.  
  1314. ### Log Collection Hook
  1315.  
  1316. Add to your hooks configuration to feed the dashboard:
  1317.  
  1318. ```json
  1319. {
  1320. "hooks": {
  1321. "PreToolUse": [
  1322. {
  1323. "matcher": "Task",
  1324. "hooks": [
  1325. {
  1326. "type": "command",
  1327. "command": "~/.claude/monitoring/log-subagent.sh start"
  1328. }
  1329. ]
  1330. }
  1331. ],
  1332. "PostToolUse": [
  1333. {
  1334. "matcher": "Task",
  1335. "hooks": [
  1336. {
  1337. "type": "command",
  1338. "command": "~/.claude/monitoring/log-subagent.sh complete"
  1339. }
  1340. ]
  1341. }
  1342. ]
  1343. }
  1344. }
  1345. ```
  1346.  
  1347. ### Log Script (`~/.claude/monitoring/log-subagent.sh`)
  1348.  
  1349. ```bash
  1350. #!/bin/bash
  1351.  
  1352. ACTION=$1
  1353. INPUT=$(cat)
  1354. TIMESTAMP=$(date -Iseconds)
  1355. LOG_FILE="$HOME/.claude/monitoring/logs/$(date +%Y-%m-%d).json"
  1356.  
  1357. mkdir -p "$HOME/.claude/monitoring/logs"
  1358.  
  1359. AGENT_NAME=$(echo "$INPUT" | jq -r '.tool_input.description // "unknown"')
  1360. MODEL=$(echo "$INPUT" | jq -r '.model // "unknown"')
  1361. TASK=$(echo "$INPUT" | jq -r '.tool_input.prompt // ""' | head -c 200)
  1362.  
  1363. if [ "$ACTION" = "start" ]; then
  1364. echo "{\"timestamp\": \"$TIMESTAMP\", \"agentName\": \"$AGENT_NAME\", \"model\": \"$MODEL\", \"task\": \"$TASK\", \"status\": \"running\"}" >> "$LOG_FILE"
  1365. elif [ "$ACTION" = "complete" ]; then
  1366. RESULT=$(echo "$INPUT" | jq -r '.result // ""' | head -c 500)
  1367. TOKENS=$(echo "$INPUT" | jq -r '.tokens_used // 0')
  1368. echo "{\"timestamp\": \"$TIMESTAMP\", \"agentName\": \"$AGENT_NAME\", \"model\": \"$MODEL\", \"status\": \"completed\", \"result\": \"$RESULT\", \"tokensUsed\": $TOKENS}" >> "$LOG_FILE"
  1369. fi
  1370.  
  1371. exit 0
  1372. ```
  1373.  
  1374. -----
  1375.  
  1376. ## 9. Quick Reference Table
  1377.  
  1378. ### Keyboard Shortcuts
  1379.  
  1380. |Shortcut |Action |
  1381. |---------------|------------------------------|
  1382. |`Escape` |Interrupt current operation |
  1383. |`Escape Escape`|Open Rewind (time travel) |
  1384. |`Shift + Tab` |Toggle Plan Mode / Auto-accept|
  1385. |`Ctrl + C` |Exit Claude Code |
  1386. |`↑` / `↓` |Navigate prompt history |
  1387.  
  1388. ### Essential Commands
  1389.  
  1390. |Command |Purpose |When to Use |
  1391. |--------------|---------------------|-----------------------------------|
  1392. |`/clear` |Clear conversation |Starting new task, context bloat |
  1393. |`/compact` |Summarize context |Approaching 70% usage |
  1394. |`/context` |Show context usage |Regular monitoring |
  1395. |`/rewind` |Time travel UI |Made a mistake, want to undo |
  1396. |`/help` |List all commands |Forgot command names |
  1397. |`/model` |Switch model |Cost optimization, capability needs|
  1398. |`/agents` |Manage subagents |Configure custom agents |
  1399. |`/permissions`|View/edit permissions|Troubleshooting tool access |
  1400. |`/hooks` |Manage hooks |Review/update safety rules |
  1401.  
  1402. ### Context Management Thresholds
  1403.  
  1404. |Context %|Status |Action |
  1405. |---------|----------|------------------------------------|
  1406. |0-40% |🟢 Healthy |Work freely |
  1407. |40-60% |🟡 Watch |Be selective about new files |
  1408. |60-80% |🟠 Caution |Consider compacting |
  1409. |80-95% |🔴 Critical|/clear or targeted /compact |
  1410. |95-100% |⛔ Danger |Auto-compact triggers (uncontrolled)|
  1411.  
  1412. ### Model Selection Guide
  1413.  
  1414. |Model |Best For |Cost|Speed |
  1415. |----------|----------------------------------------------|----|------|
  1416. |Opus 4.5 |Architecture, complex reasoning, critical code|$$$ |Slow |
  1417. |Sonnet 4.5|Most coding tasks, balanced |$$ |Medium|
  1418. |Haiku 4.5 |Quick queries, simple tasks, exploration |$ |Fast |
  1419.  
  1420. ### File Locations
  1421.  
  1422. |Path |Purpose |
  1423. |-----------------------------|-----------------------------------|
  1424. |`~/.claude/CLAUDE.md` |Global instructions |
  1425. |`~/.claude/settings.json` |Global settings, hooks |
  1426. |`~/.claude/commands/` |Personal slash commands |
  1427. |`~/.claude/agents/` |Custom subagents |
  1428. |`.claude/CLAUDE.md` |Project instructions (team) |
  1429. |`.claude/settings.json` |Project settings (team) |
  1430. |`.claude/settings.local.json`|Local project settings (gitignored)|
  1431. |`.claude/commands/` |Project slash commands |
  1432. |`.claude/agents/` |Project subagents |
  1433.  
  1434. ### Safety Hook Checklist
  1435.  
  1436. |Hook Type |Recommended Use |
  1437. |-------------------------|------------------------|
  1438. |`PreToolUse:Bash` |Block dangerous commands|
  1439. |`PreToolUse:Write` |Protect sensitive files |
  1440. |`PostToolUse:Write(*.py)`|Auto-format Python |
  1441. |`PostToolUse:Write(*.ts)`|Auto-format + typecheck |
  1442. |`PostToolUse:Edit` |Run linters |
  1443. |`Stop` |Session summary logging |
  1444.  
  1445. ### Prompt Quality Checklist
  1446.  
  1447. Before sending a prompt, verify:
  1448.  
  1449. - [ ] **Goal is specific**: What exactly should happen?
  1450. - [ ] **Context is provided**: What files/info does Claude need?
  1451. - [ ] **Constraints are explicit**: What must/must not happen?
  1452. - [ ] **Success criteria defined**: How do I know it’s done?
  1453. - [ ] **Examples given**: For complex patterns, show don’t tell
  1454.  
  1455. ### Error Recovery Flowchart
  1456.  
  1457. ```
  1458. Issue Detected
  1459. │
  1460. ▼
  1461. Small/Local? ────Yes────▶ Escape Escape (Rewind)
  1462. │ │
  1463. No Pick restore point
  1464. │ │
  1465. ▼ ▼
  1466. Code broken? ────Yes────▶ git checkout / git stash
  1467. │
  1468. No
  1469. │
  1470. ▼
  1471. Context rot? ────Yes────▶ /clear + restart with notes
  1472. │
  1473. No
  1474. │
  1475. ▼
  1476. Log to error journal for pattern analysis
  1477. ```
  1478.  
  1479. -----
  1480.  
  1481. ## Appendix: CLAUDE.md Template
  1482.  
  1483. Copy this to your project root and customize:
  1484.  
  1485. ```markdown
  1486. # Project: [NAME]
  1487.  
  1488. ## Overview
  1489. [2-3 sentences describing the project]
  1490.  
  1491. ## Tech Stack
  1492. - Language: [e.g., TypeScript 5.3]
  1493. - Framework: [e.g., Next.js 14]
  1494. - Database: [e.g., PostgreSQL + Prisma]
  1495. - Testing: [e.g., Jest + React Testing Library]
  1496.  
  1497. ## Key Commands
  1498. - `npm run dev` - Start development server
  1499. - `npm run build` - Production build
  1500. - `npm run test` - Run tests
  1501. - `npm run lint` - Run linter
  1502.  
  1503. ## Project Structure
  1504. ```
  1505.  
  1506. src/
  1507. ├── app/ # Next.js app router
  1508. ├── components/ # React components
  1509. ├── lib/ # Utilities and helpers
  1510. ├── hooks/ # Custom React hooks
  1511. └── types/ # TypeScript types
  1512.  
  1513. ```
  1514. ## Coding Standards
  1515. - Use functional components with hooks
  1516. - Prefer named exports over default exports
  1517. - One component per file
  1518. - Tests go in `__tests__/` directories
  1519.  
  1520. ## Important Patterns
  1521. - State management: [describe pattern]
  1522. - API calls: [describe pattern]
  1523. - Error handling: [describe pattern]
  1524.  
  1525. ## DO NOT
  1526. - Modify files in `node_modules/`
  1527. - Commit to main directly
  1528. - Skip tests for new features
  1529.  
  1530. ## Subagent Rules
  1531. - Always use Opus for subagents
  1532. - Announce before spawning subagents
  1533. - Summarize subagent results concisely
  1534.  
  1535. ## Context Management
  1536. - Warn when context exceeds 60%
  1537. - Include "Context: X%" in responses when >50%
  1538. - Never auto-compact without asking
  1539. ```
  1540.  
  1541. -----
  1542.  
  1543. *Guide version 1.0 | Last updated: January 2026*
Add Comment
Please, Sign In to add comment