diff --git a/LICENSE b/LICENSE index b8c8de2..3b7b82d 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,427 @@ -MIT License +Attribution-ShareAlike 4.0 International -Copyright (c) 2026 Florian BRUNIAUX +======================================================================= -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Using Creative Commons Public Licenses -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-ShareAlike 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-ShareAlike 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. BY-SA Compatible License means a license listed at + creativecommons.org/compatiblelicenses, approved by Creative + Commons as essentially the equivalent of this Public License. + + d. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + e. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + f. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + g. License Elements means the license attributes listed in the name + of a Creative Commons Public License. The License Elements of this + Public License are Attribution and ShareAlike. + + h. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + i. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + j. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + k. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + l. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + m. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. Additional offer from the Licensor -- Adapted Material. + Every recipient of Adapted Material from You + automatically receives an offer from the Licensor to + exercise the Licensed Rights in the Adapted Material + under the conditions of the Adapter's License You apply. + + c. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + b. ShareAlike. + + In addition to the conditions in Section 3(a), if You Share + Adapted Material You produce, the following conditions also apply. + + 1. The Adapter's License You apply must be a Creative Commons + license with the same License Elements, this version or + later, or a BY-SA Compatible License. + + 2. You must include the text of, or the URI or hyperlink to, the + Adapter's License You apply. You may satisfy this condition + in any reasonable manner based on the medium, means, and + context in which You Share Adapted Material. + + 3. You may not offer or impose any additional or different terms + or conditions on, or apply any Effective Technological + Measures to, Adapted Material that restrict exercise of the + rights granted under the Adapter's License You apply. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material, + + including for purposes of Section 3(b); and + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/README.md b/README.md new file mode 100644 index 0000000..64eb6a0 --- /dev/null +++ b/README.md @@ -0,0 +1,174 @@ +# The Ultimate Claude Code Guide + +> From zero to power user — a comprehensive, self-contained guide to mastering Claude Code. + +[![License: CC BY-SA 4.0](https://img.shields.io/badge/License-CC%20BY--SA%204.0-lightgrey.svg)](https://creativecommons.org/licenses/by-sa/4.0/) + +**Author**: [Florian BRUNIAUX](https://github.com/FlorianBruniaux) | Founding Engineer [@Méthode Aristote](https://methode-aristote.fr) + +**Contact**: [LinkedIn](https://www.linkedin.com/in/florian-bruniaux-43408b83/) + +**Written with**: Claude (Anthropic) + +--- + +## About This Guide + +This guide is the result of **several months of daily practice and research** with Claude Code. I don't claim to be an "expert" — I'm simply sharing what I've learned along the way, humbly hoping to help my peers and evangelize good practices in AI-assisted development. + +A significant source of inspiration for this work was [Claudelog.com](https://claudelog.com/), which I highly recommend for anyone wanting to go deeper. + +If you find value in this guide, have questions, or want to discuss Claude Code practices, feel free to reach out on [LinkedIn](https://www.linkedin.com/in/florian-bruniaux-43408b83/). + +--- + +## What's Inside + +| File | Description | Reading Time | +|------|-------------|--------------| +| [`english-ultimate-claude-code-guide.md`](./english-ultimate-claude-code-guide.md) | Complete guide (4000+ lines) | ~2.5 hours | +| [`cheatsheet-en.md`](./cheatsheet-en.md) | 1-page printable daily reference | 5 minutes | +| [`claude-code-ultimate-guide_notebooklm.pdf`](./claude-code-ultimate-guide_notebooklm.pdf) | Audio Deep Dive (NotebookLM podcast) | ~1 hour | +| [`claude-code-ultimate-guide_kimi.pdf`](./claude-code-ultimate-guide_kimi.pdf) | PDF version (Kimi export) | ~2.5 hours | + +--- + +## Guide Overview + +### 1. Quick Start (Day 1) +Installation, first workflow, essential commands, permission modes. + +### 2. Core Concepts +- **Context Management** — The most critical concept (zones, recovery, poisoning) +- **Plan Mode** — Safe exploration before changes +- **Rewind** — Undo mistakes safely +- **Mental Model** — How Claude sees your codebase + +### 3. Configuration +- `CLAUDE.md` files (global, project, local) +- The `.claude/` folder structure +- Settings & permissions +- Precedence rules + +### 4. Agents +Create specialized AI personas for specific tasks: +- Code reviewer, debugger, backend architect +- Tool SEO for better agent discovery +- Multi-agent orchestration patterns + +### 5. Skills +Reusable knowledge modules: +- Security Guardian (OWASP, secrets management) +- TDD (Red-Green-Refactor cycle) +- Creating your own skills + +### 6. Commands +Custom slash commands: +- `/commit`, `/pr`, problem framer +- Variable interpolation with `$ARGUMENTS` + +### 7. Hooks +Event-driven automation: +- Security blockers (pre-tool use) +- Auto-formatters (post-tool use) +- Context enrichers (prompt submit) +- Activity logging + +### 8. MCP Servers +External tool integrations: +- **Serena** — Semantic code navigation +- **Context7** — Library documentation +- **Sequential** — Structured reasoning +- **Playwright** — Browser automation +- **Postgres** — Database queries + +### 9. Advanced Patterns +- The Trinity (Plan + Think + Agents) +- CI/CD & IDE integration +- Tight feedback loops +- Todo as instruction mirrors +- Vibe coding & skeleton projects +- Batch operations + +### 10. Reference +Commands table, keyboard shortcuts, troubleshooting, checklists. + +### Appendix +Ready-to-use templates for agents, skills, commands, hooks, settings, and prompts. + +--- + +## Quick Start + +```bash +# Install Claude Code +curl -fsSL https://claude.ai/install.sh | sh + +# Start in your project +cd your-project +claude +``` + +### The 7 Commands You Need + +| Command | Action | +|---------|--------| +| `/help` | Show all commands | +| `/status` | Check context usage | +| `/compact` | Compress context (>70%) | +| `/clear` | Fresh start | +| `/plan` | Safe read-only mode | +| `/rewind` | Undo changes | +| `Ctrl+C` | Cancel operation | + +### Context Management (Critical!) + +| Context % | Action | +|-----------|--------| +| 0-50% | Work freely | +| 50-70% | Be selective | +| 70-90% | `/compact` now | +| 90%+ | `/clear` required | + +--- + +## The Golden Rules + +1. **Always review diffs** before accepting changes +2. **Use `/compact`** before context gets critical (>70%) +3. **Be specific** in requests (WHAT, WHERE, HOW, VERIFY) +4. **Start with Plan Mode** for complex/risky tasks +5. **Create CLAUDE.md** for every project + +--- + +## Who Is This For? + +- **Beginners**: Start with Quick Start (15 min) → be productive immediately +- **Intermediate**: Deep dive into Configuration, Agents, Skills +- **Power Users**: Advanced Patterns, MCP orchestration, CI/CD integration + +--- + +## Contributing + +Found an error? Have a suggestion? Open an issue or PR. + +--- + +## Resources + +- [Official Claude Code Documentation](https://docs.anthropic.com/en/docs/claude-code) +- [Claudelog.com](https://claudelog.com/) — Advanced tips & patterns (inspiration for some sections) + +--- + +## License + +This work is licensed under [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). + +You are free to share and adapt this material, provided you give appropriate credit and distribute your contributions under the same license. + +--- + +*Last updated: January 2025 | Version 1.0* \ No newline at end of file diff --git a/cheatsheet-en.md b/cheatsheet-en.md new file mode 100644 index 0000000..697e6e6 --- /dev/null +++ b/cheatsheet-en.md @@ -0,0 +1,298 @@ +# Claude Code Cheatsheet + +**1 printable page** - Daily essentials + +**Author**: Florian BRUNIAUX | Founding Engineer [@Méthode Aristote](https://methode-aristote.fr) + +**Written with**: Claude (Anthropic) + +--- + +## Essential Commands + +| Command | Action | +|---------|--------| +| `/help` | Contextual help | +| `/clear` | Reset conversation | +| `/compact` | Free up context | +| `/context` | View token usage | +| `/status` | Session state | +| `/exit` | Quit (or Ctrl+D) | + +--- + +## Keyboard Shortcuts + +| Shortcut | Action | +|----------|--------| +| `Shift+Tab` | Cycle permission modes | +| `Esc` × 2 | Rewind (undo) | +| `Ctrl+C` | Interrupt | +| `Tab` | Autocomplete | +| `Shift+Enter` | New line | +| `Ctrl+D` | Exit | + +--- + +## File References + +``` +@path/to/file.ts → Reference a file +@agent-name → Call an agent +!shell-command → Run shell command +``` + +| IDE | Shortcut | +|-----|----------| +| VS Code | `Alt+K` | +| JetBrains | `Cmd+Option+K` | + +--- + +## Permission Modes + +| Mode | Editing | Execution | +|------|---------|-----------| +| Default | Asks | Asks | +| Auto-accept | Auto | Asks | +| Plan Mode | ❌ | ❌ | + +**Shift+Tab** to switch modes + +--- + +## Configuration (2 levels) + +| Level | Location | Scope | Git | +|-------|----------|-------|-----| +| **Project** | `.claude/` | Team | ✅ | +| **Personal** | `~/.claude/` | You (all projects) | ❌ | + +**Priority**: Project overrides Personal + +| File | Where | Usage | +|------|-------|-------| +| `CLAUDE.md` | Project root | Team instructions | +| `settings.json` | `.claude/` | Team permissions | +| `settings.local.json` | `.claude/` | Your overrides | +| `CLAUDE.md` | `~/.claude/` | Personal instructions | + +--- + +## .claude/ Folder Structure + +``` +.claude/ +├── CLAUDE.md # Personal instructions +├── settings.json # Hooks (committed) +├── settings.local.json # Permissions (not committed) +├── agents/ # Custom agents +├── commands/ # Slash commands +├── hooks/ # Event scripts +├── rules/ # Auto-loaded rules +└── skills/ # Knowledge modules +``` + +--- + +## Typical Workflow + +``` +1. Start session → claude +2. Check context → /status +3. Plan Mode → Shift+Tab × 2 (for complex tasks) +4. Describe task → Clear, specific prompt +5. Review changes → Always read the diff! +6. Accept/Reject → y/n +7. Verify → Run tests +8. Commit → When task complete +9. /compact → When context >70% +``` + +--- + +## Context Management (CRITICAL) + +### Statusline + +``` +Model: Sonnet | Ctx: 89.5k | Cost: $2.11 | Ctx(u): 56.0% +``` +**Watch `Ctx(u):`** → >70% = `/compact`, >85% = `/clear` + +### Actions by Symptom + +| Sign | Action | +|------|--------| +| Short responses | `/compact` | +| Frequent forgetting | `/clear` | +| >70% context | `/compact` | +| Task complete | `/clear` | + +### Context Recovery Commands + +| Command | Usage | +|---------|-------| +| `/compact` | Summarize and free context | +| `/clear` | Fresh start | +| `/resume` | Resume previous session | +| `/rewind` | Undo recent changes | + +--- + +## Plan Mode & Think Levels + +| Feature | Activation | Usage | +|---------|------------|-------| +| **Plan Mode** | `Shift+Tab × 2` or `/plan` | Explore without modifying | +| **Think** | `--think` flag | Standard analysis (~4K tokens) | +| **Think Hard** | `--think-hard` flag | Deep analysis (~10K tokens) | +| **Ultrathink** | `--ultrathink` flag | Maximum depth (~32K tokens) | + +**Required for**: features >3 files, architecture, complex debugging + +--- + +## MCP Servers + +| Server | Purpose | +|--------|---------| +| **Serena** | Semantic code navigation | +| **Context7** | Library documentation | +| **Sequential** | Structured reasoning | +| **Playwright** | Browser automation | +| **Postgres** | Database queries | + +Check status: `/mcp` + +--- + +## Creating Custom Components + +### Agent (`.claude/agents/my-agent.md`) +```yaml +--- +name: my-agent +description: Use when [trigger] +model: sonnet +tools: Read, Write, Edit, Bash +--- +# Instructions here +``` + +### Command (`.claude/commands/my-command.md`) +```markdown +# Command Name +Instructions for what to do... +$ARGUMENTS - user provided args +``` + +### Hook (`.claude/hooks/my-hook.sh`) +```bash +#!/bin/bash +INPUT=$(cat) +# Process JSON input +exit 0 # 0=continue, 2=block +``` + +--- + +## Anti-patterns + +| ❌ Don't | ✅ Do | +|----------|-------| +| Vague prompts | Specify file + line | +| Accept without reading | Read every diff | +| Ignore warnings | Use `/compact` | +| Skip permissions | Never in production | +| Giant context loads | Load only what's needed | +| Negative constraints only | Provide alternatives | + +--- + +## Quick Prompting Formula + +``` +WHAT: [Concrete deliverable] +WHERE: [File paths] +HOW: [Constraints, approach] +VERIFY: [Success criteria] +``` + +**Example:** +``` +Add input validation to the login form. +WHERE: src/components/LoginForm.tsx +HOW: Use Zod schema, show inline errors +VERIFY: Empty email shows error, invalid format shows error +``` + +--- + +## Debug Commands + +```bash +claude --version # Version +claude doctor # Diagnostic +claude --debug # Verbose mode +claude --mcp-debug # Debug MCPs +/mcp # MCP status +``` + +--- + +## CI/CD Mode (Headless) + +```bash +# Non-interactive execution +claude -p "analyze this file" src/api.ts + +# JSON output +claude -p "review" --output-format json + +# Economic model +claude -p "lint" --model haiku + +# With auto-accept +claude -p "fix typos" --dangerously-skip-permissions +``` + +--- + +## The Golden Rules + +1. **Always review diffs** before accepting +2. **Use `/compact`** before context gets critical (>70%) +3. **Be specific** in requests (WHAT, WHERE, HOW, VERIFY) +4. **Plan Mode first** for complex/risky tasks +5. **Create CLAUDE.md** for every project +6. **Commit frequently** after each completed task + +--- + +## Quick Decision Tree + +``` +Simple task → Just ask Claude +Complex task → TodoWrite to plan first +Risky change → Plan Mode first +Repeating task → Create agent or command +Context full → /compact or /clear +Need docs → Use Context7 MCP +Deep analysis → Use --think or --ultrathink +``` + +--- + +## Resources + +- **Official docs**: [docs.anthropic.com/claude-code](https://docs.anthropic.com/en/docs/claude-code) +- **Inspired by**: [Claudelog.com](https://claudelog.com/) - Advanced tips & patterns +- **Full guide**: `english-ultimate-claude-code-guide.md` +- **Project config**: `CLAUDE.md` at project root + +--- + +**Author**: Florian BRUNIAUX | [@Méthode Aristote](https://methode-aristote.fr) | Written with Claude + +*Last updated: January 2025 | Version 1.0* diff --git a/claude-code-ultimate-guide_kimi.pdf b/claude-code-ultimate-guide_kimi.pdf new file mode 100644 index 0000000..a3f1aaf Binary files /dev/null and b/claude-code-ultimate-guide_kimi.pdf differ diff --git a/claude-code-ultimate-guide_notebooklm.pdf b/claude-code-ultimate-guide_notebooklm.pdf new file mode 100644 index 0000000..5e75734 Binary files /dev/null and b/claude-code-ultimate-guide_notebooklm.pdf differ diff --git a/english-ultimate-claude-code-guide.md b/english-ultimate-claude-code-guide.md new file mode 100644 index 0000000..1900202 --- /dev/null +++ b/english-ultimate-claude-code-guide.md @@ -0,0 +1,4365 @@ +# The Ultimate Claude Code Guide + +> A comprehensive, self-contained guide to mastering Claude Code - from zero to power user. + +**Author**: Florian BRUNIAUX | Founding Engineer [@Méthode Aristote](https://methode-aristote.fr) + +**Written with**: Claude (Anthropic) + +**Reading time**: ~2.5 hours (full) | ~15 minutes (Quick Start only) + +**Last updated**: January 2025 + +**Version**: 1.0 + +--- + +## TL;DR - The 5-Minute Summary + +If you only have 5 minutes, here's what you need to know: + +### Essential Commands +```bash +claude # Start Claude Code +/help # Show all commands +/status # Check context usage +/compact # Compress context when >70% +/clear # Fresh start +/plan # Safe read-only mode +Ctrl+C # Cancel operation +``` + +### The Workflow +``` +Describe → Claude Analyzes → Review Diff → Accept/Reject → Verify +``` + +### Context Management (Critical!) +| Context % | Action | +|-----------|--------| +| 0-50% | Work freely | +| 50-70% | Be selective | +| 70-90% | `/compact` now | +| 90%+ | `/clear` required | + +### Configuration Priority +``` +~/.claude/CLAUDE.md → Global (all projects) +/project/CLAUDE.md → Project (committed) +/project/.claude/ → Personal (not committed) +``` + +### Power Features +| Feature | What It Does | +|---------|--------------| +| **Agents** | Specialized AI personas for specific tasks | +| **Skills** | Reusable knowledge modules | +| **Hooks** | Automation scripts triggered by events | +| **MCP Servers** | External tools (Serena, Context7, Playwright...) | + +### The Golden Rules +1. **Always review diffs** before accepting changes +2. **Use `/compact`** before context gets critical +3. **Be specific** in your requests (WHAT, WHERE, HOW, VERIFY) +4. **Start with Plan Mode** for complex/risky tasks +5. **Create CLAUDE.md** for every project + +### Quick Decision Tree +``` +Simple task → Just ask Claude +Complex task → Use TodoWrite to plan +Risky change → Enter Plan Mode first +Repeating task → Create an agent or command +Context full → /compact or /clear +``` + +**Now read Section 1 for the full Quick Start, or jump to any section you need.** + +--- + +## Table of Contents + +- [1. Quick Start (Day 1)](#1-quick-start-day-1) + - [1.1 Installation](#11-installation) + - [1.2 First Workflow](#12-first-workflow) + - [1.3 Essential Commands](#13-essential-commands) + - [1.4 Permission Modes](#14-permission-modes) + - [1.5 Productivity Checklist](#15-productivity-checklist) +- [2. Core Concepts](#2-core-concepts) + - [2.1 The Interaction Loop](#21-the-interaction-loop) + - [2.2 Context Management](#22-context-management) + - [2.3 Plan Mode](#23-plan-mode) + - [2.4 Rewind](#24-rewind) + - [2.5 Mental Model](#25-mental-model) +- [3. Configuration](#3-configuration) + - [3.1 CLAUDE.md Files](#31-claudemd-files) + - [3.2 The .claude/ Folder](#32-the-claude-folder) + - [3.3 Settings & Permissions](#33-settings--permissions) + - [3.4 Precedence Rules](#34-precedence-rules) +- [4. Agents](#4-agents) + - [4.1 What Are Agents](#41-what-are-agents) + - [4.2 Creating Custom Agents](#42-creating-custom-agents) + - [4.3 Agent Template](#43-agent-template) + - [4.4 Best Practices](#44-best-practices) + - [4.5 Agent Examples](#45-agent-examples) +- [5. Skills](#5-skills) + - [5.1 Understanding Skills](#51-understanding-skills) + - [5.2 Creating Skills](#52-creating-skills) + - [5.3 Skill Template](#53-skill-template) + - [5.4 Skill Examples](#54-skill-examples) +- [6. Commands](#6-commands) + - [6.1 Slash Commands](#61-slash-commands) + - [6.2 Creating Custom Commands](#62-creating-custom-commands) + - [6.3 Command Template](#63-command-template) + - [6.4 Command Examples](#64-command-examples) +- [7. Hooks](#7-hooks) + - [7.1 The Event System](#71-the-event-system) + - [7.2 Creating Hooks](#72-creating-hooks) + - [7.3 Hook Templates](#73-hook-templates) + - [7.4 Security Hooks](#74-security-hooks) + - [7.5 Hook Examples](#75-hook-examples) +- [8. MCP Servers](#8-mcp-servers) + - [8.1 What is MCP](#81-what-is-mcp) + - [8.2 Available Servers](#82-available-servers) + - [8.3 Configuration](#83-configuration) + - [8.4 Server Selection Guide](#84-server-selection-guide) +- [9. Advanced Patterns](#9-advanced-patterns) + - [9.1 The Trinity](#91-the-trinity) + - [9.2 Composition Patterns](#92-composition-patterns) + - [9.3 CI/CD Integration](#93-cicd-integration) + - [9.4 IDE Integration](#94-ide-integration) + - [9.5 Tight Feedback Loops](#95-tight-feedback-loops) + - [9.6 Todo as Instruction Mirrors](#96-todo-as-instruction-mirrors) + - [9.7 Output Styles](#97-output-styles) + - [9.8 Vibe Coding & Skeleton Projects](#98-vibe-coding--skeleton-projects) + - [9.9 Batch Operations Pattern](#99-batch-operations-pattern) +- [10. Reference](#10-reference) + - [10.1 Commands Table](#101-commands-table) + - [10.2 Keyboard Shortcuts](#102-keyboard-shortcuts) + - [10.3 Configuration Reference](#103-configuration-reference) + - [10.4 Troubleshooting](#104-troubleshooting) + - [10.5 Cheatsheet](#105-cheatsheet) + - [10.6 Daily Workflow & Checklists](#106-daily-workflow--checklists) +- [Appendix: Templates Collection](#appendix-templates-collection) + - [A.8 Prompt Templates](#a8-prompt-templates) + - [A.9 Success Metrics & Maturity Model](#a9-success-metrics--maturity-model) + +--- + +# 1. Quick Start (Day 1) + +**Reading time**: 15 minutes + +**Skill level**: Beginner + +**Goal**: Go from zero to productive + +## 1.1 Installation + +Choose your preferred installation method: + +### Option A: Shell Script (Recommended) + +```bash +curl -fsSL https://claude.ai/install.sh | sh +``` + +### Option B: npm + +```bash +npm install -g @anthropic-ai/claude-code +``` + +### Option C: Homebrew (macOS) + +```bash +brew install claude-code +``` + +### Verify Installation + +```bash +claude --version +``` + +### First Launch + +```bash +cd your-project +claude +``` + +On first launch: + +1. You'll be prompted to authenticate with your Anthropic account +2. Accept the terms of service +3. Claude Code will index your project (may take a few seconds for large codebases) + +## 1.2 First Workflow + +Let's fix a bug together. This demonstrates the core interaction loop. + +### Step 1: Describe the Problem + +``` +You: There's a bug in the login function - users can't log in with email addresses containing a plus sign +``` + +### Step 2: Claude Analyzes + +Claude will: +- Search your codebase for relevant files +- Read the login-related code +- Identify the issue +- Propose a fix + +### Step 3: Review the Diff + +```diff +- const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; ++ const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; +``` + +💡 **Critical**: Always read the diff before accepting. This is your safety net. + +### Step 4: Accept or Reject + +- Press `y` to accept the change +- Press `n` to reject and ask for alternatives +- Press `e` to edit the change manually + +### Step 5: Verify + +``` +You: Run the tests to make sure this works +``` + +Claude will run your test suite and report results. + +### Step 6: Commit (Optional) + +``` +You: Commit this fix +``` + +Claude will create a commit with an appropriate message. + +## 1.3 Essential Commands + +These 7 commands cover 90% of daily usage: + +| Command | Action | When to Use | +|---------|--------|-------------| +| `/help` | Show all commands | When you're lost | +| `/clear` | Clear conversation | Start fresh | +| `/compact` | Summarize context | Running low on context | +| `/status` | Show session info | Check context usage | +| `/exit` or `Ctrl+D` | Exit Claude Code | Done working | +| `/plan` | Enter Plan Mode | Safe exploration | +| `/rewind` | Undo changes | Made a mistake | + +### Quick Actions + +| Shortcut | Action | +|----------|--------| +| `!command` | Run shell command directly | +| `@file.ts` | Reference a specific file | +| `Ctrl+C` | Cancel current operation | +| `Ctrl+R` | Retry last operation | +| `Esc` | Dismiss current suggestion | + +## 1.4 Permission Modes + +Claude Code has three permission modes that control how much autonomy Claude has: + +### Default Mode + +Claude asks permission before: +- Editing files +- Running commands +- Making commits + +This is the safest mode for learning. + +### Auto-accept Mode + +``` +You: Turn on auto-accept for the rest of this session +``` + +Claude will execute changes without asking. Use when you trust the operation and want speed. + +⚠️ **Warning**: Only use auto-accept for well-defined, reversible operations. + +### Plan Mode + +``` +/plan +``` + +Claude can only read and analyze - no modifications allowed. Perfect for: +- Understanding unfamiliar code +- Exploring architectural options +- Safe investigation before changes + +Exit with `/execute` when ready to make changes. + +## 1.5 Productivity Checklist + +You're ready for Day 2 when you can: + +- [ ] Launch Claude Code in your project +- [ ] Describe a task and review the proposed changes +- [ ] Accept or reject changes after reading the diff +- [ ] Run a shell command with `!` +- [ ] Reference a file with `@` +- [ ] Use `/clear` to start fresh +- [ ] Use `/status` to check context usage +- [ ] Exit cleanly with `/exit` or `Ctrl+D` + +--- + +# 2. Core Concepts + +**Reading time**: 20 minutes + +**Skill level**: Day 1-3 + +**Goal**: Understand how Claude Code thinks + +## 2.1 The Interaction Loop + +Every Claude Code interaction follows this pattern: + +``` +┌─────────────────────────────────────────────────────────┐ +│ INTERACTION LOOP │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ 1. DESCRIBE ──→ You explain what you need │ +│ │ │ +│ ▼ │ +│ 2. ANALYZE ──→ Claude explores the codebas │ +│ │ │ +│ ▼ │ +│ 3. PROPOSE ──→ Claude suggests changes (diff) │ +│ │ │ +│ ▼ │ +│ 4. REVIEW ──→ You read and evaluate │ +│ │ │ +│ ▼ │ +│ 5. DECIDE ──→ Accept / Reject / Modify │ +│ │ │ +│ ▼ │ +│ 6. VERIFY ──→ Run tests, check behavior │ +│ │ │ +│ ▼ │ +│ 7. COMMIT ──→ Save changes (optional) │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +### Key Insight + +The loop is designed so that **you remain in control**. Claude proposes, you decide. + +## 2.2 Context Management + +🔴 **This is the most important concept in Claude Code.** + +### What is Context? + +Context is Claude's "working memory" for your conversation. It includes: +- All messages in the conversation +- Files Claude has read +- Command outputs +- Tool results + +### The Context Budget + +Claude has a **200,000 token** context window. Think of it like RAM - when it fills up, things slow down or fail. + +### Reading the Statusline + +The statusline shows your context usage: + +``` +Claude Code │ Ctx(u): 45% │ Cost: $0.23 │ Session: 1h 23m +``` + +| Metric | Meaning | +|--------|---------| +| `Ctx(u): 45%` | You've used 45% of context | +| `Cost: $0.23` | API cost so far | +| `Session: 1h 23m` | Time elapsed | + +### Context Zones + +| Zone | Usage | Action | +|------|-------|--------| +| 🟢 Green | 0-50% | Work freely | +| 🟡 Yellow | 50-75% | Start being selective | +| 🔴 Red | 75-90% | Use `/compact` or `/clear` | +| ⚫ Critical | 90%+ | Must clear or risk errors | + +### Context Recovery Strategies + +When context gets high: + +**Option 1: Compact** (`/compact`) +- Summarizes the conversation +- Preserves key context +- Reduces usage by ~50% + +**Option 2: Clear** (`/clear`) +- Starts fresh +- Loses all context +- Use when changing topics + +**Option 3: Targeted Approach** +- Be specific in queries +- Avoid "read the entire file" +- Use symbol references: "read the `calculateTotal` function" + +### What Consumes Context? + +| Action | Context Cost | +|--------|--------------| +| Reading a small file | Low (~500 tokens) | +| Reading a large file | High (~5K+ tokens) | +| Running commands | Medium (~1K tokens) | +| Multi-file search | High (~3K+ tokens) | +| Long conversations | Accumulates | + +### Context Depletion Symptoms + +Learn to recognize when context is running out: + +| Symptom | Severity | Action | +|---------|----------|--------| +| Shorter responses than usual | 🟡 Warning | Continue with caution | +| Forgetting CLAUDE.md instructions | 🟠 Serious | Document state, prepare checkpoint | +| Inconsistencies with earlier conversation | 🔴 Critical | New session needed | +| Errors on code already discussed | 🔴 Critical | New session needed | +| "I can't access that file" (when it was read) | 🔴 Critical | New session immediately | + +### Context Inspection + +Check your context usage in detail: + +``` +/context +``` + +Example output: +``` +┌─────────────────────────────────────────────────────────────┐ +│ CONTEXT USAGE 67% used │ +├─────────────────────────────────────────────────────────────┤ +│ System Prompt ████████░░░░░░░░░░░░░░░░ 12,450 tk │ +│ System Tools ██░░░░░░░░░░░░░░░░░░░░░░ 3,200 tk │ +│ MCP Tools (5 servers) ████████████░░░░░░░░░░░░ 18,600 tk │ +│ Conversation ████████████████████░░░░ 89,200 tk │ +├─────────────────────────────────────────────────────────────┤ +│ TOTAL 123,450 tk │ +│ REMAINING 76,550 tk │ +└─────────────────────────────────────────────────────────────┘ +``` + +💡 **The Last 20% Rule**: Reserve ~20% of context for: +- Multi-file operations at end of session +- Last-minute corrections +- Generating summary/checkpoint + +### Context Poisoning (Bleeding) + +**Definition**: When information from one task contaminates another. + +**Pattern 1: Style Bleeding** +``` +Task 1: "Create a blue button" +Claude: [Creates blue button] + +Task 2: "Create a form" +Claude: [Creates form... with all buttons blue!] + ↑ The "blue" bled into the new task + +Solution: Use explicit boundaries +"---NEW TASK--- +Create a form. Use default design system colors." +``` + +**Pattern 2: Instruction Contamination** +``` +Instruction 1: "Always use arrow functions" +Instruction 2: "Follow project conventions" (which uses function) + +Claude: [Paralyzed, alternating between styles] + +Solution: Clarify priority +"In case of conflict, project conventions take precedence over my preferences." +``` + +**Pattern 3: Temporal Confusion** +``` +Early session: "auth.ts contains login logic" +... 2h of work ... +You renamed auth.ts to authentication.ts + +Claude: "I'll modify auth.ts..." + ↑ Using outdated info + +Solution: Explicit updates +"Note: auth.ts was renamed to authentication.ts" +``` + +**Context Hygiene Checklist**: +- [ ] New tasks = explicit markdown boundaries +- [ ] Structural changes = inform Claude explicitly +- [ ] Contradictory instructions = clarify priority +- [ ] Long session (>2h) = consider `/clear` or new session +- [ ] Erratic behavior = check with `/context` + +### Sanity Check Technique + +Verify that Claude has loaded your configuration correctly. + +**Simple Method**: + +1. Add at the top of CLAUDE.md: +```markdown +# My name is [Your Name] +# Project: [Project Name] +# Stack: [Your tech stack] +``` + +2. Ask Claude: "What is my name? What project am I working on?" + +3. If correct → Configuration loaded properly + +**Advanced: Multiple Checkpoints** +```markdown +# === CHECKPOINT 1 === Project: MyApp === + +[... 500 lines of instructions ...] + +# === CHECKPOINT 2 === Stack: Next.js === + +[... 500 lines of instructions ...] + +# === CHECKPOINT 3 === Owner: [Name] === +``` + +Ask "What is checkpoint 2?" to verify Claude read that far. + +| Failure Symptom | Probable Cause | Solution | +|-----------------|----------------|----------| +| Doesn't know your name | CLAUDE.md not loaded | Check file location | +| Inconsistent answers | Typo in filename | Must be `CLAUDE.md` (not `clause.md`) | +| Partial knowledge | Context exhausted | `/clear` or new session | + +## 2.3 Plan Mode + +Plan Mode is Claude Code's "look but don't touch" mode. + +### Entering Plan Mode + +``` +/plan +``` + +Or ask Claude directly: + +``` +You: Let's plan this feature before implementing +``` + +### What Plan Mode Allows + +- ✅ Reading files +- ✅ Searching the codebase +- ✅ Analyzing architecture +- ✅ Proposing approaches +- ✅ Writing to a plan file + +### What Plan Mode Prevents + +- ❌ Editing files +- ❌ Running commands that modify state +- ❌ Creating new files +- ❌ Making commits + +### When to Use Plan Mode + +| Situation | Use Plan Mode? | +|-----------|----------------| +| Exploring unfamiliar codebase | ✅ Yes | +| Investigating a bug | ✅ Yes | +| Planning a new feature | ✅ Yes | +| Fixing a typo | ❌ No | +| Quick edit to known file | ❌ No | + +### Exiting Plan Mode + +``` +/execute +``` + +Or Claude will ask: "Ready to implement this plan?" + +### Auto Plan Mode + +**Concept**: Automatically trigger planning mode before any risky operation. + +**Configuration File** (`~/.claude/auto-plan-mode.txt`): +``` +Before executing ANY tool (Read, Write, Edit, Bash, Grep, Glob, WebSearch), you MUST: +1. FIRST: Use exit_plan_mode tool to present your plan +2. WAIT: For explicit user approval before proceeding +3. ONLY THEN: Execute the planned actions + +Each new user request requires a fresh plan - previous approvals don't carry over. +``` + +**Launch with Auto Plan Mode**: +```bash +# Direct +claude --append-system-prompt "Before executing ANY tool..." + +# Via file (recommended) +claude --append-system-prompt "$(cat ~/.claude/auto-plan-mode.txt)" + +# Alias in .zshrc/.bashrc +alias claude-safe='claude --append-system-prompt "$(cat ~/.claude/auto-plan-mode.txt)"' +``` + +**Resulting Workflow**: +``` +User: "Add an email field to the User model" + +Claude (Auto Plan Mode active): +┌─────────────────────────────────────────────────────────────┐ +│ 📋 PROPOSED PLAN │ +│ │ +│ 1. Read schema.prisma to understand current model │ +│ 2. Add field email: String? @unique │ +│ 3. Generate Prisma migration │ +│ 4. Update TypeScript types │ +│ 5. Add Zod validation in routers │ +│ │ +│ ⚠️ Impact: 3 files modified, 1 migration created │ +│ │ +│ Approve this plan? (y/n) │ +└─────────────────────────────────────────────────────────────┘ + +User: "y" + +Claude: [Executes the plan] +``` + +**Result**: 76% fewer tokens with better results because the plan is validated before execution. + +## 2.4 Rewind + +Rewind is Claude Code's undo mechanism. + +### Using Rewind + +``` +/rewind +``` + +Or: + +``` +You: Undo the last change +``` + +### What Rewind Does + +- Reverts file changes +- Restores previous state +- Works across multiple files + +### Limitations + +- Only works on Claude's changes (not manual edits) +- Works within the current session +- Git commits are NOT automatically reverted + +### Best Practice: Checkpoint Before Risk + +Before a risky operation: + +``` +You: Let's commit what we have before trying this experimental approach +``` + +This creates a git checkpoint you can always return to. + +## 2.5 Mental Model + +Understanding how Claude Code "thinks" makes you more effective. + +### Claude's View of Your Project + +``` +┌─────────────────────────────────────────────────────────┐ +│ YOUR PROJECT │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ +│ │ Files │ │ Git │ │ Config │ │ +│ │ (.ts,.py) │ │ History │ │ Files │ │ +│ └─────────────┘ └─────────────┘ └───────────┘ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────────────────────────────────────────────┐ │ +│ │ Claude's Understanding │ │ +│ │ - File structure & relationships │ │ +│ │ - Code patterns & conventions │ │ +│ │ - Recent changes (from git) │ │ +│ │ - Project rules (from CLAUDE.md) │ │ +│ └─────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +### What Claude Knows + +1. **File Structure**: Claude can navigate and search your files +2. **Code Content**: Claude can read and understand code +3. **Git State**: Claude sees branches, commits, changes +4. **Project Rules**: Claude reads CLAUDE.md for conventions + +### What Claude Doesn't Know + +1. **Runtime State**: Claude can't see running processes +2. **External Services**: Claude can't access your databases directly +3. **Your Intent**: Claude needs clear instructions +4. **Hidden Files**: Claude respects .gitignore by default + +### Communicating Effectively + +**Good prompt**: +``` +The login function in src/auth/login.ts isn't validating email addresses properly. +Plus signs should be allowed but they're being rejected. +``` + +**Weak prompt**: +``` +Login is broken +``` + +The more context you provide, the better Claude can help. + +--- + +# 3. Configuration + +**Reading time**: 15 minutes +**Skill level**: Week 1 +**Goal**: Customize Claude Code for your project + +## 3.1 CLAUDE.md Files + +CLAUDE.md files are persistent instructions that Claude reads at the start of every session. + +### Three Levels of Configuration + +``` +┌─────────────────────────────────────────────────────────┐ +│ CONFIGURATION HIERARCHY │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ ~/.claude/CLAUDE.md (Global - All projects) │ +│ │ │ +│ ▼ │ +│ /project/CLAUDE.md (Project - This repo) │ +│ │ │ +│ ▼ │ +│ /project/.claude/CLAUDE.md (Local - Personal prefs) │ +│ │ +│ Priority: Local > Project > Global │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +### Level 1: Global (~/.claude/CLAUDE.md) + +Personal preferences that apply to all your projects: + +```markdown +# Global Claude Code Settings + +## Communication Style +- Be concise in responses +- Use code examples over explanations +- Ask clarifying questions before major changes + +## Preferred Tools +- Use TypeScript over JavaScript +- Prefer pnpm over npm +- Use Prettier for formatting + +## Safety Rules +- Always run tests before committing +- Never force push to main +- Check for secrets before committing +``` + +### Level 2: Project (/project/CLAUDE.md) + +Shared team conventions checked into version control: + +```markdown +# Project: MyApp + +## Tech Stack +- Next.js 14 with App Router +- TypeScript 5.3 +- PostgreSQL with Prisma +- TailwindCSS + +## Code Conventions +- Use functional components +- Use `const` arrow functions +- File naming: kebab-case (my-component.tsx) + +## Architecture +- API routes in /app/api +- Components in /components +- Database queries in /lib/db + +## Commands +- `pnpm dev` - Start development +- `pnpm test` - Run tests +- `pnpm lint` - Check linting +``` + +### Level 3: Local (/project/.claude/CLAUDE.md) + +Personal overrides not committed to git (add to .gitignore): + +```markdown +# My Local Preferences + +## Overrides +- Skip pre-commit hooks for quick iterations +- Use verbose logging during debugging +``` + +### CLAUDE.md Best Practices + +| Do | Don't | +|-----|-------| +| Keep it concise | Write essays | +| Include examples | Be vague | +| Update when conventions change | Let it go stale | +| Reference external docs | Duplicate documentation | + +## 3.2 The .claude/ Folder + +The `.claude/` folder is your project's Claude Code configuration directory. + +### Full Structure + +``` +.claude/ +├── CLAUDE.md # Local instructions (gitignored) +├── settings.json # Hook configuration +├── settings.local.json # Personal permissions (gitignored) +├── agents/ # Custom agent definitions +│ ├── README.md +│ ├── backend-architect.md +│ ├── code-reviewer.md +│ └── ... +├── commands/ # Custom slash commands +│ ├── tech/ +│ │ ├── commit.md +│ │ └── pr.md +│ ├── product/ +│ │ └── problem-framer.md +│ └── support/ +│ └── support-assistant.md +├── hooks/ # Event-driven scripts +│ ├── README.md +│ ├── auto-format.sh +│ └── git-context.sh +├── rules/ # Auto-loaded conventions +│ ├── code-conventions.md +│ └── git-workflow.md +├── skills/ # Knowledge modules +│ ├── README.md +│ └── security-guardian/ +│ ├── SKILL.md +│ └── checklists/ +└── plans/ # Saved plan files +``` + +### What Goes Where + +| Content Type | Location | Shared? | +|--------------|----------|---------| +| Team conventions | `rules/` | ✅ Commit | +| Reusable agents | `agents/` | ✅ Commit | +| Team commands | `commands/` | ✅ Commit | +| Automation hooks | `hooks/` | ✅ Commit | +| Knowledge modules | `skills/` | ✅ Commit | +| Personal preferences | `CLAUDE.md` | ❌ Gitignore | +| Personal permissions | `settings.local.json` | ❌ Gitignore | + +## 3.3 Settings & Permissions + +### settings.json (Team Configuration) + +This file configures hooks and is committed to the repo: + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash|Edit|Write", + "hooks": [ + { + "type": "command", + "command": ".claude/hooks/security-check.sh", + "timeout": 5000 + } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { + "type": "command", + "command": ".claude/hooks/auto-format.sh" + } + ] + } + ], + "UserPromptSubmit": [ + { + "matcher": "", + "hooks": [ + { + "type": "command", + "command": ".claude/hooks/git-context.sh" + } + ] + } + ] + } +} +``` + +### settings.local.json (Personal Permissions) + +Personal permission overrides (gitignored): + +```json +{ + "permissions": { + "allow": [ + "Bash(git *)", + "Bash(pnpm *)", + "Bash(npm test)", + "Edit", + "Write", + "WebSearch" + ], + "deny": [ + "Bash(rm -rf *)", + "Bash(sudo *)" + ], + "ask": [ + "Bash(npm publish)", + "Bash(git push --force)" + ] + } +} +``` + +### Permission Patterns + +| Pattern | Matches | +|---------|---------| +| `Bash(git *)` | Any git command | +| `Bash(pnpm *)` | Any pnpm command | +| `Edit` | All file edits | +| `Write` | All file writes | +| `WebSearch` | Web search capability | +| `mcp__serena__*` | All Serena MCP tools | + +### Permission Behavior + +| Category | Behavior | +|----------|----------| +| `allow` | Auto-approve without asking | +| `deny` | Block completely | +| `ask` | Prompt for confirmation | +| (default) | Use default permission mode | + +### allowedTools Configuration (Alternative) + +For granular control, use `~/.claude.json`: + +```json +{ + "allowedTools": [ + "Read(*)", + "Grep(*)", + "Glob(*)", + "WebFetch(*)", + "TodoRead", + "TodoWrite", + "Task(*)", + "Bash(git status:*)", + "Bash(git diff:*)", + "Bash(git log:*)", + "Bash(pnpm typecheck:*)", + "Bash(pnpm lint:*)", + "Bash(pnpm test:*)" + ] +} +``` + +**Pattern Logic**: +| Pattern | Meaning | Example | +|---------|---------|---------| +| `Read(*)` | All reads | Any file | +| `Bash(git status:*)` | Specific command | `git status` allowed | +| `Bash(pnpm *:*)` | Command prefix | `pnpm test`, `pnpm build` | +| `Edit(*)` | All edits | ⚠️ Dangerous | + +**Progressive Permission Levels**: + +**Level 1 - Beginner (very restrictive)**: +```json +{ + "allowedTools": ["Read(*)", "Grep(*)", "Glob(*)"] +} +``` + +**Level 2 - Intermediate**: +```json +{ + "allowedTools": [ + "Read(*)", "Grep(*)", "Glob(*)", + "Bash(git:*)", "Bash(pnpm:*)", + "TodoRead", "TodoWrite" + ] +} +``` + +**Level 3 - Advanced**: +```json +{ + "allowedTools": [ + "Read(*)", "Grep(*)", "Glob(*)", "WebFetch(*)", + "Edit(*)", "Write(*)", + "Bash(git:*)", "Bash(pnpm:*)", "Bash(npm:*)", + "Task(*)", "TodoRead", "TodoWrite" + ] +} +``` + +⚠️ **Never use `--dangerously-skip-permissions`** + +Horror stories from r/ClaudeAI include: +- `rm -rf node_modules` followed by `rm -rf .` (path error) +- `git push --force` to main unintentionally +- `DROP TABLE users` in a poorly generated migration +- Deletion of `.env` files with credentials + +**Always prefer granular `allowedTools` over disabling permissions entirely.** + +### Dynamic Memory (Profile Switching) + +**Concept**: Temporarily modify CLAUDE.md for specific tasks, then restore. + +**Technique 1: Git Stash** +```bash +# Before modification +git stash push -m "CLAUDE.md original" CLAUDE.md + +# Claude modifies CLAUDE.md for specific task +# ... work ... + +# After task +git stash pop +``` + +**Technique 2: Profile Library** +``` +~/.claude/profiles/ +├── default.md # General config +├── security-audit.md # For security audits +├── refactoring.md # For major refactoring +├── documentation.md # For writing docs +└── debugging.md # For debug sessions +``` + +**Profile Switch Script**: +```bash +#!/bin/bash +# ~/.local/bin/claude-profile + +PROFILE=$1 +cp ~/.claude/profiles/${PROFILE}.md ./CLAUDE.md +echo "Switched to profile: $PROFILE" +``` + +Usage: +```bash +claude-profile security-audit +claude # Launches with security profile +``` + +**Technique 3: Parallel Instances** +```bash +# Terminal 1: Main project +cd ~/projects/myapp +claude # Loads myapp's CLAUDE.md + +# Terminal 2: Worktree for isolated feature +cd ~/projects/myapp-feature-x +# Different CLAUDE.md, isolated context +claude +``` + +## 3.4 Precedence Rules + +When configurations conflict, Claude Code uses this precedence: + +### Configuration Precedence + +``` +Highest Priority + │ + ▼ +┌──────────────────────────────────┐ +│ settings.local.json │ Personal overrides +└──────────────────────────────────┘ + │ + ▼ +┌──────────────────────────────────┐ +│ settings.json │ Project settings +└──────────────────────────────────┘ + │ + ▼ +┌──────────────────────────────────┐ +│ ~/.claude/settings.json │ Global defaults +└──────────────────────────────────┘ + │ + ▼ +Lowest Priority +``` + +### CLAUDE.md Precedence + +``` +Highest Priority + │ + ▼ +┌──────────────────────────────────┐ +│ .claude/CLAUDE.md │ Local (personal) +└──────────────────────────────────┘ + │ + ▼ +┌──────────────────────────────────┐ +│ /project/CLAUDE.md │ Project (team) +└──────────────────────────────────┘ + │ + ▼ +┌──────────────────────────────────┐ +│ ~/.claude/CLAUDE.md │ Global (personal) +└──────────────────────────────────┘ + │ + ▼ +Lowest Priority +``` + +### Rules Auto-Loading + +Files in `.claude/rules/` are automatically loaded and combined: + +``` +.claude/rules/ +├── code-conventions.md ──┐ +├── git-workflow.md ──┼──→ All loaded automatically +└── architecture.md ──┘ +``` + +--- + +# 4. Agents + +**Reading time**: 20 minutes +**Skill level**: Week 1-2 +**Goal**: Create specialized AI assistants + +## 4.1 What Are Agents + +Agents are specialized sub-processes that Claude can delegate tasks to. + +### Why Use Agents? + +| Without Agents | With Agents | +|----------------|-------------| +| One Claude doing everything | Specialized experts for each domain | +| Context gets cluttered | Each agent has focused context | +| Generic responses | Domain-specific expertise | +| Manual tool selection | Pre-configured tool access | + +### Agent vs Direct Prompt + +``` +Direct Prompt: +You: Review this code for security issues, focusing on OWASP Top 10, + checking for SQL injection, XSS, CSRF, and authentication vulnerabilities... + +With Agent: +You: Use the security-reviewer agent to audit this code +``` + +The agent encapsulates all that expertise. + +### Built-in vs Custom Agents + +| Type | Source | Example | +|------|--------|---------| +| Built-in | Claude Code default | Explore, Plan | +| Custom | Your `.claude/agents/` | Backend architect, Code reviewer | + +## 4.2 Creating Custom Agents + +Agents are markdown files in `.claude/agents/` with YAML frontmatter. + +### Agent File Structure + +```markdown +--- +name: agent-name +description: Clear activation trigger (50-100 chars) +model: sonnet +tools: Read, Write, Edit, Bash, Grep, Glob +skills: + - skill-name +disallowedTools: + - WebSearch +--- + +[Markdown instructions for the agent] +``` + +### Frontmatter Fields + +| Field | Required | Description | +|-------|----------|-------------| +| `name` | ✅ | Kebab-case identifier | +| `description` | ✅ | When to activate this agent | +| `model` | ❌ | `sonnet` (default), `opus`, or `haiku` | +| `tools` | ❌ | Allowed tools (comma-separated) | +| `skills` | ❌ | Skills to inherit | +| `disallowedTools` | ❌ | Tools to block | + +### Model Selection + +| Model | Best For | Speed | Cost | +|-------|----------|-------|------| +| `haiku` | Quick tasks, simple changes | Fast | Low | +| `sonnet` | Most tasks (default) | Balanced | Medium | +| `opus` | Complex reasoning, architecture | Slow | High | + +## 4.3 Agent Template + +Copy this template to create your own agent: + +```markdown +--- +name: your-agent-name +description: Use this agent when [specific trigger description] +model: sonnet +tools: Read, Write, Edit, Bash, Grep, Glob +skills: [] +--- + +# Your Agent Name + +## Role Definition + +You are an expert in [domain]. Your responsibilities include: +- [Responsibility 1] +- [Responsibility 2] +- [Responsibility 3] + +## Activation Triggers + +Use this agent when: +- [Trigger 1] +- [Trigger 2] +- [Trigger 3] + +## Methodology + +When given a task, you should: +1. [Step 1] +2. [Step 2] +3. [Step 3] +4. [Step 4] + +## Output Format + +Your deliverables should include: +- [Output 1] +- [Output 2] + +## Constraints + +- [Constraint 1] +- [Constraint 2] + +## Examples + +### Example 1: [Scenario Name] + +**User**: [Example prompt] + +**Your approach**: +1. [What you do first] +2. [What you do next] +3. [Final output] +``` + +## 4.4 Best Practices + +### Do's and Don'ts + +| ✅ Do | ❌ Don't | +|-------|----------| +| Make agents specialists | Create generalist agents | +| Define clear triggers | Use vague descriptions | +| Include concrete examples | Leave activation ambiguous | +| Limit tool access | Give all tools to all agents | +| Compose via skills | Duplicate expertise | + +### Specialization Over Generalization + +**Good**: An agent for each concern +``` +backend-architect → API design, database, performance +security-reviewer → OWASP, auth, encryption +test-engineer → Test strategy, coverage, TDD +``` + +**Bad**: One agent for everything +``` +full-stack-expert → Does everything (poorly) +``` + +### Explicit Activation Triggers + +**Good description**: +```yaml +description: Use when designing APIs, reviewing database schemas, or optimizing backend performance +``` + +**Bad description**: +```yaml +description: Backend stuff +``` + +### Skill Composition + +Instead of duplicating knowledge: + +```yaml +# security-reviewer.md +skills: + - security-guardian # Inherits OWASP knowledge +``` + +## 4.5 Agent Examples + +### Example 1: Code Reviewer Agent + +```markdown +--- +name: code-reviewer +description: Use for code quality reviews, security audits, and performance analysis +model: sonnet +tools: Read, Grep, Glob +skills: + - security-guardian +--- + +# Code Reviewer + +## Role Definition + +You are a senior code reviewer with expertise in: +- Code quality and maintainability +- Security best practices (OWASP Top 10) +- Performance optimization +- Test coverage analysis + +## Activation Triggers + +Use this agent when: +- Completing a feature before PR +- Reviewing someone else's code +- Auditing security-sensitive code +- Analyzing performance bottlenecks + +## Methodology + +1. **Understand Context**: Read the code and understand its purpose +2. **Check Quality**: Evaluate readability, maintainability, DRY principles +3. **Security Scan**: Look for OWASP Top 10 vulnerabilities +4. **Performance Review**: Identify potential bottlenecks +5. **Provide Feedback**: Structured report with severity levels + +## Output Format + +### Code Review Report + +**Summary**: [1-2 sentence overview] + +**Critical Issues** (Must Fix): +- [Issue with file:line reference] + +**Warnings** (Should Fix): +- [Issue with file:line reference] + +**Suggestions** (Nice to Have): +- [Improvement opportunity] + +**Positive Notes**: +- [What was done well] +``` + +### Example 2: Debugger Agent + +```markdown +--- +name: debugger +description: Use when encountering errors, test failures, or unexpected behavior +model: sonnet +tools: Read, Bash, Grep, Glob +--- + +# Debugger + +## Role Definition + +You are a systematic debugger who: +- Investigates root causes, not symptoms +- Uses evidence-based debugging +- Never guesses - always verifies + +## Methodology + +1. **Reproduce**: Confirm the issue exists +2. **Isolate**: Narrow down to smallest reproducible case +3. **Analyze**: Read code, check logs, trace execution +4. **Hypothesize**: Form theories about the cause +5. **Test**: Verify hypothesis with minimal changes +6. **Fix**: Implement the solution +7. **Verify**: Confirm fix works and doesn't break other things + +## Output Format + +### Debug Report + +**Issue**: [Description] +**Root Cause**: [What's actually wrong] +**Evidence**: [How you know] +**Fix**: [What to change] +**Verification**: [How to confirm it works] +``` + +### Example 3: Backend Architect Agent + +```markdown +--- +name: backend-architect +description: Use for API design, database optimization, and system architecture decisions +model: opus +tools: Read, Write, Edit, Bash, Grep +skills: + - backend-patterns +--- + +# Backend Architect + +## Role Definition + +You are a senior backend architect specializing in: +- API design (REST, GraphQL, tRPC) +- Database modeling and optimization +- System scalability +- Clean architecture patterns + +## Activation Triggers + +Use this agent when: +- Designing new API endpoints +- Optimizing database queries +- Planning system architecture +- Refactoring backend code + +## Methodology + +1. **Requirements Analysis**: Understand the business need +2. **Architecture Review**: Check current system state +3. **Design Options**: Propose 2-3 approaches with trade-offs +4. **Recommendation**: Suggest best approach with rationale +5. **Implementation Plan**: Break down into actionable steps + +## Constraints + +- Follow existing project patterns +- Prioritize backward compatibility +- Consider performance implications +- Document architectural decisions +``` + +## 4.6 Advanced Agent Patterns + +### Tool SEO - Optimizing Agent Descriptions + +The `description` field determines when Claude auto-activates your agent. Optimize it like SEO: + +```yaml +# ❌ Bad description +description: Reviews code + +# ✅ Good description (Tool SEO) +description: | + Security code reviewer - use PROACTIVELY when: + - Reviewing authentication/authorization code + - Analyzing API endpoints + - Checking input validation + - Auditing data handling + Triggers: security, auth, vulnerability, OWASP, injection +``` + +**Tool SEO Techniques**: +1. **"use PROACTIVELY"**: Encourages automatic activation +2. **Explicit triggers**: Keywords that trigger the agent +3. **Listed contexts**: When the agent is relevant +4. **Short nicknames**: `sec-1`, `perf-a`, `doc-gen` + +### Agent Weight Classification + +| Category | Tokens | Init Time | Optimal Use | +|----------|--------|-----------|-------------| +| **Lightweight** | <3K | <1s | Frequent tasks, workers | +| **Medium** | 10-15K | 2-3s | Analysis, reviews | +| **Heavy** | 25K+ | 5-10s | Architecture, full audits | + +**Golden Rule**: A lightweight agent used 100x > A heavy agent used 10x + +### The 7-Parallel-Task Method + +Launch 7 specialized sub-agents in parallel for complete features: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ PARALLEL FEATURE IMPLEMENTATION │ +│ │ +│ Task 1: Components → Create React components │ +│ Task 2: Styles → Generate Tailwind styles │ +│ Task 3: Tests → Write unit tests │ +│ Task 4: Types → Define TypeScript types │ +│ Task 5: Hooks → Create custom hooks │ +│ Task 6: Integration → Connect with API/state │ +│ Task 7: Config → Update configurations │ +│ │ +│ All in parallel → Final consolidation │ +└─────────────────────────────────────────────────────────────┘ +``` + +**Example Prompt**: +``` +Implement the "User Profile" feature using 7 parallel sub-agents: + +1. COMPONENTS: Create UserProfile.tsx, UserAvatar.tsx, UserStats.tsx +2. STYLES: Define Tailwind classes in a styles file +3. TESTS: Write tests for each component +4. TYPES: Create types in types/user-profile.ts +5. HOOKS: Create useUserProfile and useUserStats hooks +6. INTEGRATION: Connect with existing tRPC router +7. CONFIG: Update exports and routing + +Launch all agents in parallel. +``` + +### Split Role Sub-Agents + +**Concept**: Multi-perspective analysis in parallel. + +**Process**: +``` +┌─────────────────────────────────────────────────────────────┐ +│ SPLIT ROLE ANALYSIS │ +│ │ +│ Step 1: Setup │ +│ └─ Activate Plan Mode + ultrathink │ +│ │ +│ Step 2: Role Suggestion │ +│ └─ "What expert roles would analyze this code?" │ +│ Claude suggests: Security, Performance, UX, etc. │ +│ │ +│ Step 3: Selection │ +│ └─ "Use: Security Expert, Senior Dev, Code Reviewer" │ +│ │ +│ Step 4: Parallel Analysis │ +│ ├─ Security Agent: [Vulnerability analysis] │ +│ ├─ Senior Agent: [Architecture analysis] │ +│ └─ Reviewer Agent: [Readability analysis] │ +│ │ +│ Step 5: Consolidation │ +│ └─ Synthesize 3 reports into recommendations │ +└─────────────────────────────────────────────────────────────┘ +``` + +**Code Review Prompt**: +``` +Analyze this PR with the following perspectives: +1. Senior Engineer: Architecture and patterns +2. Security Expert: Vulnerabilities and risks +3. Performance Engineer: Bottlenecks and optimizations +4. Junior Dev: Readability and documentation +5. QA Engineer: Testability and edge cases +``` + +**UX Review Prompt**: +``` +Evaluate this interface with perspectives: +1. Designer: Visual consistency and design system +2. New User: Discoverability ease +3. Power User: Efficiency and shortcuts +4. Accessibility Expert: WCAG compliance +5. Mobile User: Responsive and touch +``` + +### Parallelization Decision Matrix + +``` +┌─────────────────────────────────────────────────────────────┐ +│ PARALLELIZABLE? │ +│ │ +│ Non-destructive Destructive │ +│ (read-only) (write) │ +│ │ +│ Independent ✅ PARALLEL ⚠️ SEQUENTIAL │ +│ Max efficiency Plan Mode first │ +│ │ +│ Dependent ⚠️ SEQUENTIAL ❌ CAREFUL │ +│ Order matters Risk of conflicts │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +**✅ Perfectly parallelizable**: +``` +"Search 8 different GitHub repos for best practices on X" +"Analyze these 5 files for vulnerabilities (without modifying)" +"Compare 4 libraries and produce a comparative report" +``` + +**⚠️ Sequential recommended**: +``` +"Refactor these 3 files (they depend on each other)" +"Migrate DB schema then update models then update routers" +``` + +**❌ Needs extra care**: +``` +"Modify these 10 files in parallel" +→ Risk: conflicts if files share imports/exports +→ Solution: Plan Mode → Identify dependencies → Sequence if needed +``` + +### Multi-Agent Orchestration Pattern + +``` +┌─────────────────────────────────────────────────────────────┐ +│ ORCHESTRATION PATTERN │ +│ │ +│ ┌──────────────┐ │ +│ │ Sonnet 4.5 │ │ +│ │ Orchestrator │ │ +│ └──────┬───────┘ │ +│ │ │ +│ ┌────────────┼────────────┐ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ +│ │ Haiku │ │ Haiku │ │ Haiku │ │ +│ │ Worker1 │ │ Worker2 │ │ Worker3 │ │ +│ └────┬────┘ └────┬────┘ └────┬────┘ │ +│ │ │ │ │ +│ └────────────┼────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌──────────────┐ │ +│ │ Sonnet 4.5 │ │ +│ │ Validator │ │ +│ └──────────────┘ │ +│ │ +│ Cost: 2-2.5x cheaper than Opus everywhere │ +│ Quality: Equivalent for 90% of tasks │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Tactical Model Selection Matrix + +| Task | Model | Justification | +|------|-------|---------------| +| Read and summarize a file | Haiku | Simple, fast | +| Write a standard component | Sonnet | Good balance | +| Debug complex issue | Sonnet + ultrathink | Depth needed | +| System architecture | Opus | Maximum reasoning | +| Critical security review | Opus | High stakes | +| Generate tests | Haiku | Repetitive pattern | +| Refactor 50 files | Sonnet orchestrate + Haiku workers | Optimized cost | + +**Cost Optimization Example**: +``` +Scenario: Refactoring 100 files + +❌ Naive approach: +- Opus for everything +- Cost: ~$50-100 +- Time: 2-3h + +✅ Optimized approach: +- Sonnet: Analysis and plan (1x) +- Haiku: Parallel workers (100x) +- Sonnet: Final validation (1x) +- Cost: ~$5-15 +- Time: 1h (parallelized) + +Savings: 80-90% +``` + +--- + +# 5. Skills + +**Reading time**: 15 minutes +**Skill level**: Week 2 +**Goal**: Create reusable knowledge modules + +## 5.1 Understanding Skills + +Skills are knowledge packages that agents can inherit. + +### Skills vs Agents vs Commands + +| Concept | Purpose | Invocation | +|---------|---------|------------| +| **Agent** | Specialized role | Task tool delegation | +| **Skill** | Knowledge module | Inherited by agents | +| **Command** | Process workflow | Slash command | + +### Why Skills? + +Without skills: +``` +Agent A: Has security knowledge (duplicated) +Agent B: Has security knowledge (duplicated) +Agent C: Has security knowledge (duplicated) +``` + +With skills: +``` +security-guardian skill: Single source of security knowledge +Agent A: inherits security-guardian +Agent B: inherits security-guardian +Agent C: inherits security-guardian +``` + +### What Makes a Good Skill? + +| Good Skill | Bad Skill | +|------------|-----------| +| Reusable across agents | Single-agent specific | +| Domain-focused | Too broad | +| Contains reference material | Just instructions | +| Includes checklists | Missing verification | + +## 5.2 Creating Skills + +Skills live in `.claude/skills/{skill-name}/` directories. + +### Skill Folder Structure + +``` +skill-name/ +├── SKILL.md # Required - Main instructions +├── reference.md # Optional - Detailed documentation +├── checklists/ # Optional - Verification lists +│ ├── security.md +│ └── performance.md +├── examples/ # Optional - Code patterns +│ ├── good-example.ts +│ └── bad-example.ts +└── scripts/ # Optional - Helper scripts + └── audit.sh +``` + +### SKILL.md Frontmatter + +```yaml +--- +name: skill-name +description: Short description for activation (100 chars) +allowed-tools: Read, Grep, Bash +context: fork +agent: specialist +--- +``` + +| Field | Description | +|-------|-------------| +| `name` | Kebab-case identifier | +| `description` | Activation trigger | +| `allowed-tools` | Tools this skill can use | +| `context` | `fork` (isolated) or `inherit` (shared) | +| `agent` | `specialist` (domain) or `general` (broad) | + +## 5.3 Skill Template + +```markdown +--- +name: your-skill-name +description: Expert guidance for [domain] problems +allowed-tools: Read, Grep, Bash +context: fork +agent: specialist +--- + +# Your Skill Name + +## Expertise Areas + +This skill provides knowledge in: +- [Area 1] +- [Area 2] +- [Area 3] + +## When to Apply + +Use this skill when: +- [Situation 1] +- [Situation 2] + +## Methodology + +When activated, follow this approach: +1. [Step 1] +2. [Step 2] +3. [Step 3] + +## Key Concepts + +### Concept 1: [Name] +[Explanation] + +### Concept 2: [Name] +[Explanation] + +## Checklists + +### Pre-Implementation Checklist +- [ ] [Check 1] +- [ ] [Check 2] +- [ ] [Check 3] + +### Post-Implementation Checklist +- [ ] [Verification 1] +- [ ] [Verification 2] + +## Examples + +### Good Pattern +```[language] +// Good example +``` + +### Anti-Pattern +```[language] +// Bad example - don't do this +``` + +## Reference Material + +See `reference.md` for detailed documentation. + +## 5.4 Skill Examples + +### Example 1: Security Guardian Skill + +```markdown +--- +name: security-guardian +description: Security expertise for OWASP Top 10, auth, and data protection +allowed-tools: Read, Grep, Bash +context: fork +agent: specialist +--- + +# Security Guardian + +## Expertise Areas + +- OWASP Top 10 vulnerabilities +- Authentication & Authorization +- Data protection & encryption +- API security +- Secrets management + +## OWASP Top 10 Checklist + +### A01: Broken Access Control +- [ ] Check authorization on every endpoint +- [ ] Verify row-level permissions +- [ ] Test IDOR vulnerabilities +- [ ] Check for privilege escalation + +### A02: Cryptographic Failures +- [ ] Check for hardcoded secrets +- [ ] Verify TLS configuration +- [ ] Review password hashing (bcrypt/argon2) +- [ ] Check data encryption at rest + +### A03: Injection +- [ ] Review SQL queries (parameterized?) +- [ ] Check NoSQL operations +- [ ] Review command execution +- [ ] Check XSS vectors + +[... more checklists ...] + +## Authentication Patterns + +### Good: Secure Password Hashing +```typescript +import { hash, verify } from 'argon2'; + +const hashedPassword = await hash(password); +const isValid = await verify(hashedPassword, inputPassword); +``` + +### Bad: Insecure Hashing +```typescript +// DON'T DO THIS +const hashed = md5(password); +const hashed = sha1(password); +``` + +## Secrets Management + +### Never Commit Secrets +``` +# .gitignore +.env +.env.local +*.pem +*credentials* +``` + +### Use Environment Variables +```typescript +// Good +const apiKey = process.env.API_KEY; + +// Bad +const apiKey = "sk-1234567890abcdef"; +``` + + +### Example 2: TDD Skill + +```markdown +--- +name: tdd +description: Test-Driven Development methodology and patterns +allowed-tools: Read, Write, Bash +context: inherit +agent: specialist +--- + +# TDD (Test-Driven Development) + +## The TDD Cycle + +┌─────────────────────────────────────────────────────────┐ +│ RED → GREEN → REFACTOR │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ 1. RED ──→ Write a failing test │ +│ │ │ +│ ▼ │ +│ 2. GREEN ──→ Write minimal code to pass │ +│ │ │ +│ ▼ │ +│ 3. REFACTOR ──→ Improve code, keep tests green │ +│ │ │ +│ └────────────→ Repeat │ +│ │ +└─────────────────────────────────────────────────────────┘ + + +## Methodology + +### Step 1: RED (Write Failing Test) + +Write a test for the behavior you want BEFORE writing any code. + +```typescript +// user.test.ts +describe('User', () => { + it('should validate email format', () => { + expect(isValidEmail('test@example.com')).toBe(true); + expect(isValidEmail('invalid')).toBe(false); + }); +}); +``` + +Run: `pnpm test` → Should FAIL (function doesn't exist) + +### Step 2: GREEN (Minimal Implementation) + +Write the MINIMUM code to make the test pass. + +```typescript +// user.ts +export const isValidEmail = (email: string): boolean => { + return email.includes('@'); +}; +``` + +Run: `pnpm test` → Should PASS + +### Step 3: REFACTOR (Improve) + +Now improve the implementation while keeping tests green. + +```typescript +// user.ts (improved) +export const isValidEmail = (email: string): boolean => { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + return emailRegex.test(email); +}; +``` + +Run: `pnpm test` → Should still PASS + +## Test Structure: AAA Pattern + +```typescript +it('should calculate order total', () => { + // Arrange - Set up test data + const items = [ + { price: 10, quantity: 2 }, + { price: 5, quantity: 3 } + ]; + + // Act - Execute the code + const total = calculateTotal(items); + + // Assert - Verify the result + expect(total).toBe(35); +}); +``` + +--- + +# 6. Commands + +**Reading time**: 10 minutes +**Skill level**: Week 1-2 +**Goal**: Create custom slash commands + +## 6.1 Slash Commands + +Slash commands are shortcuts for common workflows. + +### Built-in Commands + +| Command | Action | +|---------|--------| +| `/help` | Show all commands | +| `/clear` | Clear conversation | +| `/compact` | Summarize context | +| `/status` | Show session info | +| `/plan` | Enter Plan Mode | +| `/rewind` | Undo changes | +| `/exit` | Exit Claude Code | + +### Custom Commands + +You can create your own commands in `.claude/commands/`: + +``` +/tech:commit → .claude/commands/tech/commit.md +/tech:pr → .claude/commands/tech/pr.md +/product:scope → .claude/commands/product/scope.md +``` + +## 6.2 Creating Custom Commands + +Commands are markdown files that define a process. + +### Command File Location + +``` +.claude/commands/ +├── tech/ # Development workflows +│ ├── commit.md +│ └── pr.md +├── product/ # Product workflows +│ └── problem-framer.md +└── support/ # Support workflows + └── ticket-analyzer.md +``` + +### Command Naming + +| File | Invocation | +|------|------------| +| `commit.md` in `tech/` | `/tech:commit` | +| `pr.md` in `tech/` | `/tech:pr` | +| `problem-framer.md` in `product/` | `/product:problem-framer` | + +### Variable Interpolation + +Commands can accept arguments: + +```markdown +# My Command + +You received the following arguments: $ARGUMENTS + +Process them accordingly. +``` + +Usage: +``` +/tech:deploy production +``` + +`$ARGUMENTS` becomes `production`. + +## 6.3 Command Template + +```markdown +# Command Name + +## Purpose + +[Brief description of what this command does] + +## Process + +Follow these steps: + +1. **Step 1 Name** + [Detailed instructions] + +2. **Step 2 Name** + [Detailed instructions] + +3. **Step 3 Name** + [Detailed instructions] + +## Arguments + +If arguments provided ($ARGUMENTS): [How to handle them] +If no arguments: [Default behavior] + +## Output Format + +[Expected output structure] + +## Examples + +### Example 1 +Input: `/command arg1` +Output: [Expected result] + +## Error Handling + +If [error condition]: +- [Recovery action] +``` + +## 6.4 Command Examples + +### Example 1: Commit Command + +```markdown +# Commit Current Changes + +## Purpose + +Create a well-formatted git commit following Conventional Commits. + +## Process + +1. **Check Status** + Run `git status` to see all changes. + +2. **Analyze Changes** + Run `git diff` to understand what changed. + +3. **Review History** + Run `git log -5 --oneline` to see recent commit style. + +4. **Draft Message** + Create commit message following: + - `feat`: New feature + - `fix`: Bug fix + - `refactor`: Code restructuring + - `docs`: Documentation + - `test`: Test changes + - `chore`: Maintenance + +5. **Stage and Commit** + ```bash + git add [relevant files] + git commit -m "[type](scope): description" + ``` + +6. **Verify** + Run `git status` to confirm commit succeeded. + +## Arguments + +If $ARGUMENTS provided: +- Use as commit message hint: "$ARGUMENTS" + +## Output Format + +Commit: [hash] [message] +Files: [number] changed + + +### Example 2: PR Command + +```markdown +# Create Pull Request + +## Purpose + +Create a well-documented pull request on GitHub. + +## Process + +1. **Check Branch State** + - `git status` - Verify clean working directory + - `git branch` - Confirm on feature branch + - `git log main..HEAD` - Review all commits + +2. **Analyze Changes** + - `git diff main...HEAD` - See all changes vs main + - Understand the full scope of the PR + +3. **Push if Needed** + If branch not pushed: + ```bash + git push -u origin [branch-name] + ``` + +4. **Create PR** + +```bash +gh pr create --title "[title]" --body "[body]" +``` + +## PR Body Template + +```markdown +## Summary +[1-3 bullet points describing changes] + +## Changes +- [Specific change 1] +- [Specific change 2] + +## Testing +- [ ] Unit tests pass +- [ ] Manual testing completed +- [ ] No regressions + +## Screenshots +[If UI changes] +``` + +## Arguments + +If $ARGUMENTS provided: +- Use as PR title hint + +## Error Handling + +If not on feature branch: +- WARN: "Create a feature branch first" + +If working directory dirty: +- ASK: "Commit changes first?" + +### Example 3: Problem Framer Command + +```markdown +# Problem Framer + +## Purpose + +Challenge and refine problem definitions before solution design. + +## Process + +1. **Capture Initial Problem** + Record the problem as stated by user. + +2. **5 Whys Analysis** + Ask "Why?" 5 times to find root cause: + - Why 1: [First answer] + - Why 2: [Deeper answer] + - Why 3: [Even deeper] + - Why 4: [Getting to root] + - Why 5: [Root cause] + +3. **Stakeholder Analysis** + - Who is affected? + - Who has decision power? + - Who benefits from solution? + +4. **Constraint Identification** + - Technical constraints + - Business constraints + - Time constraints + - Resource constraints + +5. **Success Criteria** + Define measurable outcomes: + - [Metric 1]: [Target] + - [Metric 2]: [Target] + +6. **Reframe Problem** + Write refined problem statement: + "How might we [action] for [user] so that [outcome]?" + +## Output Format + +### Problem Analysis Report + +**Original Problem**: [As stated] + +**Root Cause**: [From 5 Whys] + +**Refined Problem Statement**: +"How might we [X] for [Y] so that [Z]?" + +**Success Criteria**: +1. [Measurable outcome 1] +2. [Measurable outcome 2] + +**Constraints**: +- [Constraint 1] +- [Constraint 2] +``` + +--- + +# 7. Hooks + +**Reading time**: 20 minutes +**Skill level**: Week 2-3 +**Goal**: Automate Claude Code with event-driven scripts + +## 7.1 The Event System + +Hooks are scripts that run automatically when specific events occur. + +### Event Types + +| Event | When It Fires | Use Case | +|-------|---------------|----------| +| `PreToolUse` | Before any tool runs | Security validation | +| `PostToolUse` | After any tool runs | Formatting, logging | +| `UserPromptSubmit` | User sends a message | Context enrichment | +| `Notification` | Claude sends notification | Sound alerts | +| `SessionStart` | Session begins | Initialization | +| `SessionEnd` | Session ends | Cleanup | +| `Stop` | User interrupts | Graceful shutdown | + +### Event Flow + +``` +┌─────────────────────────────────────────────────────────┐ +│ EVENT FLOW │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ User types message │ +│ │ │ +│ ▼ │ +│ ┌────────────────────┐ │ +│ │ UserPromptSubmit │ ← Add context (git status) │ +│ └────────────────────┘ │ +│ │ │ +│ ▼ │ +│ Claude decides to run tool (e.g., Edit) │ +│ │ │ +│ ▼ │ +│ ┌────────────────────┐ │ +│ │ PreToolUse │ ← Security check │ +│ └────────────────────┘ │ +│ │ │ +│ ▼ (if allowed) │ +│ Tool executes │ +│ │ │ +│ ▼ │ +│ ┌────────────────────┐ │ +│ │ PostToolUse │ ← Auto-format │ +│ └────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +## 7.2 Creating Hooks + +### Hook Registration (settings.json) + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash|Edit|Write", + "hooks": [ + { + "type": "command", + "command": ".claude/hooks/security-check.sh", + "timeout": 5000 + } + ] + } + ] + } +} +``` + +### Configuration Fields + +| Field | Description | +|-------|-------------| +| `matcher` | Regex pattern for which tools trigger hook | +| `type` | Always `"command"` | +| `command` | Path to hook script | +| `timeout` | Max execution time (ms) | + +### Hook Input (stdin JSON) + +Hooks receive JSON on stdin: + +```json +{ + "tool_name": "Bash", + "tool_input": { + "command": "git status" + }, + "session_id": "abc123", + "cwd": "/project" +} +``` + +### Hook Output + +Hooks can return JSON on stdout: + +```json +{ + "systemMessage": "Message shown to Claude", + "hookSpecificOutput": { + "additionalContext": "Extra information" + } +} +``` + +### Exit Codes + +| Code | Meaning | Result | +|------|---------|--------| +| `0` | Success | Allow operation | +| `2` | Block | Prevent operation | +| Other | Error | Log and continue | + +## 7.3 Hook Templates + +### Template 1: PreToolUse (Security Blocker) + +```bash +#!/bin/bash +# .claude/hooks/security-blocker.sh +# Blocks dangerous commands + +INPUT=$(cat) +TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name') +COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""') + +# List of dangerous patterns +DANGEROUS_PATTERNS=( + "rm -rf /" + "rm -rf ~" + "rm -rf *" + "sudo rm" + "git push --force origin main" + "git push -f origin main" + "npm publish" + "> /dev/sda" +) + +# Check if command matches any dangerous pattern +for pattern in "${DANGEROUS_PATTERNS[@]}"; do + if [[ "$COMMAND" == *"$pattern"* ]]; then + echo "BLOCKED: Dangerous command detected: $pattern" >&2 + exit 2 + fi +done + +exit 0 +``` + +### Template 2: PostToolUse (Auto-Formatter) + +```bash +#!/bin/bash +# .claude/hooks/auto-format.sh +# Auto-formats code after edits + +INPUT=$(cat) +TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name') + +# Only run for Edit/Write operations +if [[ "$TOOL_NAME" != "Edit" && "$TOOL_NAME" != "Write" ]]; then + exit 0 +fi + +# Get the file path +FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""') + +# Skip if no file path +if [[ -z "$FILE_PATH" ]]; then + exit 0 +fi + +# Run Prettier on supported files +if [[ "$FILE_PATH" =~ \.(ts|tsx|js|jsx|json|md|css|scss)$ ]]; then + npx prettier --write "$FILE_PATH" 2>/dev/null +fi + +exit 0 +``` + +### Template 3: UserPromptSubmit (Context Enricher) + +```bash +#!/bin/bash +# .claude/hooks/git-context.sh +# Adds git context to every prompt + +# Get git information +BRANCH=$(git branch --show-current 2>/dev/null || echo "not a git repo") +LAST_COMMIT=$(git log -1 --format='%h %s' 2>/dev/null || echo "no commits") +STAGED=$(git diff --cached --stat 2>/dev/null | tail -1 || echo "none") +UNSTAGED=$(git diff --stat 2>/dev/null | tail -1 || echo "none") + +# Output JSON with context +cat << EOF +{ + "hookSpecificOutput": { + "additionalContext": "[Git] Branch: $BRANCH | Last: $LAST_COMMIT | Staged: $STAGED | Unstaged: $UNSTAGED" + } +} +EOF + +exit 0 +``` + +### Template 4: Notification (Sound Alerts) + +```bash +#!/bin/bash +# .claude/hooks/notification.sh +# Plays sounds on notifications (macOS) + +INPUT=$(cat) +TITLE=$(echo "$INPUT" | jq -r '.title // ""') +BODY=$(echo "$INPUT" | jq -r '.body // ""') + +# Determine sound based on content +if [[ "$TITLE" == *"error"* ]] || [[ "$BODY" == *"failed"* ]]; then + SOUND="/System/Library/Sounds/Basso.aiff" +elif [[ "$TITLE" == *"complete"* ]] || [[ "$BODY" == *"success"* ]]; then + SOUND="/System/Library/Sounds/Hero.aiff" +else + SOUND="/System/Library/Sounds/Pop.aiff" +fi + +# Play sound (macOS) +afplay "$SOUND" 2>/dev/null & + +exit 0 +``` + +## 7.4 Security Hooks + +Security hooks are critical for protecting your system. + +### Recommended Security Rules + +```bash +#!/bin/bash +# .claude/hooks/comprehensive-security.sh + +INPUT=$(cat) +COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""') + +# === CRITICAL BLOCKS (Exit 2) === + +# Filesystem destruction +[[ "$COMMAND" =~ rm.*-rf.*[/~] ]] && { echo "BLOCKED: Recursive delete of root/home" >&2; exit 2; } + +# Disk operations +[[ "$COMMAND" =~ ">/dev/sd" ]] && { echo "BLOCKED: Direct disk write" >&2; exit 2; } +[[ "$COMMAND" =~ "dd if=" ]] && { echo "BLOCKED: dd command" >&2; exit 2; } + +# Git force operations on protected branches +[[ "$COMMAND" =~ "git push".*"-f".*"(main|master)" ]] && { echo "BLOCKED: Force push to main" >&2; exit 2; } +[[ "$COMMAND" =~ "git push --force".*"(main|master)" ]] && { echo "BLOCKED: Force push to main" >&2; exit 2; } + +# Package publishing +[[ "$COMMAND" =~ "npm publish" ]] && { echo "BLOCKED: npm publish" >&2; exit 2; } + +# Privileged operations +[[ "$COMMAND" =~ ^sudo ]] && { echo "BLOCKED: sudo command" >&2; exit 2; } + +# === WARNINGS (Exit 0 but log) === + +[[ "$COMMAND" =~ "rm -rf" ]] && echo "WARNING: Recursive delete detected" >&2 + +exit 0 +``` + +### Testing Security Hooks + +Before deploying, test your hooks: + +```bash +# Test with a blocked command +echo '{"tool_name":"Bash","tool_input":{"command":"rm -rf /"}}' | .claude/hooks/security-blocker.sh +echo "Exit code: $?" # Should be 2 + +# Test with a safe command +echo '{"tool_name":"Bash","tool_input":{"command":"git status"}}' | .claude/hooks/security-blocker.sh +echo "Exit code: $?" # Should be 0 +``` + +## 7.5 Hook Examples + +### Example 1: Activity Logger + +```bash +#!/bin/bash +# .claude/hooks/activity-logger.sh +# Logs all tool usage to JSONL file + +INPUT=$(cat) +LOG_DIR="$HOME/.claude/logs" +LOG_FILE="$LOG_DIR/activity-$(date +%Y-%m-%d).jsonl" + +# Create log directory +mkdir -p "$LOG_DIR" + +# Clean up old logs (keep 7 days) +find "$LOG_DIR" -name "activity-*.jsonl" -mtime +7 -delete + +# Extract tool info +TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name') +TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%SZ") +SESSION_ID=$(echo "$INPUT" | jq -r '.session_id') + +# Create log entry +LOG_ENTRY=$(jq -n \ + --arg timestamp "$TIMESTAMP" \ + --arg tool "$TOOL_NAME" \ + --arg session "$SESSION_ID" \ + '{timestamp: $timestamp, tool: $tool, session: $session}') + +# Append to log +echo "$LOG_ENTRY" >> "$LOG_FILE" + +exit 0 +``` + +### Example 2: Linting Gate + +```bash +#!/bin/bash +# .claude/hooks/lint-gate.sh +# Runs linter after code changes + +INPUT=$(cat) +TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name') + +# Only check after Edit/Write +if [[ "$TOOL_NAME" != "Edit" && "$TOOL_NAME" != "Write" ]]; then + exit 0 +fi + +FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""') + +# Only lint TypeScript/JavaScript +if [[ ! "$FILE_PATH" =~ \.(ts|tsx|js|jsx)$ ]]; then + exit 0 +fi + +# Run ESLint +LINT_OUTPUT=$(npx eslint "$FILE_PATH" 2>&1) +LINT_EXIT=$? + +if [[ $LINT_EXIT -ne 0 ]]; then + cat << EOF +{ + "systemMessage": "Lint errors found in $FILE_PATH:\n$LINT_OUTPUT" +} +EOF +fi + +exit 0 +``` + +--- + +# 8. MCP Servers + +**Reading time**: 15 minutes +**Skill level**: Week 2-3 +**Goal**: Extend Claude Code with external tools + +## 8.1 What is MCP + +MCP (Model Context Protocol) is a standard for connecting AI models to external tools and data sources. + +### Why MCP? + +| Without MCP | With MCP | +|-------------|----------| +| Limited to built-in tools | Extensible tool ecosystem | +| Claude guesses about external data | Claude queries real data | +| Generic code understanding | Deep semantic analysis | + +### How It Works + +``` +┌─────────────────────────────────────────────────────────┐ +│ MCP ARCHITECTURE │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────┐ │ +│ │ Claude Code │ │ +│ └──────┬──────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────────────────────────────┐ │ +│ │ MCP Protocol │ │ +│ └──────────────────────┬──────────────────────┘ │ +│ │ │ +│ ┌───────────────┼───────────────┐ │ +│ ▼ ▼ ▼ │ +│ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ +│ │ Serena │ │ Context7 │ │ Postgres │ │ +│ │(Semantic) │ │ (Docs) │ │(Database) │ │ +│ └───────────┘ └───────────┘ └───────────┘ │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +## 8.2 Available Servers + +### Serena (Semantic Code Analysis) + +**Purpose**: Deep code understanding through semantic analysis. + +**Tools**: + +| Tool | Description | +|------|-------------| +| `find_symbol` | Find functions, classes, methods by name | +| `get_symbols_overview` | Get file structure overview | +| `search_for_pattern` | Regex search across codebase | +| `find_referencing_symbols` | Find all usages of a symbol | +| `replace_symbol_body` | Replace function/class body | + +**Use when**: +- Navigating large codebases +- Understanding symbol relationships +- Refactoring across files + +### Context7 (Documentation Lookup) + +**Purpose**: Access official library documentation. + +**Tools**: + +| Tool | Description | +|------|-------------| +| `resolve-library-id` | Find library documentation | +| `query-docs` | Query specific documentation | + +**Use when**: +- Learning new libraries +- Finding correct API usage +- Checking official patterns + +### Sequential Thinking (Structured Reasoning) + +**Purpose**: Multi-step analysis with explicit reasoning. + +**Tools**: + +| Tool | Description | +|------|-------------| +| `sequentialthinking` | Step-by-step reasoning | + +**Use when**: +- Complex debugging +- Architectural analysis +- System design decisions + +### Postgres (Database Queries) + +**Purpose**: Direct database access for queries. + +**Tools**: + +| Tool | Description | +|------|-------------| +| `query` | Execute SQL queries | + +**Use when**: +- Investigating data issues +- Understanding schema +- Debugging data problems + +### Playwright (Browser Automation) + +**Purpose**: Browser testing and automation. + +**Tools**: + +| Tool | Description | +|------|-------------| +| `navigate` | Go to URL | +| `click` | Click element | +| `fill` | Fill form field | +| `screenshot` | Capture screenshot | + +**Use when**: +- E2E testing +- Visual validation +- Browser debugging + +## 8.3 Configuration + +### mcp.json Location + +``` +~/.claude/mcp.json # Global MCP configuration +/project/.claude/mcp.json # Project-specific (overrides) +``` + +### Example Configuration + +```json +{ + "servers": { + "serena": { + "command": "npx", + "args": ["serena-mcp"], + "env": { + "PROJECT_PATH": "${workspaceFolder}" + } + }, + "context7": { + "command": "npx", + "args": ["@context7/mcp-server"] + }, + "postgres": { + "command": "npx", + "args": ["@modelcontextprotocol/server-postgres"], + "env": { + "DATABASE_URL": "${env:DATABASE_URL}" + } + } + } +} +``` + +### Configuration Fields + +| Field | Description | +|-------|-------------| +| `command` | Executable to run | +| `args` | Command arguments | +| `env` | Environment variables | +| `cwd` | Working directory | + +### Variable Substitution + +| Variable | Expands To | +|----------|------------| +| `${workspaceFolder}` | Current project path | +| `${env:VAR_NAME}` | Environment variable | + +## 8.4 Server Selection Guide + +### Decision Tree + +``` +What do you need? +│ +├─ Deep code understanding? +│ └─ Use Serena +│ +├─ Library documentation? +│ └─ Use Context7 +│ +├─ Complex reasoning? +│ └─ Use Sequential Thinking +│ +├─ Database queries? +│ └─ Use Postgres +│ +├─ Browser testing? +│ └─ Use Playwright +│ +└─ General task? + └─ Use built-in tools +``` + +### Server Comparison + +| Need | Best Server | Why | +|------|-------------|-----| +| "Find all usages of this function" | Serena | Semantic analysis | +| "How does React useEffect work?" | Context7 | Official docs | +| "Why is this failing?" | Sequential | Structured debugging | +| "What's in the users table?" | Postgres | Direct query | +| "Test the login flow" | Playwright | Browser automation | + +### Combining Servers + +Servers can work together: + +``` +1. Context7 → Get official pattern for auth +2. Serena → Find existing auth code +3. Sequential → Analyze how to integrate +4. Playwright → Test the implementation +``` + +--- + +# 9. Advanced Patterns + +**Reading time**: 20 minutes +**Skill level**: Month 1+ +**Goal**: Master power-user techniques + +## 9.1 The Trinity + +The most powerful Claude Code pattern combines three techniques: + +``` +┌─────────────────────────────────────────────────────────┐ +│ THE TRINITY │ +├─────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────┐ │ +│ │ Plan Mode │ Safe exploration without changes │ +│ └──────┬──────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────┐ │ +│ │ Ultrathink │ Deep analysis with extended thinking │ +│ └──────┬──────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────────┐ │ +│ │ Sequential Thinking │ Structured multi-step reason │ +│ └─────────────────────┘ │ +│ │ +│ Combined: Maximum understanding before action │ +│ │ +└─────────────────────────────────────────────────────────┘ +``` + +### When to Use the Trinity + +| Situation | Use Trinity? | +|-----------|--------------| +| Fixing a typo | ❌ Overkill | +| Adding a feature | Maybe | +| Debugging complex issue | ✅ Yes | +| Architectural decision | ✅ Yes | +| Legacy system modernization | ✅ Yes | + +### Ultrathink Levels + +| Flag | Thinking Depth | Token Usage | Best For | +|------|----------------|-------------|----------| +| `--think` | Standard | ~4K | Multi-component analysis | +| `--think-hard` | Deep | ~10K | Architectural decisions | +| `--ultrathink` | Maximum | ~32K | Critical redesign | + +### Example: Using the Trinity + +``` +You: /plan + +Let's analyze this legacy authentication system before we touch anything. +Use --ultrathink to understand all the implications. + +[Claude enters Plan Mode and does deep analysis] + +Claude: I've analyzed the auth system. Here's what I found: +- 47 files depend on the current auth module +- 3 critical security issues +- Migration path needs 4 phases + +Ready to implement? + +You: /execute +Let's start with phase 1 +``` + +## 9.2 Composition Patterns + +### Multi-Agent Delegation + +Launch multiple agents for different aspects: + +``` +You: For this feature, I need: +1. Backend architect to design the API +2. Security reviewer to audit the design +3. Test engineer to plan the tests + +Run these in parallel. +``` + +Claude will coordinate: +- Backend architect designs API +- Security reviewer audits (in parallel) +- Test engineer plans tests (in parallel) + +### Skill Stacking + +Combine multiple skills for complex tasks: + +```yaml +# code-reviewer.md +skills: + - security-guardian + - performance-patterns + - accessibility-checker +``` + +The reviewer now has all three knowledge domains. + +### The "Rev the Engine" Pattern + +For quality work, use multiple rounds of critique: + +``` +You: Write the function, then critique it, then improve it. +Do this 3 times. + +Round 1: [Initial implementation] +Critique: [What's wrong] +Improvement: [Better version] + +Round 2: [Improved implementation] +Critique: [What's still wrong] +Improvement: [Even better version] + +Round 3: [Final implementation] +Final check: [Verification] +``` + +### The "Stack Maximum" Pattern + +For critical work, combine everything: + +``` +1. Plan Mode + Ultrathink → Deep exploration +2. Multiple Agents → Specialized analysis +3. Sequential Thinking → Structured reasoning +4. Rev the Engine → Iterative improvement +5. Code Review Agent → Final validation +``` + +## 9.3 CI/CD Integration + +### Headless Mode + +Run Claude Code without interactive prompts: + +```bash +# Basic headless execution +claude --headless "Run the tests and report results" + +# With timeout +claude --headless --timeout 300 "Build the project" + +# With specific model +claude --headless --model sonnet "Analyze code quality" +``` + +### Git Hooks Integration + +**Pre-commit hook**: + +```bash +#!/bin/bash +# .git/hooks/pre-commit + +# Run Claude Code for commit message validation +COMMIT_MSG=$(cat "$1") +claude --headless "Is this commit message good? '$COMMIT_MSG'. Reply YES or NO with reason." +``` + +**Pre-push hook**: + +```bash +#!/bin/bash +# .git/hooks/pre-push + +# Security check before push +claude --headless "Scan staged files for secrets and security issues. Exit 1 if found." +EXIT_CODE=$? + +if [ $EXIT_CODE -ne 0 ]; then + echo "Security issues found. Push blocked." + exit 1 +fi +``` + +### GitHub Actions Integration + +```yaml +# .github/workflows/claude-review.yml +name: Claude Code Review + +on: + pull_request: + types: [opened, synchronize] + +jobs: + review: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install Claude Code + run: npm install -g @anthropic-ai/claude-code + + - name: Run Review + env: + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + run: | + claude --headless "Review the changes in this PR. \ + Focus on security, performance, and code quality. \ + Output as markdown." +``` + +## 9.4 IDE Integration + +### VS Code Integration + +Claude Code integrates with VS Code: + +1. **Install Extension**: Search "Claude Code" in Extensions +2. **Configure**: Set API key in settings +3. **Use**: + - `Ctrl+Shift+P` → "Claude Code: Start Session" + - Select text → Right-click → "Ask Claude" + +### JetBrains Integration + +Works with IntelliJ, WebStorm, PyCharm: + +1. **Install Plugin**: Settings → Plugins → "Claude Code" +2. **Configure**: Tools → Claude Code → Set API key +3. **Use**: + - `Ctrl+Shift+A` → "Claude Code" + - Tool window for persistent session + +### Terminal Integration + +For terminal-native workflow: + +```bash +# Add to .bashrc or .zshrc +alias cc='claude' +alias ccp='claude --plan' +alias cce='claude --execute' + +# Quick code question +cq() { + claude --headless "$*" +} +``` + +Usage: +```bash +cq "What does this regex do: ^[a-z]+$" +``` + +## 9.5 Tight Feedback Loops + +**Reading time**: 5 minutes +**Skill level**: Week 1+ + +Tight feedback loops accelerate learning and catch issues early. Design your workflow to validate changes immediately. + +### The Feedback Loop Pyramid + +``` + ┌─────────────┐ + │ Deploy │ ← Hours/Days + │ Tests │ + ├─────────────┤ + │ CI/CD │ ← Minutes + │ Pipeline │ + ├─────────────┤ + │ Local │ ← Seconds + │ Tests │ + ├─────────────┤ + │ TypeCheck │ ← Immediate + │ Lint │ + └─────────────┘ +``` + +### Implementing Tight Loops + +#### Level 1: Immediate (IDE/Editor) +```bash +# Watch mode for instant feedback +pnpm tsc --watch +pnpm lint --watch +``` + +#### Level 2: On-Save (Git Hooks) +```bash +# Pre-commit hook +#!/bin/bash +pnpm lint-staged && pnpm tsc --noEmit +``` + +#### Level 3: On-Commit (CI) +```yaml +# GitHub Action for PR checks +- run: pnpm lint && pnpm tsc && pnpm test +``` + +### Claude Code Integration + +Use hooks for automatic validation: + +```json +// settings.json +{ + "hooks": { + "PostToolUse": [{ + "matcher": "Edit|Write", + "hooks": ["./scripts/validate.sh"] + }] + } +} +``` + +**validate.sh:** +```bash +#!/bin/bash +# Run after every file change +FILE=$(echo "$TOOL_INPUT" | jq -r '.file_path // .file') +if [[ "$FILE" == *.ts || "$FILE" == *.tsx ]]; then + npx tsc --noEmit "$FILE" 2>&1 | head -5 +fi +``` + +### Feedback Loop Checklist + +| Loop | Trigger | Response Time | What It Catches | +|------|---------|---------------|-----------------| +| Lint | On type | <1s | Style, imports | +| TypeCheck | On save | 1-3s | Type errors | +| Unit tests | On save | 5-15s | Logic errors | +| Integration | On commit | 1-5min | API contracts | +| E2E | On PR | 5-15min | User flows | + +💡 **Tip**: Faster loops catch more bugs. Invest in making your test suite fast. + +## 9.6 Todo as Instruction Mirrors + +**Reading time**: 5 minutes +**Skill level**: Week 1+ + +TodoWrite isn't just tracking—it's an instruction mechanism. Well-crafted todos guide Claude's execution. + +### The Mirror Principle + +What you write as a todo becomes Claude's instruction: + +``` +❌ Vague Todo → Vague Execution +"Fix the bug" + +✅ Specific Todo → Precise Execution +"Fix null pointer in getUserById when user not found - return null instead of throwing" +``` + +### Todo as Specification + +```markdown +## Effective Todo Pattern + +- [ ] **What**: Create user validation function +- [ ] **Where**: src/lib/validation.ts +- [ ] **How**: Use Zod schema with email, password rules +- [ ] **Verify**: Test with edge cases (empty, invalid format) +``` + +### Todo Granularity Guide + +| Task Complexity | Todo Granularity | Example | +|-----------------|------------------|---------| +| Simple fix | 1-2 todos | "Fix typo in header component" | +| Feature | 3-5 todos | Auth flow steps | +| Epic | 10+ todos | Full feature with tests | + +### Instruction Embedding + +Embed constraints directly in todos: + +```markdown +## Bad +- [ ] Add error handling + +## Good +- [ ] Add error handling: try/catch around API calls, + log errors with context, return user-friendly messages, + use existing ErrorBoundary component +``` + +### Todo Templates + +**Bug Fix:** +```markdown +- [ ] Reproduce: [steps to reproduce] +- [ ] Root cause: [investigation findings] +- [ ] Fix: [specific change needed] +- [ ] Verify: [test command or manual check] +``` + +**Feature:** +```markdown +- [ ] Design: [what components/functions needed] +- [ ] Implement: [core logic] +- [ ] Tests: [test coverage expectations] +- [ ] Docs: [if public API] +``` + +## 9.7 Output Styles + +**Reading time**: 5 minutes +**Skill level**: Week 1+ + +Control how Claude responds to match your workflow preferences. + +### Output Style Spectrum + +``` +← Minimal Verbose → +─────────────────────────────────────────────────────── +Code only | Code + comments | Explanations | Tutorial +``` + +### Style Directives + +Add to CLAUDE.md or prompt: + +**Minimal (Expert Mode):** +```markdown +Output code only. No explanations unless asked. +Assume I understand the codebase. +``` + +**Balanced:** +```markdown +Explain significant decisions. Comment complex logic. +Skip obvious explanations. +``` + +**Verbose (Learning Mode):** +```markdown +Explain each step. Include alternatives considered. +Link to documentation for concepts used. +``` + +### Context-Aware Styles + +```markdown +## In CLAUDE.md + +### Output Preferences +- **Code reviews**: Detailed, cite specific lines +- **Bug fixes**: Minimal, show diff only +- **New features**: Balanced, explain architecture decisions +- **Refactoring**: Minimal, trust my review +``` + +### Format Control + +**For code:** +```markdown +Format code output as: +- Full file with changes marked: // CHANGED +- Diff format for reviews +- Inline for small changes +``` + +**For explanations:** +```markdown +Explain using: +- Bullet points for lists +- Tables for comparisons +- Diagrams for architecture +``` + +### Output Templates + +**Bug Fix Output:** +```markdown +**Root Cause**: [one line] +**Fix**: [code block] +**Test**: [verification command] +``` + +**Feature Output:** +```markdown +**Files Changed**: [list] +**Key Decisions**: [bullet points] +**Next Steps**: [if any] +``` + +## 9.8 Vibe Coding & Skeleton Projects + +**Reading time**: 5 minutes +**Skill level**: Month 1 + +### Vibe Coding + +"Vibe Coding" is rapid prototyping through natural conversation—exploring ideas before committing to implementation. + +#### When to Vibe Code + +- **Early exploration**: Testing if an approach works +- **Proof of concept**: Quick validation before full implementation +- **Learning**: Understanding a new library or pattern + +#### Vibe Coding Session + +```markdown +User: Let's explore how we could add real-time updates to the dashboard. + Don't write code yet, just brainstorm approaches. + +Claude: Here are three approaches we could consider: + +1. **WebSockets**: Full duplex, lowest latency + - Pro: Real-time push + - Con: Connection management complexity + +2. **Server-Sent Events (SSE)**: One-way server push + - Pro: Simple, native browser support + - Con: One direction only + +3. **Polling**: Periodic HTTP requests + - Pro: Simplest implementation + - Con: Not truly real-time, more server load + +User: Let's vibe on option 2. Show me a minimal SSE setup. + +Claude: [Provides minimal example for exploration] +``` + +#### Vibe Coding Rules + +1. **No production code**: This is exploration only +2. **Throw away freely**: No attachment to vibe code +3. **Focus on learning**: Understand the approach +4. **Signal clearly**: "This is vibe code, not for production" + +### Skeleton Projects + +Skeleton projects are minimal, working templates that establish patterns before full implementation. + +#### Skeleton Structure + +``` +project/ +├── src/ +│ ├── index.ts # Entry point (working) +│ ├── config.ts # Config structure (minimal) +│ ├── types.ts # Core types (defined) +│ └── features/ +│ └── example/ # One working example +│ ├── route.ts +│ ├── service.ts +│ └── repo.ts +├── tests/ +│ └── example.test.ts # One working test +└── package.json # Dependencies defined +``` + +#### Skeleton Principles + +1. **It must run**: `pnpm dev` works from day 1 +2. **One complete vertical**: Full stack for one feature +3. **Patterns, not features**: Shows HOW, not WHAT +4. **Minimal dependencies**: Only what's needed + +#### Creating a Skeleton + +```markdown +User: Create a skeleton for our new microservice. Include: + - Express setup + - One complete route (health check) + - Database connection pattern + - Test setup + - Docker configuration + +Claude: [Creates minimal, working skeleton with these elements] +``` + +#### Skeleton Expansion + +``` +Skeleton (Day 1) → MVP (Week 1) → Full (Month 1) +──────────────────────────────────────────────────────────── +1 route → 5 routes → 20 routes +1 test → 20 tests → 100+ tests +Basic config → Env-based → Full config +Local DB → Docker DB → Production DB +``` + +## 9.9 Batch Operations Pattern + +**Reading time**: 5 minutes +**Skill level**: Week 1+ + +Batch operations improve efficiency and reduce context usage when making similar changes across files. + +### When to Batch + +| Scenario | Batch? | Why | +|----------|--------|-----| +| Same change in 5+ files | ✅ Yes | Efficiency | +| Related changes in 3 files | ✅ Yes | Coherence | +| Unrelated fixes | ❌ No | Risk of errors | +| Complex refactoring | ⚠️ Maybe | Depends on pattern | + +### Batch Patterns + +#### 1. Import Updates +```markdown +User: Update all files in src/components to use the new Button import: + - Old: import { Button } from "~/ui/button" + - New: import { Button } from "~/components/ui/button" +``` + +#### 2. API Migration +```markdown +User: Migrate all API calls from v1 to v2: + - Change: /api/v1/* → /api/v2/* + - Update response handling for new format + - Files: src/services/*.ts +``` + +#### 3. Pattern Application +```markdown +User: Add error boundaries to all page components: + - Wrap each page export with ErrorBoundary + - Use consistent error fallback + - Files: src/pages/**/*.tsx +``` + +### Batch Execution Strategy + +``` +1. Identify scope → List all affected files +2. Define pattern → Exact change needed +3. Create template → One example implementation +4. Batch apply → Apply to all files +5. Verify all → Run tests, typecheck +``` + +### Batch with Claude + +```markdown +## Effective Batch Request + +"Apply this change pattern to all matching files: + +**Pattern**: Add 'use client' directive to components using hooks +**Scope**: src/components/**/*.tsx +**Rule**: If file contains useState, useEffect, or useContext +**Change**: Add 'use client' as first line + +List affected files first, then make changes." +``` + +--- + +# 10. Reference + +**Purpose**: Quick lookup for all Claude Code information + +## 10.1 Commands Table + +### Built-in Commands + +| Command | Action | Category | +|---------|--------|----------| +| `/help` | Show all available commands | Navigation | +| `/clear` | Clear conversation history | Session | +| `/compact` | Summarize and compress context | Context | +| `/status` | Show session info (context, cost) | Info | +| `/plan` | Enter Plan Mode | Mode | +| `/execute` | Exit Plan Mode | Mode | +| `/rewind` | Undo recent changes | Edit | +| `/exit` | Exit Claude Code | Session | +| `Ctrl+D` | Exit Claude Code | Session | + +### Quick Actions + +| Action | Shortcut | +|--------|----------| +| Run shell command | `!command` | +| Reference file | `@filename` | +| Cancel operation | `Ctrl+C` | +| Retry last | `Ctrl+R` | +| Dismiss suggestion | `Esc` | + +## 10.2 Keyboard Shortcuts + +| Shortcut | Action | +|----------|--------| +| `Enter` | Send message | +| `Shift+Enter` | New line in message | +| `Ctrl+C` | Cancel current operation | +| `Ctrl+D` | Exit Claude Code | +| `Ctrl+R` | Retry last operation | +| `Ctrl+L` | Clear screen (keeps context) | +| `Tab` | Autocomplete file paths | +| `↑` / `↓` | Navigate command history | +| `Esc` | Dismiss current suggestion | + +## 10.3 Configuration Reference + +### CLAUDE.md Locations + +| Location | Scope | Committed | +|----------|-------|-----------| +| `~/.claude/CLAUDE.md` | All projects | N/A | +| `/project/CLAUDE.md` | This project | ✅ Yes | +| `/project/.claude/CLAUDE.md` | Personal | ❌ No | + +### Settings Files + +| File | Purpose | Committed | +|------|---------|-----------| +| `settings.json` | Hook configuration | ✅ Yes | +| `settings.local.json` | Permission overrides | ❌ No | + +### Permission Patterns + +| Pattern | Matches | +|---------|---------| +| `Bash(git *)` | Any git command | +| `Bash(npm test)` | Exactly npm test | +| `Edit` | All file edits | +| `Write` | All file writes | +| `WebSearch` | Web search | +| `mcp__serena__*` | All Serena tools | + +## 10.4 Troubleshooting + +| Symptom | Cause | Solution | +|---------|-------|----------| +| "Context too long" | Used 100% context | `/clear` or `/compact` | +| Slow responses | High context usage | `/compact` | +| "Permission denied" | Security settings | Check `settings.local.json` | +| Hook not running | Registration error | Check `settings.json` matcher | +| MCP tool not found | Server not running | Check `mcp.json` config | +| Agent not found | File naming | Check `.claude/agents/` | +| Command not found | Path error | Check `.claude/commands/` | + +### Context Recovery + +| Context Level | Recommended Action | +|---------------|-------------------| +| 0-50% | Continue normally | +| 50-75% | Be more specific in queries | +| 75-90% | Use `/compact` | +| 90%+ | Use `/clear` | + +### Common Errors + +**"Tool execution failed"** +- Check tool permissions in `settings.local.json` +- Verify command syntax +- Check for missing dependencies + +**"Agent not available"** +- Verify agent file exists in `.claude/agents/` +- Check YAML frontmatter syntax +- Restart Claude Code session + +**"Hook blocked operation"** +- Check hook exit code (2 = blocked) +- Review hook error message +- Adjust hook rules if needed + +## 10.5 Cheatsheet + +### One-Page Quick Reference + +``` +╔══════════════════════════════════════════════════════════╗ +║ CLAUDE CODE CHEATSHEET ║ +╠══════════════════════════════════════════════════════════╣ +║ ║ +║ ESSENTIAL COMMANDS ║ +║ ───────────────── ║ +║ /help Show commands /clear Fresh start ║ +║ /status Session info /compact Save context ║ +║ /plan Safe mode /rewind Undo changes ║ +║ /exit Quit Ctrl+C Cancel ║ +║ ║ +║ QUICK ACTIONS ║ +║ ───────────── ║ +║ !command Run shell @file Reference file ║ +║ Ctrl+R Retry ↑/↓ History ║ +║ ║ +║ CONTEXT MANAGEMENT ║ +║ ────────────────── ║ +║ 🟢 0-50% Work freely ║ +║ 🟡 50-75% Be selective ║ +║ 🔴 75-90% /compact now ║ +║ ⚫ 90%+ /clear required ║ +║ ║ +║ PERMISSION MODES ║ +║ ──────────────── ║ +║ Default Ask before changes ║ +║ Auto-accept Execute without asking ║ +║ Plan Mode Read-only exploration ║ +║ ║ +║ CONFIGURATION ║ +║ ───────────── ║ +║ ~/.claude/CLAUDE.md Global settings ║ +║ /project/CLAUDE.md Project settings ║ +║ .claude/settings.json Hooks config ║ +║ .claude/settings.local.json Permission overrides ║ +║ ║ +║ .claude/ FOLDER ║ +║ ─────────────── ║ +║ agents/ Custom agents commands/ Slash commands ║ +║ hooks/ Event scripts rules/ Auto-load rules ║ +║ skills/ Knowledge modules ║ +║ ║ +║ ULTRATHINK LEVELS ║ +║ ───────────────── ║ +║ --think ~4K tokens Standard analysis ║ +║ --think-hard ~10K tokens Deep analysis ║ +║ --ultrathink ~32K tokens Maximum depth ║ +║ ║ +║ MCP SERVERS ║ +║ ─────────── ║ +║ Serena Semantic code analysis ║ +║ Context7 Library documentation ║ +║ Sequential Structured reasoning ║ +║ Postgres Database queries ║ +║ Playwright Browser automation ║ +║ ║ +║ HOOKS (events) ║ +║ ────────────── ║ +║ PreToolUse Before tool (security) ║ +║ PostToolUse After tool (format, log) ║ +║ UserPromptSubmit On message (enrich context) ║ +║ ║ +║ WORKFLOW ║ +║ ──────── ║ +║ Describe → Analyze → Review → Accept/Reject → Verify ║ +║ ║ +║ BEST PRACTICE: Always read the diff before accepting! ║ +║ ║ +╚══════════════════════════════════════════════════════════╝ +``` + +## 10.6 Daily Workflow & Checklists + +### Daily Workflow Pattern + +``` +┌─────────────────────────────────────────────────────────────┐ +│ DAILY WORKFLOW │ +├─────────────────────────────────────────────────────────────┤ +│ │ +│ MORNING (Setup) │ +│ ─────────────── │ +│ □ Git pull latest changes │ +│ □ Review context with /status │ +│ □ Load project memory (/sc:load if using Serena) │ +│ □ Review yesterday's progress │ +│ │ +│ WORK SESSION │ +│ ──────────── │ +│ □ Define task clearly before starting │ +│ □ Use TodoWrite for multi-step work │ +│ □ Commit after each completed task │ +│ □ /compact when context >70% │ +│ □ Take breaks every 90 minutes │ +│ │ +│ END OF DAY │ +│ ────────── │ +│ □ Commit all work in progress │ +│ □ Save session (/sc:save) │ +│ □ Note blockers or next steps │ +│ □ Push to remote │ +│ │ +└─────────────────────────────────────────────────────────────┘ +``` + +### Task-Specific Checklists + +#### Bug Fix Checklist +``` +□ Reproduce the bug (confirm it exists) +□ Identify root cause (not just symptoms) +□ Write failing test (captures the bug) +□ Implement fix +□ Verify test passes +□ Check for regressions +□ Update documentation if needed +□ Commit with descriptive message +``` + +#### Feature Implementation Checklist +``` +□ Requirements clear? (Ask if not) +□ Design approach documented +□ Break into small tasks (TodoWrite) +□ Implement core functionality first +□ Add tests alongside code +□ Handle error cases +□ Update types/interfaces +□ Run full test suite +□ Code review (self or peer) +□ Documentation updated +``` + +#### Code Review Checklist +``` +□ Code compiles without errors +□ Tests pass (new and existing) +□ No security vulnerabilities +□ Performance implications considered +□ Error handling adequate +□ Code style consistent +□ No commented-out code +□ No debug statements left +□ Documentation updated +``` + +#### Refactoring Checklist +``` +□ Tests exist before refactoring +□ All tests pass before starting +□ Small, incremental changes +□ Run tests after each change +□ No behavior changes (unless intended) +□ Remove dead code +□ Update imports and references +□ Final test run passes +``` + +### Prompt Quality Checklist + +Use this before sending complex requests: + +``` +□ WHAT: Clear deliverable described? +□ WHERE: File paths/locations specified? +□ HOW: Constraints/approach mentioned? +□ WHY: Context for decision-making? +□ VERIFY: Success criteria defined? +``` + +**Example applying checklist:** + +``` +❌ Vague: "Add user authentication" + +✅ Complete: +"Add JWT authentication to the /api/login endpoint. +- WHERE: src/api/auth/login.ts +- HOW: Use jsonwebtoken library (already in deps), + bcrypt for password comparison +- CONSTRAINTS: Token expires in 24h, include userId and role +- VERIFY: Test with wrong password, expired token, invalid token" +``` + +--- + +# Appendix: Templates Collection + +## A.1 Agent Template + +```markdown +--- +name: your-agent-name +description: Use this agent when [specific trigger] +model: sonnet +tools: Read, Write, Edit, Bash, Grep, Glob +skills: [] +--- + +# Agent Name + +## Role Definition +You are an expert in [domain]. + +## Activation Triggers +Use this agent when: +- [Trigger 1] +- [Trigger 2] + +## Methodology +1. [Step 1] +2. [Step 2] +3. [Step 3] + +## Output Format +[Expected deliverables] + +## Examples +[Concrete usage examples] +``` + +## A.2 Skill Template + +```markdown +--- +name: skill-name +description: Expert guidance for [domain] +allowed-tools: Read, Grep, Bash +context: fork +agent: specialist +--- + +# Skill Name + +## Expertise Areas +- [Area 1] +- [Area 2] + +## Methodology +1. [Step 1] +2. [Step 2] + +## Checklists +- [ ] [Check 1] +- [ ] [Check 2] + +## Examples +[Good and bad patterns] +``` + +## A.3 Command Template + +```markdown +# Command Name + +## Purpose +[What this command does] + +## Process +1. **Step 1**: [Instructions] +2. **Step 2**: [Instructions] + +## Arguments +$ARGUMENTS usage: [How to handle] + +## Output Format +[Expected output] +``` + +## A.4 Hook Templates + +### PreToolUse (Security) + +```bash +#!/bin/bash +INPUT=$(cat) +COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""') + +# Block dangerous patterns +[[ "$COMMAND" =~ "dangerous-pattern" ]] && { echo "BLOCKED" >&2; exit 2; } + +exit 0 +``` + +### PostToolUse (Formatting) + +```bash +#!/bin/bash +INPUT=$(cat) +FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""') + +# Auto-format +[[ "$FILE_PATH" =~ \.(ts|tsx)$ ]] && npx prettier --write "$FILE_PATH" 2>/dev/null + +exit 0 +``` + +### UserPromptSubmit (Context) + +```bash +#!/bin/bash +CONTEXT="[Custom context here]" +cat << EOF +{"hookSpecificOutput":{"additionalContext":"$CONTEXT"}} +EOF +exit 0 +``` + +## A.5 settings.json Template + +```json +{ + "hooks": { + "PreToolUse": [ + { + "matcher": "Bash", + "hooks": [{"type": "command", "command": ".claude/hooks/security.sh", "timeout": 5000}] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [{"type": "command", "command": ".claude/hooks/format.sh"}] + } + ], + "UserPromptSubmit": [ + { + "matcher": "", + "hooks": [{"type": "command", "command": ".claude/hooks/context.sh"}] + } + ] + } +} +``` + +## A.6 settings.local.json Template + +```json +{ + "permissions": { + "allow": [ + "Bash(git *)", + "Bash(npm test)", + "Bash(pnpm *)", + "Edit", + "Write" + ], + "deny": [ + "Bash(rm -rf *)", + "Bash(sudo *)" + ], + "ask": [ + "Bash(npm publish)", + "Bash(git push --force)" + ] + } +} +``` + +## A.7 CLAUDE.md Template + +```markdown +# Project Name + +## Tech Stack +- [Technology 1] +- [Technology 2] + +## Code Conventions +- [Convention 1] +- [Convention 2] + +## Architecture +- [Pattern 1] +- [Pattern 2] + +## Commands +- `npm run dev` - Start development +- `npm test` - Run tests +``` + +## A.8 Prompt Templates + +### Feature Request Prompt +```markdown +## Feature: [Name] + +**Deliverable**: [Concrete output] +**Location**: [File paths] + +**Requirements**: +1. [Requirement 1] +2. [Requirement 2] + +**Constraints**: +- Must use [existing pattern/library] +- Must handle [edge case] + +**Acceptance Criteria**: +- [ ] [Criterion 1] +- [ ] [Criterion 2] + +**Verification**: [Commands to verify] +``` + +### Bug Fix Prompt +```markdown +## Bug: [Brief description] + +**Observed**: [What happens] +**Expected**: [What should happen] +**Reproduce**: [Steps or file:line reference] + +**Suspected Cause**: [If known] + +**Files to Check**: +- [file1.ts] +- [file2.ts] + +**Fix Should**: +- [ ] Resolve the issue +- [ ] Not break existing tests +- [ ] Include test for this case +``` + +### Refactoring Prompt +```markdown +## Refactor: [Component/Function name] + +**Current State**: [What's wrong] +**Target State**: [What we want] +**Scope**: [Files affected] + +**Approach**: +1. [Step 1] +2. [Step 2] + +**Constraints**: +- No behavior change +- Keep API surface same +- [Other constraints] + +**Verify**: [Test commands] +``` + +### Code Review Prompt +```markdown +## Review: [PR/Files description] + +**Focus Areas**: +- [ ] Security vulnerabilities +- [ ] Performance concerns +- [ ] Code style compliance +- [ ] Test coverage + +**Context**: [Why these changes] + +**Questions**: +1. [Specific question about approach] +2. [Specific question about implementation] +``` + +### Architecture Discussion Prompt +```markdown +## Architecture: [Topic] + +**Current State**: +[Describe current architecture] + +**Problem**: +[What's not working or missing] + +**Options Considered**: +1. **Option A**: [Description] + - Pro: [...] + - Con: [...] +2. **Option B**: [Description] + - Pro: [...] + - Con: [...] + +**Constraints**: +- [Constraint 1] +- [Constraint 2] + +**Questions**: +1. [What you need Claude to analyze] +``` + +## A.9 Success Metrics & Maturity Model + +### Claude Code Maturity Model + +| Level | Name | Characteristics | Typical Timeline | +|-------|------|-----------------|------------------| +| 1 | **Beginner** | Uses basic commands, accepts all changes, minimal config | Day 1-7 | +| 2 | **Competent** | Reviews diffs, uses /compact, basic CLAUDE.md | Week 1-2 | +| 3 | **Proficient** | Creates agents, uses hooks, Plan Mode mastery | Week 2-4 | +| 4 | **Advanced** | MCP servers, multi-agent workflows, full automation | Month 1-2 | +| 5 | **Expert** | Custom tooling, CI/CD integration, team patterns | Month 2+ | + +### Success Metrics by Area + +#### Productivity Metrics +| Metric | Beginner | Proficient | Expert | +|--------|----------|------------|--------| +| Tasks completed/day | 2-3 | 5-7 | 10+ | +| Context resets/day | 3+ | 1-2 | 0-1 | +| Rejected changes | <30% | <10% | <5% | +| Time to first commit | >1h | 30min | <15min | + +#### Quality Metrics +| Metric | Target | Measure | +|--------|--------|---------| +| Test coverage | >80% | Coverage reports | +| Type errors | 0 | `tsc --noEmit` | +| Lint violations | 0 | Linter output | +| Security issues | 0 | Security scan | + +#### Efficiency Metrics +| Metric | Baseline | Optimized | +|--------|----------|-----------| +| Context usage | ~90% | <70% | +| Parallel operations | None | 3-5 simultaneous | +| Agent delegation | Never | When appropriate | +| Hook automation | None | Full automation | + +### Self-Assessment Checklist + +#### Day 1 Proficiency +``` +□ Can start Claude Code session +□ Know essential commands (/help, /clear, /status) +□ Understand permission prompts +□ Can describe tasks clearly +□ Know how to cancel operations (Ctrl+C) +``` + +#### Week 1 Proficiency +``` +□ Use /compact to manage context +□ Review diffs before accepting +□ Have basic CLAUDE.md setup +□ Understand Plan Mode purpose +□ Can use file references (@filename) +``` + +#### Month 1 Proficiency +``` +□ Created at least 1 custom agent +□ Use hooks for automation +□ Understand MCP server selection +□ Can manage multi-step tasks +□ Use appropriate think levels +``` + +### Improvement Tracking + +```markdown +## Weekly Retrospective Template + +**Week of**: [Date] + +**Accomplishments**: +- [Major task completed] +- [Skill learned] + +**Challenges**: +- [What was difficult] +- [Where Claude struggled] + +**Improvements Made**: +- [Config change] +- [New pattern adopted] + +**Next Week Goals**: +- [ ] [Improvement 1] +- [ ] [Improvement 2] + +**Claude Usage Stats**: +- Sessions: [count] +- Avg context at reset: [%] +- Commands created: [count] +- Agents created: [count] +``` + +--- + +## About This Guide + +**End of Guide** + +--- + +**Author**: [Florian BRUNIAUX](https://github.com/florianb) | Founding Engineer [@Méthode Aristote](https://methode-aristote.fr) + +**Written with**: Claude (Anthropic) - This guide was collaboratively written with Claude Code, demonstrating the tool's capabilities for technical documentation. + +**Inspired by**: [Claudelog.com](https://claudelog.com/) - An excellent resource for Claude Code tips, patterns, and advanced techniques that served as a major reference for this guide. + +**License**: MIT - Feel free to use, adapt, and share. + +**Contributions**: Issues and PRs welcome. + +**Last updated**: January 2025 | **Version**: 1.0