[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"similar-Cranot--claude-code-guide":3,"tool-Cranot--claude-code-guide":61},[4,18,26,36,44,53],{"id":5,"name":6,"github_repo":7,"description_zh":8,"stars":9,"difficulty_score":10,"last_commit_at":11,"category_tags":12,"status":17},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[13,14,15,16],"Agent","开发框架","图像","数据工具","ready",{"id":19,"name":20,"github_repo":21,"description_zh":22,"stars":23,"difficulty_score":10,"last_commit_at":24,"category_tags":25,"status":17},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[14,15,13],{"id":27,"name":28,"github_repo":29,"description_zh":30,"stars":31,"difficulty_score":32,"last_commit_at":33,"category_tags":34,"status":17},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",150037,2,"2026-04-10T23:33:47",[14,13,35],"语言模型",{"id":37,"name":38,"github_repo":39,"description_zh":40,"stars":41,"difficulty_score":32,"last_commit_at":42,"category_tags":43,"status":17},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[14,15,13],{"id":45,"name":46,"github_repo":47,"description_zh":48,"stars":49,"difficulty_score":32,"last_commit_at":50,"category_tags":51,"status":17},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[52,13,15,14],"插件",{"id":54,"name":55,"github_repo":56,"description_zh":57,"stars":58,"difficulty_score":32,"last_commit_at":59,"category_tags":60,"status":17},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[52,14],{"id":62,"github_repo":63,"name":64,"description_en":65,"description_zh":66,"ai_summary_zh":66,"readme_en":67,"readme_zh":68,"quickstart_zh":69,"use_case_zh":70,"hero_image_url":71,"owner_login":72,"owner_name":73,"owner_avatar_url":74,"owner_bio":73,"owner_company":75,"owner_location":76,"owner_email":73,"owner_twitter":77,"owner_website":78,"owner_url":79,"languages":80,"stars":85,"forks":86,"last_commit_at":87,"license":73,"difficulty_score":32,"env_os":88,"env_gpu":89,"env_ram":89,"env_deps":90,"category_tags":95,"github_topics":73,"view_count":10,"oss_zip_url":73,"oss_zip_packed_at":73,"status":17,"created_at":96,"updated_at":97,"faqs":98,"releases":99},3543,"Cranot\u002Fclaude-code-guide","claude-code-guide","The Complete Claude Code CLI Guide - Live & Auto-Updated Every 2 Days","claude-code-guide 是一份专为 Claude Code 命令行工具打造的实时指南，旨在帮助开发者快速掌握这款驻留在终端中的智能编程助手。Claude Code 能够理解整个项目上下文，通过自然语言对话直接编辑文件、执行命令并管理开发流程，从而显著提升编码效率。\n\n这份指南解决了官方文档更新频繁、功能特性分散难以查阅的痛点。它每两天自动同步一次，整合了官方文档、GitHub 发布说明及社区实践，确保用户始终获取最新、最准确的操作指引。无论是基础的会话管理、内置命令查询，还是进阶的 MCP（模型上下文协议）集成、Skills 系统配置及多智能体协作，指南都提供了清晰的示例与最佳实践。\n\n该资源特别适合需要在终端环境中高效工作的软件工程师、DevOps 人员及技术研究人员。其独特亮点在于不仅服务于人类读者，还针对 AI Agent 进行了优化标注，明确区分“官方确认”、“社区观察”与“实验性”功能，帮助用户在复杂的技术迭代中做出明智决策。无论你是刚接触命令行辅助编程的新手，还是希望深度定制工作流的高级用户，claude-code-guide 都能成为你值得信赖的案头参考。","# The Complete Claude Code CLI Guide\n\n[![Official Docs](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FOfficial_Docs-code.claude.com-blue)](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview) [![GitHub](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FGitHub-anthropics%2Fclaude--code-black)](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code) [![NPM](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FNPM-@anthropic--ai%2Fclaude--code-red)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@anthropic-ai\u002Fclaude-code) [![Auto-Updated](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FAuto--Updated-Every%202%20Days-brightgreen)](#auto-update-pipeline)\n\n**Quick Links:** [Get Started](#what-is-claude-code) · [Commands](#quick-reference) · [MCP Setup](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fmcp) · [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings) · [SDK](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsdk) · [Changelog](#changelog)\n\n> **🔄 Live Guide**: Auto-updated every 2 days from [official docs](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview), [GitHub releases](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Freleases), and [Anthropic changelog](https:\u002F\u002Fwww.anthropic.com\u002Fchangelog). See [update-log.md](.\u002Fupdate-log.md).\n\n> **🤖 For AI Agents**: Optimized for both humans and AI. `[OFFICIAL]` = from code.claude.com. `[COMMUNITY]` = observed patterns. `[EXPERIMENTAL]` = unverified.\n\n---\n\n## What is Claude Code?\n\n**Claude Code is an agentic AI coding assistant that lives in your terminal.** It understands your codebase, edits files directly, runs commands, and helps you code faster through natural language conversation.\n\n**Key Capabilities:**\n- 💬 Natural language interface in your terminal\n- 📝 Direct file editing and command execution\n- 🔍 Full project context awareness\n- 🔗 External integrations via MCP (Model Context Protocol)\n- 🤖 Extensible via Skills, Hooks, and Plugins\n- 🛡️ Sandboxed execution for security\n\n**Installation:**\n```bash\n# Quick Install (macOS, Linux, WSL)\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash\n\n# Windows PowerShell\nirm https:\u002F\u002Fclaude.ai\u002Finstall.ps1 | iex\n\n# Windows CMD\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.cmd -o install.cmd && install.cmd && del install.cmd\n\n# Alternative: Homebrew (macOS\u002FLinux)\nbrew install --cask claude-code\n\n# Alternative: WinGet (Windows)\nwinget install Anthropic.ClaudeCode\n\n# Alternative: NPM (⚠️ Deprecated - use native install instead)\nnpm install -g @anthropic-ai\u002Fclaude-code\n\nclaude --version  # Verify installation\n```\n\n**Official Documentation:** https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview\n\n---\n\n## Contents\n\n| Getting Started | Core Features | Practical Usage | Reference |\n|-----------------|---------------|-----------------|-----------|\n| [What is Claude Code?](#what-is-claude-code) | [Skills System](#skills-system) | [Development Workflows](#development-workflows) | [Security](#security-considerations) |\n| [Core Concepts](#core-concepts) | [Built-in Commands](#built-in-commands) | [Tool Synergies](#tool-synergies) | [SDK Integration](#sdk-integration) |\n| [Quick Start Guide](#quick-start-guide) | [Hooks System](#hooks-system) | [Examples Library](#examples-library) | [Troubleshooting](#troubleshooting) |\n| [Quick Reference](#quick-reference) | [MCP Integration](#mcp-integration) | [Best Practices](#best-practices) | [Changelog](#changelog) |\n| | [Sub-Agents](#sub-agents) | | [Auto-Update Pipeline](#auto-update-pipeline) |\n| | [Agent Teams](#agent-teams) | | |\n| | [Plugins](#plugins) | | |\n\n---\n\n## Quick Reference\n\n### Essential Commands [OFFICIAL]\n\n```bash\n# Starting Claude Code\nclaude                    # Start interactive session\nclaude -p \"task\"          # Print mode (non-interactive)\nclaude --continue         # Continue last session\nclaude --resume \u003Cid>      # Resume specific session\n\n# Session Management\n\u002Fhelp                     # Show available commands\n\u002Fexit                     # End session\n\u002Fcompact                  # Reduce context size\n\u002Fcompact [instructions]  # Compact conversation with optional focus instructions\n\n# Background Tasks\n\u002Fbashes                   # List background processes\n\u002Fkill \u003Cid>               # Stop background process\n\n# Discovery\n\u002Fcommands                 # List skills and commands\n\u002Fhooks                   # Show configured hooks\n\u002Fskills                  # List available Skills (NEW)\n\u002Fplugin                  # Manage plugins\n```\n\n**Source:** [CLI Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n### CLI Flags Reference [OFFICIAL]\n\n```bash\n# Output Control\nclaude -p, --print \"task\"          # Print mode: non-interactive, prints result and exits\nclaude --output-format json         # Output format: text, json, or stream-json\nclaude --input-format text          # Input format: text or stream-json\nclaude --verbose                    # Enable verbose logging (full turn-by-turn output)\n\n# Session Management\nclaude --continue                   # Continue from last session\nclaude --resume \u003Csession-id>        # Resume specific session by ID or name\nclaude --from-pr \u003Cpr>               # Resume session linked to GitHub PR number or URL [NEW]\nclaude --fork-session               # Create new session ID instead of reusing original\nclaude --session-id \u003Cuuid>          # Use specific session ID (must be valid UUID)\n\n# Remote Sessions (claude.ai subscribers)\nclaude --remote \"task\"              # Create web session on claude.ai\nclaude --teleport                   # Resume web session in local terminal\n\n# Debugging & Logging\nclaude --debug                      # Enable debug mode (with optional category filtering)\nclaude --debug \"api,mcp\"            # Debug specific categories\nclaude --debug \"!statsig,!file\"     # Exclude categories with !\n\n# Model & Agent Configuration\nclaude --model \u003Cname>               # Specify model (sonnet, opus, haiku, or full name)\nclaude --fallback-model \u003Cname>      # Fallback model when default overloaded (print mode)\nclaude --agent \u003Cname>               # Specify custom agent (overrides settings)\nclaude --agents '\u003Cjson>'            # Define custom subagents dynamically via JSON\n\n# System Prompt Customization\nclaude --system-prompt \"prompt\"     # Replace entire default system prompt\nclaude --system-prompt-file \u003Cpath>  # Replace with file contents (print mode only)\nclaude --append-system-prompt \"...\"  # Append to default system prompt\nclaude --append-system-prompt-file \u003Cpath>  # Append file contents (print mode only)\n\n# Tool & Permission Management\nclaude --tools \"Bash,Read,Edit\"     # Restrict built-in tools (use \"\" to disable all)\nclaude --allowedTools \"Bash(git:*)\" # Tools that execute without prompting\nclaude --disallowedTools \"Edit\"     # Tools removed from context\nclaude --permission-mode plan       # Begin in specified permission mode\nclaude --dangerously-skip-permissions  # Skip all permission prompts ⚠️\nclaude --allow-dangerously-skip-permissions  # Enable bypass option without activating [NEW]\nclaude --permission-prompt-tool \u003Cmcp-tool>  # MCP tool for permission prompts (non-interactive) [NEW]\n\n# Budget & Execution Limits (print mode)\nclaude --max-budget-usd 5.00        # Maximum dollar amount for API calls\nclaude --max-turns 3                # Limit number of agentic turns\nclaude --json-schema '\u003Cschema>'     # Get validated JSON output matching schema (print mode) [NEW]\n\n# Directory & Configuration\nclaude --add-dir ..\u002Fapps ..\u002Flib     # Add additional working directories\nclaude --plugin-dir .\u002Fmy-plugins    # Load plugins from directories\nclaude --settings .\u002Fsettings.json   # Path to settings JSON file\nclaude --setting-sources user,project  # Comma-separated list of setting sources [NEW]\nclaude --mcp-config .\u002Fmcp.json      # Load MCP servers from JSON file\nclaude --strict-mcp-config          # Only use MCP servers from --mcp-config\n\n# IDE & Browser Integration\nclaude --ide                        # Auto-connect to IDE on startup\nclaude --chrome                     # Enable Chrome browser integration\nclaude --no-chrome                  # Disable Chrome browser integration\n\n# Agent Teams [NEW]\nclaude --teammate-mode in-process   # Teammates display in main terminal\nclaude --teammate-mode tmux         # Each teammate in own pane (requires tmux\u002FiTerm2)\nclaude --teammate-mode auto         # Auto-detect (default)\n\n# Setup & Maintenance\nclaude --init                       # Run Setup hooks and start interactive mode\nclaude --init-only                  # Run Setup hooks and exit (no interactive session)\nclaude --maintenance                # Run Setup hooks with maintenance trigger and exit\n\n# Other Options\nclaude --disable-slash-commands     # Disable all skills and slash commands\nclaude --no-session-persistence     # Disable session persistence (print mode)\nclaude --betas interleaved-thinking # Beta headers for API requests\nclaude --include-partial-messages   # Include partial streaming events (with stream-json) [NEW]\n```\n\n**Common Flag Combinations:**\n\n```bash\n# One-off task with JSON output\nclaude --print \"analyze this code\" --output-format json\n\n# Debug MCP and API issues\nclaude --debug \"api,mcp\"\n\n# Resume session with specific model\nclaude --resume auth-refactor --model opus\n\n# Non-interactive with budget limit (CI\u002FCD)\nclaude -p --max-budget-usd 5.00 --output-format json \"run tests\"\n\n# Custom subagents for specialized work\nclaude --agents '{\"reviewer\":{\"description\":\"Code reviewer\",\"prompt\":\"Review for bugs\"}}'\n\n# Remote session for claude.ai subscribers\nclaude --remote \"fix the login bug\"\n```\n\n**Source:** [CLI Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n### Core Tools [OFFICIAL]\n\n| Tool | Purpose | Permission Required |\n|------|---------|---------------------|\n| **Read** | Read files, images, PDFs | No |\n| **Write** | Create new files | Yes |\n| **Edit** | Modify existing files | Yes |\n| **Bash** | Execute shell commands | Yes |\n| **Grep** | Search content with regex | No |\n| **Glob** | Find files by pattern | No |\n| **TodoWrite** | Task management | No |\n| **Task** | Launch sub-agents | No |\n| **WebFetch** | Fetch web content | Yes |\n| **WebSearch** | Search the web | Yes |\n| **NotebookEdit** | Edit Jupyter notebooks | Yes |\n| **NotebookRead** | Read Jupyter notebooks | No |\n\n**Source:** [Settings Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n---\n\n## Core Concepts\n\n### 1. How Claude Code Works [OFFICIAL]\n\nClaude Code operates through a **conversational interface** in your terminal:\n\n```bash\n# You describe what you want\n$ claude\n> \"Add user authentication to the API\"\n\n# Claude Code:\n1. Analyzes your codebase structure\n2. Plans the implementation\n3. Requests permission for file edits (first time)\n4. Writes code directly to your files\n5. Can run tests and verify changes\n6. Creates git commits if requested\n```\n\n**Key Principles:**\n- **Natural Language**: Just describe what you need - no special syntax\n- **Direct Action**: Edits files and runs commands with your permission\n- **Context Aware**: Understands your entire project structure\n- **Incremental Trust**: Asks permission as needed for new operations\n- **Scriptable**: Can be automated via SDK\n\n**Source:** [Overview](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview)\n\n### 2. Permission Model [OFFICIAL]\n\nClaude Code uses an **incremental permission system** for safety:\n\n```bash\n# Permission Modes\n\"ask\"    # Prompt for each use (default for new operations)\n\"allow\"  # Permit without asking\n\"deny\"   # Block completely\n\n# Permission Priority [NEW v2.1.27]\n# Content-level rules override tool-level rules\n# Example: allow: [\"Bash\"], ask: [\"Bash(rm *)\"]\n#   -> Bash is generally allowed, but \"rm *\" commands require confirmation\n\n# Tools Requiring Permission\n- Bash (command execution)\n- Write\u002FEdit\u002FNotebookEdit (file modifications)\n- WebFetch\u002FWebSearch (network access)\n- Skill (skills and custom commands)\n\n# Tools Not Requiring Permission (Safe Operations)\n- Read\u002FNotebookRead (reading files)\n- Grep\u002FGlob (searching)\n- TodoWrite (task tracking)\n- Task (sub-agents)\n```\n\n**Configuring Permissions:**\n\nCreate `.claude\u002Fsettings.json` in your project or `~\u002F.claude\u002Fsettings.json` globally:\n\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"ask\",\n    \"allow\": {\n      \"Bash\": [\"git status\", \"git diff\", \"git log\", \"npm test\", \"npm run*\"],\n      \"Read\": {},\n      \"Edit\": {}\n    },\n    \"deny\": {\n      \"Write\": [\"*.env\", \".env.*\", \".git\u002F*\"],\n      \"Edit\": [\"*.env\", \".env.*\"]\n    },\n    \"additionalDirectories\": [\n      \"\u002Fpath\u002Fto\u002Fother\u002Fproject\"\n    ]\n  }\n}\n```\n\n**Source:** [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n### 3. Project Context - CLAUDE.md [COMMUNITY]\n\nA **CLAUDE.md** file in your project root provides persistent context across sessions:\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>Example CLAUDE.md file (click to expand)\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n    # Project: My Application\n\n    ## Critical Context (Read First)\n    - Language: TypeScript + Node.js\n    - Framework: Express + React\n    - Database: PostgreSQL with Prisma ORM\n    - Testing: Jest + React Testing Library\n\n    ## Commands That Work\n    npm run dev          # Start dev server (port 3000)\n    npm test             # Run all tests\n    npm run lint         # ESLint check\n    npm run typecheck    # TypeScript validation\n    npm run db:migrate   # Run Prisma migrations\n\n    ## Important Patterns\n    - All API routes in \u002Fsrc\u002Froutes - RESTful structure\n    - Database queries use Prisma Client\n    - Auth uses JWT tokens (implementation in \u002Fsrc\u002Fauth)\n    - Frontend components in \u002Fsrc\u002Fcomponents\n    - API responses: {success: boolean, data: any, error?: string}\n\n    ## Gotchas & What NOT to Do\n    - DON'T modify \u002Fgenerated folder (auto-generated by Prisma)\n    - DON'T commit .env files (use .env.example instead)\n    - ALWAYS run npm run db:migrate after pulling schema changes\n    - DON'T use `any` type in TypeScript - use proper typing\n\n    ## File Structure\n    \u002Fsrc\n      \u002Froutes       # Express API routes\n      \u002Fservices     # Business logic\n      \u002Fmodels       # Type definitions\n      \u002Fmiddleware   # Express middleware\n      \u002Futils        # Shared utilities\n      \u002Fauth         # Authentication logic\n\n    ## Recent Learnings\n    - [2026-01-15] Payment webhook needs raw body parser for Stripe\n    - [2026-01-10] Redis pool: {maxRetriesPerRequest: 3}\n\n\u003C\u002Fdetails>\n\n**Why CLAUDE.md Helps:**\n- ✅ Provides context immediately at session start\n- ✅ Reduces need to re-explain project structure\n- ✅ Stores project-specific patterns and conventions\n- ✅ Documents what works (and what doesn't)\n- ✅ Shared with team via git\n- ✅ AI-optimized format for Claude to understand quickly\n\n**Note:** While CLAUDE.md is not an official feature, it's a widely-adopted community pattern. Claude Code will automatically read it if present at project root.\n\n### 4. Tools Reference [OFFICIAL]\n\n#### Read Tool\n**Purpose:** Read and analyze files\n\n```bash\n# Examples\nRead file_path=\"\u002Fsrc\u002Fapp.ts\"\nRead file_path=\"\u002Fdocs\u002Fscreenshot.png\"  # Can read images!\nRead file_path=\"\u002Fdocs\u002Fguide.pdf\"       # Can read PDFs!\nRead file_path=\"\u002Fdocs\u002Fguide.pdf\" pages=\"1-5\"  # Read specific PDF pages [NEW v2.1.30]\n```\n\n**Capabilities:**\n- Reads any text file (code, configs, logs, etc.)\n- Handles images (screenshots, diagrams, charts)\n- Processes PDFs - extracts text and visual content\n- Parses Jupyter notebooks (.ipynb files)\n- Returns content with line numbers (`cat -n` format)\n- Can read large files with offset\u002Flimit parameters\n\n**PDF Parameters** [NEW v2.1.30]:\n- `pages`: Optional page range (e.g., `\"1-5\"`, `\"1,3,5\"`) to read specific pages\n- Large PDFs (>10 pages) return a lightweight reference when @mentioned\n- PDF limits: Maximum 100 pages, 20MB file size\n\n**Special Features:**\n- **Images**: Claude can read screenshots of errors, UI designs, architecture diagrams\n- **PDFs**: Extract and analyze PDF content, useful for documentation and requirements\n- **Notebooks**: Full access to code cells, markdown, and outputs\n\n#### Write Tool\n**Purpose:** Create new files\n\n```bash\nWrite file_path=\"\u002Fsrc\u002FnewFile.ts\"\n      content=\"export const config = {...}\"\n```\n\n**Behavior:**\n- Creates new file with specified content\n- Will OVERWRITE if file already exists (use Edit for existing files)\n- Requires permission on first use per session\n- Creates parent directories if needed\n\n**Best Practice:** Use Edit tool for modifying existing files, Write tool only for new files.\n\n#### Edit Tool\n**Purpose:** Modify existing files with precise string replacement\n\n```bash\nEdit file_path=\"\u002Fsrc\u002Fapp.ts\"\n     old_string=\"const port = 3000\"\n     new_string=\"const port = process.env.PORT || 3000\"\n```\n\n**Important:**\n- Requires **exact string match** including whitespace and indentation\n- Fails if `old_string` is not unique in file (use larger context or `replace_all`)\n- Use `replace_all=true` to replace all occurrences (useful for renaming)\n- Must read file first before editing\n\n**Common Pattern:**\n```bash\n# 1. Read file to see exact content\nRead file_path=\"\u002Fsrc\u002Fapp.ts\"\n\n# 2. Edit with exact string match\nEdit file_path=\"\u002Fsrc\u002Fapp.ts\"\n     old_string=\"function login() {\n  return 'TODO';\n}\"\n     new_string=\"function login() {\n  return authenticateUser();\n}\"\n```\n\n#### Bash Tool\n**Purpose:** Execute shell commands\n\n```bash\nBash command=\"npm test\"\nBash command=\"git status\"\nBash command=\"find . -name '*.test.ts'\"\n```\n\n**Features:**\n- Can run any shell command\n- Supports background execution (`run_in_background=true`)\n- Configurable timeout (default 2 minutes, max 10 minutes)\n- Git operations are common (status, diff, log, commit, push)\n\n**Security:**\n- Requires permission\n- Can be restricted by pattern in settings\n- Sandboxing available on macOS\u002FLinux\n\n**Common Git Patterns:**\n```bash\n# Check status\nBash command=\"git status\"\n\n# View changes\nBash command=\"git diff\"\n\n# Create commit\nBash command='git add . && git commit -m \"feat: add authentication\"'\n\n# View history\nBash command=\"git log --oneline -10\"\n```\n\n#### Grep Tool\n**Purpose:** Search file contents with regex patterns\n\n```bash\n# Find functions\nGrep pattern=\"function.*auth\" path=\"src\u002F\" output_mode=\"content\"\n\n# Find TODOs with context\nGrep pattern=\"TODO\" output_mode=\"content\" -C=3\n\n# Count occurrences\nGrep pattern=\"import.*from\" output_mode=\"count\"\n\n# Case insensitive\nGrep pattern=\"error\" -i=true output_mode=\"files_with_matches\"\n```\n\n**Parameters:**\n- `pattern`: Regex pattern (ripgrep syntax)\n- `path`: Directory or file to search (default: current directory)\n- `output_mode`:\n  - `\"files_with_matches\"` (default) - Just file paths\n  - `\"content\"` - Show matching lines\n  - `\"count\"` - Show match counts per file\n- `-A`, `-B`, `-C`: Context lines (after, before, both)\n- `-i`: Case insensitive\n- `-n`: Show line numbers\n- `type`: Filter by file type (e.g., \"js\", \"py\", \"rust\")\n- `glob`: Filter by glob pattern (e.g., \"*.test.ts\")\n\n**Fast and Powerful:** Uses ripgrep under the hood, much faster than bash grep on large codebases.\n\n#### Glob Tool\n**Purpose:** Find files by pattern\n\n```bash\n# Find test files\nGlob pattern=\"**\u002F*.test.ts\"\n\n# Find specific extensions\nGlob pattern=\"src\u002F**\u002F*.{ts,tsx}\"\n\n# Find config files\nGlob pattern=\"**\u002Fconfig.{json,yaml,yml}\"\n```\n\n**Features:**\n- Fast pattern matching (works with any codebase size)\n- Returns files sorted by modification time (recent first)\n- Supports complex glob patterns (`**` for recursive, `{}` for alternatives)\n\n#### TodoWrite Tool\n**Purpose:** Manage task lists during work\n\n```bash\nTodoWrite todos=[\n  {\n    \"content\": \"Add authentication endpoint\",\n    \"status\": \"in_progress\",\n    \"activeForm\": \"Adding authentication endpoint\"\n  },\n  {\n    \"content\": \"Write integration tests\",\n    \"status\": \"pending\",\n    \"activeForm\": \"Writing integration tests\"\n  },\n  {\n    \"content\": \"Update API documentation\",\n    \"status\": \"pending\",\n    \"activeForm\": \"Updating API documentation\"\n  }\n]\n```\n\n**Task States:**\n- `\"pending\"` - Not started yet\n- `\"in_progress\"` - Currently working on (should be only ONE at a time)\n- `\"completed\"` - Finished successfully\n\n**Dependency Tracking** [NEW]: v2.1.16 introduced task dependency tracking, allowing tasks to define prerequisites that must complete before they start. This enables complex multi-step workflows with proper sequencing.\n\n**Best Practices:**\n- Use for multi-step tasks (3+ steps)\n- Keep ONE task `in_progress` at a time\n- Mark completed IMMEDIATELY after finishing\n- Use descriptive `content` (what to do) and `activeForm` (what you're doing)\n\n**When to Use:**\n- ✅ Complex multi-step features\n- ✅ User provides multiple tasks\n- ✅ Non-trivial work requiring planning\n- ❌ Single straightforward tasks\n- ❌ Trivial operations\n\n#### Task Tool (Sub-Agents)\n**Purpose:** Launch specialized AI agents for specific tasks\n\n```bash\n# Explore codebase\nTask subagent_type=\"Explore\"\n     prompt=\"Find all API endpoints and their authentication requirements\"\n\n# General purpose agent for complex tasks\nTask subagent_type=\"general-purpose\"\n     prompt=\"Research best practices for rate limiting APIs and implement a solution\"\n```\n\n**Available Sub-Agent Types:**\n- `\"general-purpose\"` - Complex multi-step tasks, research, implementation\n- `\"Explore\"` - Fast codebase exploration (Glob, Grep, Read, Bash)\n\n**When to Use:**\n- Research tasks requiring web search + analysis\n- Codebase exploration (finding patterns, understanding architecture)\n- Complex multi-step operations that can run independently\n- Background work while you continue other tasks\n\n#### WebFetch Tool\n**Purpose:** Fetch and analyze web page content\n\n```bash\nWebFetch url=\"https:\u002F\u002Fdocs.example.com\u002Fapi\"\n         prompt=\"Extract all endpoint documentation\"\n```\n\n**Features:**\n- Converts HTML to markdown for analysis\n- Can extract specific information with prompt\n- Useful for researching docs, articles, references\n\n#### WebSearch Tool\n**Purpose:** Search the web for current information\n\n```bash\nWebSearch query=\"React 19 new features 2024\"\n```\n\n**Use Cases:**\n- Research current best practices\n- Find up-to-date library documentation\n- Check for known issues or solutions\n- Verify latest framework features\n\n**Source:** [CLI Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference), [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n#### LSP Tool (Language Server Protocol) [OFFICIAL]\n**Purpose:** Get code intelligence features like go-to-definition, find references, and hover documentation.\n\n```bash\nLSP operation=\"goToDefinition\"\n    filePath=\"src\u002Futils\u002Fauth.ts\"\n    line=42\n    character=15\n```\n\n**Available Operations:**\n| Operation | Description |\n|-----------|-------------|\n| `goToDefinition` | Find where a symbol is defined |\n| `findReferences` | Find all references to a symbol |\n| `hover` | Get documentation and type info for a symbol |\n| `documentSymbol` | Get all symbols in a document (functions, classes, variables) |\n| `workspaceSymbol` | Search for symbols across the entire workspace |\n| `goToImplementation` | Find implementations of an interface or abstract method |\n| `prepareCallHierarchy` | Get call hierarchy item at a position |\n| `incomingCalls` | Find all functions\u002Fmethods that call the function at a position |\n| `outgoingCalls` | Find all functions\u002Fmethods called by the function at a position |\n\n**Parameters:**\n- `operation` (required): The LSP operation to perform\n- `filePath` (required): Absolute or relative path to the file\n- `line` (required): Line number (1-based, as shown in editors)\n- `character` (required): Character offset (1-based, as shown in editors)\n\n**Use Cases:**\n```bash\n# Find where a function is defined\n> \"Go to the definition of getUserById\"\n\n# Find all usages of a function\n> \"Find all references to the authenticate function\"\n\n# Get documentation for a symbol\n> \"What does the validateToken function do?\"\n\n# Explore code structure\n> \"List all symbols in the auth.ts file\"\n```\n\n**Note:** LSP servers must be configured for the file type. If no server is available for a language, an error will be returned.\n\n**Source:** [CLI Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n### 5. Context Management [OFFICIAL]\n\nClaude Code maintains conversation context with smart management:\n\n#### Context Commands\n\n```bash\n\u002Fcompact                   # Reduce context by removing old information\n\u002Fcompact \"keep auth work\"  # Compact with focus instructions (keeps specified context)\n```\n\n#### When to Use\n\n**Use \u002Fcompact when:**\n- Long sessions with many file reads\n- \"Context too large\" errors\n- You've completed a major task and want to start fresh\n\n**Use \u002Fcompact with instructions when:**\n- Context is getting large but you want to preserve recent work\n- Switching between related tasks\n- You want intelligent cleanup without losing important context\n- Example: `\u002Fcompact \"keep the authentication implementation context\"`\n\n#### What Gets Preserved vs Cleared\n\n**Preserved:**\n- CLAUDE.md content (your project context)\n- Recent interactions and decisions\n- Current task information and todos\n- Recent file reads still relevant\n\n**Cleared:**\n- Old file reads no longer needed\n- Completed operations\n- Stale search results\n- Old context no longer relevant\n\n#### Automatic Context Management\n\nClaude Code may automatically compact when:\n- Token limit is approaching\n- Many old file reads are present\n- Session has been very long\n\n**Source:** [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n### 6. Workspace Management [OFFICIAL]\n\n#### Adding Directories with \u002Fadd-dir\n\nClaude Code can work with multiple directories simultaneously:\n\n```bash\n# Add another directory to current session\n\u002Fadd-dir \u002Fpath\u002Fto\u002Fother\u002Fproject\n\n# Work across multiple projects\n> \"Update the User type in backend and propagate to frontend\"\n# Claude can now access both directories\n```\n\n**Use Cases:**\n- Monorepo development (frontend + backend + shared libs)\n- Cross-project refactoring\n- Dependency updates across multiple projects\n- Coordinating changes between related repositories\n\n**Configuration:**\n\nYou can also pre-configure additional directories in `.claude\u002Fsettings.json`:\n\n```json\n{\n  \"permissions\": {\n    \"additionalDirectories\": [\n      \"\u002Fpath\u002Fto\u002Ffrontend\",\n      \"\u002Fpath\u002Fto\u002Fbackend\",\n      \"\u002Fpath\u002Fto\u002Fshared-libs\"\n    ]\n  }\n}\n```\n\n#### Status Line Configuration with \u002Fstatusline\n\nCustomize what information appears in your status line:\n\n```bash\n# Configure status line\n\u002Fstatusline\n\n# Options typically include:\n# - Current model\n# - Token usage\n# - Session duration\n# - Active tools\n# - Background processes\n```\n\n**Benefits:**\n- Monitor token usage in real-time\n- Track session duration\n- See active background processes\n- Understand which tools are being used\n\n**Source:** [CLI Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n---\n\n## Quick Start Guide\n\n### Your First Session\n\n```bash\n# 1. Navigate to your project\ncd \u002Fpath\u002Fto\u002Fyour\u002Fproject\n\n# 2. Start Claude Code\nclaude\n\n# 3. Ask Claude to understand your project\n> \"Read the codebase and explain the project structure\"\n\n# Claude will:\n- Look for README, package.json, or similar entry points\n- Read relevant files (asks permission first time)\n- Analyze the code structure\n- Provide a summary\n\n# 4. Request an analysis\n> \"Review the authentication system for security issues\"\n\n# Claude will:\n- Find authentication-related files\n- Analyze the implementation\n- Identify potential vulnerabilities\n- Suggest improvements\n\n# 5. Make changes\n> \"Add rate limiting to the login endpoint\"\n\n# Claude will:\n- Plan the implementation\n- Show you what changes will be made\n- Request permission to edit files\n- Implement the changes\n- Can run tests to verify\n\n# 6. Create a commit\n> \"Create a git commit for these changes\"\n\n# Claude will:\n- Run git status to see changes\n- Review git diff\n- Create a descriptive commit message\n- Commit the changes\n```\n\n### Setting Up Your Project for Claude Code\n\n#### 1. Create CLAUDE.md [COMMUNITY]\n\nThis provides context that persists across all sessions:\n\n```bash\n# Ask Claude to help create it\n> \"Create a CLAUDE.md file documenting this project's structure, commands, and conventions\"\n\n# Or create manually with:\n- Languages and frameworks used\n- Important commands (dev, test, build, lint)\n- Project structure overview\n- Coding conventions\n- Known gotchas or issues\n```\n\n#### 2. Configure Permissions (Optional) [OFFICIAL]\n\nCreate `.claude\u002Fsettings.json` in your project:\n\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"ask\",\n    \"allow\": {\n      \"Bash\": [\n        \"npm test\",\n        \"npm run*\",\n        \"git status\",\n        \"git diff\",\n        \"git log*\"\n      ],\n      \"Read\": {},\n      \"Grep\": {},\n      \"Glob\": {}\n    },\n    \"deny\": {\n      \"Write\": [\"*.env\", \".env.*\"],\n      \"Edit\": [\"*.env\", \".env.*\", \".git\u002F*\"]\n    }\n  }\n}\n```\n\nThis configuration:\n- Allows common safe commands without asking\n- Blocks editing sensitive files\n- Still asks permission for file modifications\n\n#### 3. Test the Setup\n\n```bash\n> \"Run the tests\"\n# Should execute without permission prompt (if configured)\n\n> \"What commands are available?\"\n# Claude will read package.json and list scripts\n\n> \"What's in CLAUDE.md?\"\n# Claude will read and summarize your project context\n```\n\n**Source:** [Quickstart](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fquickstart), [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n---\n\n## Advanced Features\n\n### Thinking Mode [OFFICIAL]\n\nClaude Code supports extended thinking for complex reasoning tasks. Opus 4.5 has thinking mode enabled by default.\n\n**Activation Methods:**\n\n```bash\n# Toggle with keyboard shortcut\nAlt+T (or Option+T on macOS)  # Toggle thinking on\u002Foff\n\n# Or use natural language\n> \"think about this problem\"\n> \"think harder about the architecture\"\n> \"ultrathink about this security issue\"\n\n# Tab key (sticky toggle)\nPress Tab to toggle thinking mode on\u002Foff for subsequent prompts\n```\n\n**Thinking Levels:**\n| Trigger | Thinking Budget | Use Case |\n|---------|----------------|----------|\n| `think` | Standard | General reasoning, code analysis |\n| `think harder` | Extended | Complex problems, multiple approaches |\n| `ultrathink` | Maximum | Critical decisions, deep architecture analysis |\n\n**Best Practices:**\n- Use `think harder` for debugging complex issues\n- Use `ultrathink` for architectural decisions or security reviews\n- Thinking content is visible in `Ctrl+O` transcript mode\n- Thinking mode is sticky - stays on until toggled off\n\n**Source:** [Thinking Mode](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fthinking-mode)\n\n### Fast Mode [NEW] [OFFICIAL]\n\nFast mode is a high-speed configuration for Claude Opus 4.6, making responses **2.5x faster** at a higher cost per token. Available since v2.1.36.\n\n**Toggle Fast Mode:**\n```bash\n# Toggle with built-in command\n\u002Ffast          # Toggle on\u002Foff\n\n# Or set in settings\n\"fastMode\": true   # In user settings file\n```\n\n**Visual Indicators:**\n- `↯` icon appears next to prompt when fast mode is active\n- Icon turns gray during rate limit cooldown\n\n**Pricing (per MTok):**\n| Mode | Input (\u003C200K) | Output | Input (>200K) | Output |\n|------|--------------|--------|---------------|--------|\n| Standard Opus 4.6 | $15 | $75 | $15 | $75 |\n| Fast Mode | $30 | $150 | $60 | $225 |\n\n**Note:** Fast mode is available at 50% discount until February 16, 2026.\n\n**Requirements:**\n- Claude subscription plan (Pro\u002FMax\u002FTeam\u002FEnterprise) or Claude Console API\n- Extra usage enabled (`\u002Fextra-usage`)\n- Not available on third-party providers (Bedrock, Vertex, Azure Foundry)\n- For Teams\u002FEnterprise: Admin must enable in organization settings\n\n**When to Use:**\n- ✅ Rapid iteration on code changes\n- ✅ Live debugging sessions\n- ✅ Time-sensitive work\n- ❌ Long autonomous tasks (cost matters more)\n- ❌ Batch processing or CI\u002FCD pipelines\n\n**Fast Mode vs Effort Level:**\n| Setting | Effect |\n|---------|--------|\n| **Fast mode** | Same quality, lower latency, higher cost |\n| **Lower effort level** | Faster responses, potentially lower quality |\n\nYou can combine both for maximum speed on straightforward tasks.\n\n**Rate Limits:**\n- Separate rate limits from standard Opus 4.6\n- Automatically falls back to standard mode during cooldown\n- Re-enables when cooldown expires\n\n**Source:** [Fast Mode](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Ffast-mode)\n\n### Plan Mode [OFFICIAL]\n\nPlan Mode provides structured planning with model selection for complex tasks.\n\n```bash\n# Enter plan mode\n\u002Fplan\n\n# Or Claude may suggest plan mode for complex tasks\n> \"Implement a complete authentication system\"\n# Claude: \"This is a complex task. Would you like me to create a plan first?\"\n```\n\n**Plan Mode Features:**\n- **Opus planning, Sonnet execution** - Uses stronger model for planning, faster model for implementation\n- **SonnetPlan Mode** - Sonnet planning, Haiku execution (cost-effective)\n- **Shift+Tab** - Auto-accept edits in plan mode\n- **Plan persistence** - Plans persist across `\u002Fclear`\n\n**Plan Mode Workflow:**\n1. Claude analyzes the task and creates a structured plan\n2. You review and approve or modify the plan\n3. Claude executes the plan step by step\n4. Progress is tracked with TodoWrite\n\n**Source:** [Plan Mode](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fplan-mode)\n\n### Background Tasks & Agents [OFFICIAL]\n\nRun commands and agents in the background while continuing to work.\n\n**Keyboard Shortcut:**\n```bash\nCtrl+B  # Background current command or agent (unified shortcut)\n```\n\n**Background Commands:**\n```bash\n# Start command in background\n> \"Run the dev server in background\"\n> \"Start tests in watch mode in background\"\n\n# Or prefix with &\n> \"& npm run dev\"\n\n# View background tasks\n\u002Ftasks\n\u002Fbashes\n\n# Kill a background task\n\u002Fkill \u003Ctask-id>\n```\n\n**Background Agents:**\n```bash\n# Launch agent in background\n> \"Have an Explore agent analyze the codebase architecture in background\"\n\n# Agents run asynchronously and notify you when complete\n# You receive wake-up messages when background agents finish\n```\n\n**Features:**\n- Real-time output streaming to status line\n- Wake-up notifications when tasks complete\n- Multiple concurrent background processes\n- Output persisted to files for large outputs\n\n**Source:** [Background Tasks](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fbackground-tasks)\n\n### Auto-Memory [NEW]\n\nClaude Code now automatically records and recalls memories as it works (v2.1.32+).\n\n**How It Works:**\n- Claude automatically remembers important context, decisions, and patterns\n- Memories persist across sessions and inform future work\n- No manual intervention required\n\n**Memory Scopes for Agents:**\n```markdown\n---\nname: my-agent\nmemory: project  # Options: user, project, local\n---\n```\n\n| Scope | Storage | Shared |\n|-------|---------|--------|\n| `user` | `~\u002F.claude\u002F` | All your projects |\n| `project` | `.claude\u002F` | Team via git |\n| `local` | `.claude\u002F*.local.*` | No (gitignored) |\n\n**Disable Auto-Memory:**\n```bash\nexport CLAUDE_CODE_DISABLE_AUTO_MEMORY=1\n```\n\n### Keyboard Shortcuts [OFFICIAL]\n\n**Navigation & Editing:**\n| Shortcut | Action |\n|----------|--------|\n| `Ctrl+R` | Search command history |\n| `Ctrl+O` | View transcript (shows thinking blocks) |\n| `Ctrl+G` | Edit prompt in system text editor |\n| `Ctrl+Y` | Readline-style paste (yank) |\n| `Alt+Y` | Yank-pop (cycle through kill ring) |\n| `Ctrl+B` | Background current command\u002Fagent |\n| `Ctrl+Z` | Suspend\u002FUndo |\n\n**Model & Mode Switching:**\n| Shortcut | Action |\n|----------|--------|\n| `Alt+P` (Win\u002FLinux) \u002F `Option+P` (macOS) | Switch models while typing |\n| `Alt+T` (Win\u002FLinux) \u002F `Option+T` (macOS) | Toggle thinking mode |\n| `Tab` | Toggle thinking (sticky) \u002F Accept suggestions |\n| `Shift+Tab` | Auto-accept edits (plan mode) \u002F Switch modes (Windows) |\n\n**Input & Submission:**\n| Shortcut | Action |\n|----------|--------|\n| `Enter` | Submit prompt \u002F Accept suggestion immediately |\n| `Shift+Enter` | New line (works in iTerm2, WezTerm, Ghostty, Kitty) |\n| `Tab` | Edit\u002Faccept prompt suggestion |\n| `Ctrl+T` | Toggle syntax highlighting in `\u002Ftheme` |\n\n**Image & File Handling:**\n| Shortcut | Action |\n|----------|--------|\n| `Cmd+V` (macOS) \u002F `Alt+V` (Windows) | Paste image from clipboard |\n| `Cmd+N` \u002F `Ctrl+N` | New conversation (VSCode) |\n\n**Vim Bindings (if enabled):**\n| Shortcut | Action |\n|----------|--------|\n| `;` and `,` | Repeat last motion |\n| `y` | Yank operator |\n| `p` \u002F `P` | Paste |\n| `Alt+B` \u002F `Alt+F` | Word navigation |\n\n**Login & Authentication:**\n| Shortcut | Action |\n|----------|--------|\n| `c` | Copy OAuth URL during login |\n\n**Bash Mode Autocomplete** [NEW v2.1.14]:\n| Shortcut | Action |\n|----------|--------|\n| `!` + `Tab` | History-based autocomplete - complete partial commands from history |\n\n### Prompt Suggestions [OFFICIAL]\n\nClaude Code suggests prompts based on context (enabled by default).\n\n```bash\n# Claude suggests contextual prompts\n> _  # Cursor blinking\n# Suggestion appears: \"Review the changes we made\"\n\n# Tab to edit the suggestion\nTab → Edit the suggestion text\n\n# Enter to submit immediately\nEnter → Submit the suggestion as-is\n```\n\n**Configuration:**\n```bash\n# Toggle in \u002Fconfig\n\u002Fconfig\n# Search for \"prompt suggestions\"\n# Toggle enable\u002Fdisable\n```\n\n### Environment Variables [OFFICIAL]\n\n**Core Configuration:**\n| Variable | Description |\n|----------|-------------|\n| `ANTHROPIC_API_KEY` | Your API key |\n| `CLAUDE_CODE_SHELL` | Override shell detection |\n| `CLAUDE_CODE_TMPDIR` | Custom temp directory |\n| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Disable background task system |\n| `CLAUDE_CODE_ENABLE_TASKS` | Set to `false` to use legacy task system [NEW v2.1.19] |\n\n**Display & UI:**\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_CODE_HIDE_ACCOUNT_INFO` | Hide account info in UI |\n\n**Bash & Commands:**\n| Variable | Description |\n|----------|-------------|\n| `BASH_DEFAULT_TIMEOUT_MS` | Default bash command timeout |\n| `BASH_MAX_TIMEOUT_MS` | Maximum allowed timeout |\n| `CLAUDE_BASH_NO_LOGIN` | Don't use login shell |\n| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | Keep working directory |\n| `CLAUDE_CODE_SHELL_PREFIX` | Prefix for shell commands |\n\n**Model Configuration:**\n| Variable | Description |\n|----------|-------------|\n| `ANTHROPIC_DEFAULT_SONNET_MODEL` | Override default Sonnet model |\n| `ANTHROPIC_DEFAULT_OPUS_MODEL` | Override default Opus model |\n| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | Override default Haiku model |\n| `ANTHROPIC_LOG` | Enable debug logging |\n\n**MCP Configuration:**\n| Variable | Description |\n|----------|-------------|\n| `MCP_TIMEOUT` | MCP connection timeout |\n| `MCP_TOOL_TIMEOUT` | Individual tool timeout |\n\n**File & Context:**\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | Max tokens for file reads |\n| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | Set to `1` to load CLAUDE.md from `--add-dir` directories [NEW] |\n| `CLAUDE_PROJECT_DIR` | Override project directory |\n| `CLAUDE_PLUGIN_ROOT` | Plugin root substitution |\n| `CLAUDE_CONFIG_DIR` | Custom config directory |\n| `XDG_CONFIG_HOME` | XDG config base path |\n\n**Network & Proxy:**\n| Variable | Description |\n|----------|-------------|\n| `NODE_EXTRA_CA_CERTS` | Custom CA certificates |\n| `NO_PROXY` | Proxy bypass list |\n| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | Proxy DNS resolution |\n\n**Auto-Update & Plugins:**\n| Variable | Description |\n|----------|-------------|\n| `DISABLE_AUTOUPDATER` | Disable auto-updates |\n| `FORCE_AUTOUPDATE_PLUGINS` | Force plugin updates |\n| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | Exit delay after stop |\n\n**Monitoring & Telemetry:**\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_CODE_ENABLE_TELEMETRY` | Enable OpenTelemetry collection (`1`) |\n| `OTEL_METRICS_EXPORTER` | OTel metrics exporter (e.g., `otlp`) |\n| `DISABLE_TELEMETRY` | Opt out of Statsig telemetry (`1`) |\n| `DISABLE_ERROR_REPORTING` | Opt out of Sentry error reporting (`1`) |\n| `DISABLE_COST_WARNINGS` | Disable cost warning messages (`1`) |\n\n**Advanced:**\n| Variable | Description |\n|----------|-------------|\n| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | Disable anthropic-beta headers (workaround for gateway users) |\n| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | Enable agent teams feature (`1`) [NEW] |\n| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | Disable automatic memory recording (`1`) [NEW] |\n| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | Disable background task system (`1`) |\n| `DISABLE_INTERLEAVED_THINKING` | Disable interleaved thinking |\n| `USE_BUILTIN_RIPGREP` | Use built-in ripgrep |\n| `CLOUD_ML_REGION` | Cloud ML region for Vertex |\n| `AWS_BEARER_TOKEN_BEDROCK` | AWS bearer token |\n| `MAX_THINKING_TOKENS` | Extended thinking budget (default: 31,999) |\n| `MAX_MCP_OUTPUT_TOKENS` | Max MCP tool response tokens (default: 25,000) |\n| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | Max output tokens (default: 32,000, max: 64,000) |\n| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | Disable autoupdate, bug reporting, telemetry |\n\n### New Settings [OFFICIAL]\n\nRecent settings additions (configure in `\u002Fconfig` or `settings.json`):\n\n```json\n{\n  \u002F\u002F Response language\n  \"language\": \"en\",  \u002F\u002F Claude's response language\n\n  \u002F\u002F Git integration\n  \"attribution\": true,  \u002F\u002F Add model name to commit bylines\n  \"respectGitignore\": true,  \u002F\u002F Respect .gitignore in searches\n\n  \u002F\u002F UI preferences\n  \"showTurnDuration\": true,  \u002F\u002F Show turn duration messages\n  \"fileSuggestion\": \"custom-cmd\",  \u002F\u002F Custom @ file search command\n  \"spinnerVerbs\": [\"analyzing\", \"thinking\", \"processing\"],  \u002F\u002F Custom spinner verbs\n  \"prefersReducedMotion\": false,  \u002F\u002F Reduce UI animations for accessibility [NEW v2.1.30]\n\n  \u002F\u002F Session behavior\n  \"companyAnnouncements\": true,  \u002F\u002F Show startup announcements\n\n  \u002F\u002F Plan mode\n  \"plansDirectory\": \".claude\u002Fplans\"  \u002F\u002F Custom directory for plan files\n}\n```\n\n**Skills Variable Substitution:** [NEW]\n```markdown\n# In skill files, use ${CLAUDE_SESSION_ID} for session-specific operations\nSession ID: ${CLAUDE_SESSION_ID}\n```\n\n**Project Rules:**\n```bash\n# New: .claude\u002Frules\u002F directory for project-specific rules\n.claude\u002Frules\u002F\n├── coding-style.md      # Coding conventions\n├── testing.md           # Testing requirements\n└── security.md          # Security guidelines\n```\n\n**Wildcard Permissions:**\n```json\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": [\"npm *\", \"git *\"],  \u002F\u002F Wildcard patterns\n      \"mcp__myserver__*\": {}       \u002F\u002F MCP tool wildcards\n    }\n  }\n}\n```\n\n---\n\n## Skills System\n\n**Skills are unified capabilities that extend Claude Code — both auto-activated by Claude and manually invoked via `\u002Fskill-name`.**\n\n> **Note:** Custom slash commands (`.claude\u002Fcommands\u002F` files) have been merged into skills as of v2.1.3. Your existing command files keep working unchanged. Skills are recommended for new work because they support additional features like supporting files, invocation control, and subagent execution. See [Migration: Commands to Skills](#migration-commands-to-skills).\n\nClaude Code skills follow the [Agent Skills](https:\u002F\u002Fagentskills.io) open standard, which works across multiple AI tools. Claude Code extends the standard with additional features like invocation control, subagent execution, and dynamic context injection.\n\n### What Are Skills? [OFFICIAL]\n\nSkills are instructions packaged as `SKILL.md` files that extend what Claude Code can do. Claude loads them when relevant to your request, or you invoke them directly:\n\n```\n# Claude auto-activates a skill based on your request\nYou: \"Review this code for security issues\"\nClaude: [Loads security-reviewer skill automatically]\n\n# Or you invoke a skill directly\nYou: \u002Fsecurity-reviewer src\u002Fauth.ts\nClaude: [Loads and executes the security-reviewer skill]\n```\n\n**Two types of skill content:**\n\n- **Reference content** — Knowledge Claude applies to your current work (conventions, patterns, style guides). Runs inline alongside your conversation context.\n- **Task content** — Step-by-step instructions for a specific action (deploy, commit, code generation). Often invoked manually with `\u002Fskill-name`.\n\n### Where Skills Live [OFFICIAL]\n\nWhere you store a skill determines who can use it:\n\n| Location | Path | Applies To |\n|----------|------|------------|\n| **Enterprise** | [Managed settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fpermissions#managed-settings) | All users in organization |\n| **Personal** | `~\u002F.claude\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md` | All your projects |\n| **Project** | `.claude\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md` | This project only |\n| **Plugin** | `\u003Cplugin>\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md` | Where plugin is enabled |\n\nWhen skills share the same name, higher-priority locations win: **Enterprise > Personal > Project**. Plugin skills use a `plugin-name:skill-name` namespace, so they cannot conflict.\n\n**Legacy compatibility:** Files in `.claude\u002Fcommands\u002F` still work and support the same frontmatter. If a skill and a command share the same name, the skill takes precedence.\n\n**Automatic nested directory discovery:** When you work with files in subdirectories, Claude Code discovers skills from nested `.claude\u002Fskills\u002F` directories. For example, editing a file in `packages\u002Ffrontend\u002F` also loads skills from `packages\u002Ffrontend\u002F.claude\u002Fskills\u002F`. This supports monorepo setups where packages have their own skills.\n\n**Live change detection:** Skills from directories added via `--add-dir` are loaded automatically and picked up by live change detection — edit them during a session without restarting.\n\n### Skill Directory Structure [OFFICIAL]\n\nEach skill is a directory with `SKILL.md` as the entrypoint:\n\n```\nmy-skill\u002F\n├── SKILL.md           # Main instructions (required)\n├── template.md        # Template for Claude to fill in (optional)\n├── examples\u002F\n│   └── sample.md      # Example output (optional)\n└── scripts\u002F\n    └── validate.sh    # Script Claude can execute (optional)\n```\n\nReference supporting files from your `SKILL.md` so Claude knows what each file contains:\n\n```markdown\n## Additional resources\n- For complete API details, see [reference.md](reference.md)\n- For usage examples, see [examples.md](examples.md)\n```\n\n> **Tip:** Keep `SKILL.md` under 500 lines. Move detailed reference material to separate files.\n\n### Creating a Skill [OFFICIAL]\n\n**Step 1:** Create the skill directory:\n```bash\n# Personal skill (available in all projects)\nmkdir -p ~\u002F.claude\u002Fskills\u002Fexplain-code\n\n# Project skill (shared with team via git)\nmkdir -p .claude\u002Fskills\u002Fexplain-code\n```\n\n**Step 2:** Write `SKILL.md` with frontmatter and instructions:\n```yaml\n---\nname: explain-code\ndescription: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks \"how does this work?\"\n---\n\nWhen explaining code, always include:\n\n1. **Start with an analogy**: Compare the code to something from everyday life\n2. **Draw a diagram**: Use ASCII art to show the flow, structure, or relationships\n3. **Walk through the code**: Explain step-by-step what happens\n4. **Highlight a gotcha**: What's a common mistake or misconception?\n\nKeep explanations conversational. For complex concepts, use multiple analogies.\n```\n\n**Step 3:** Test the skill:\n```bash\n# Let Claude invoke it automatically\n> \"How does this code work?\"\n\n# Or invoke it directly\n> \u002Fexplain-code src\u002Fauth\u002Flogin.ts\n```\n\n### Frontmatter Reference [OFFICIAL]\n\nConfigure skill behavior with YAML frontmatter between `---` markers at the top of `SKILL.md`. All fields are optional; only `description` is recommended.\n\n| Field | Required | Description |\n|-------|----------|-------------|\n| `name` | No | Display name. If omitted, uses directory name. Lowercase letters, numbers, hyphens (max 64 chars). |\n| `description` | Recommended | What the skill does and when to use it. Claude uses this to decide when to load it. |\n| `argument-hint` | No | Hint shown during autocomplete (e.g., `[issue-number]` or `[filename] [format]`). |\n| `disable-model-invocation` | No | `true` → only user can invoke via `\u002Fname`. Default: `false`. |\n| `user-invocable` | No | `false` → hidden from `\u002F` menu, only Claude can invoke. Default: `true`. |\n| `allowed-tools` | No | Tools Claude can use without asking permission when skill is active. |\n| `model` | No | Model to use when skill is active. |\n| `context` | No | Set to `fork` to run in a forked subagent context. |\n| `agent` | No | Which subagent type to use when `context: fork` is set. |\n| `hooks` | No | Hooks scoped to this skill's lifecycle. See [Hooks](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks#hooks-in-skills-and-agents). |\n\n### Controlling Invocation [OFFICIAL]\n\nBy default, both you and Claude can invoke any skill. Two frontmatter fields restrict this:\n\n- **`disable-model-invocation: true`** — Only you can invoke. Use for workflows with side effects (e.g., `\u002Fdeploy`, `\u002Fcommit`).\n- **`user-invocable: false`** — Only Claude can invoke. Use for background knowledge that isn't actionable as a command.\n\n```yaml\n# User-only skill (Claude won't auto-trigger)\n---\nname: deploy\ndescription: Deploy the application to production\ndisable-model-invocation: true\n---\n\n# Model-only skill (hidden from \u002F menu)\n---\nname: legacy-system-context\ndescription: Background knowledge about the legacy system\nuser-invocable: false\n---\n```\n\n**Invocation and context-loading behavior:**\n\n| Frontmatter | You Can Invoke | Claude Can Invoke | When Loaded into Context |\n|-------------|----------------|-------------------|--------------------------|\n| (default) | Yes | Yes | Description always in context; full skill loads when invoked |\n| `disable-model-invocation: true` | Yes | No | Description not in context; full skill loads when you invoke |\n| `user-invocable: false` | No | Yes | Description always in context; full skill loads when invoked |\n\n**Restricting Claude's access via `\u002Fpermissions`:**\n\n```bash\n# Allow only specific skills\nSkill(commit)\nSkill(review-pr *)\n\n# Deny specific skills\nSkill(deploy *)\n\n# Disable all skills\nSkill    # Add to deny rules\n```\n\nPermission syntax: `Skill(name)` for exact match, `Skill(name *)` for prefix match with any arguments.\n\n### Passing Arguments [OFFICIAL]\n\nSkills accept arguments via placeholder substitutions:\n\n| Variable | Description |\n|----------|-------------|\n| `$ARGUMENTS` | All arguments passed when invoking the skill |\n| `$ARGUMENTS[N]` | Specific argument by 0-based index (e.g., `$ARGUMENTS[0]`) |\n| `$N` | Shorthand for `$ARGUMENTS[N]` (e.g., `$0`, `$1`) |\n| `${CLAUDE_SESSION_ID}` | Current session ID (useful for logging) |\n\n**Example:**\n```yaml\n---\nname: fix-issue\ndescription: Fix a GitHub issue\ndisable-model-invocation: true\n---\n\nFix GitHub issue $ARGUMENTS following our coding standards.\n\n1. Read the issue description\n2. Implement the fix\n3. Write tests\n4. Create a commit\n```\n\n```bash\n\u002Ffix-issue 123\n# Claude receives: \"Fix GitHub issue 123 following our coding standards...\"\n```\n\n**Indexed arguments:**\n```yaml\n---\nname: compare-files\ndescription: Compare two files\n---\n\n# Compare: $ARGUMENTS[0] vs $ARGUMENTS[1]\n# Shorthand: $0 vs $1\n\nCompare $0 and $1 for differences.\n```\n\n```bash\n\u002Fcompare-files \"src\u002Fv1\u002Fapi.ts\" \"src\u002Fv2\u002Fapi.ts\"\n# $0 = \"src\u002Fv1\u002Fapi.ts\", $1 = \"src\u002Fv2\u002Fapi.ts\"\n```\n\nIf `$ARGUMENTS` is not present in the skill content, arguments are appended as `ARGUMENTS: \u003Cvalue>`.\n\n### Advanced Patterns [OFFICIAL]\n\n#### Dynamic Context Injection\n\nThe `` !`command` `` syntax runs shell commands before the skill content is sent to Claude. The output replaces the placeholder:\n\n```yaml\n---\nname: pr-summary\ndescription: Summarize changes in a pull request\ncontext: fork\nagent: Explore\nallowed-tools: Bash(gh *)\n---\n\n## Pull request context\n- PR diff: !`gh pr diff`\n- PR comments: !`gh pr view --comments`\n- Changed files: !`gh pr diff --name-only`\n\n## Your task\nSummarize this pull request...\n```\n\nEach `` !`command` `` executes immediately (before Claude sees anything). Claude only sees the final result with actual data.\n\n#### Running in a Subagent\n\nAdd `context: fork` to run a skill in isolation. The skill content becomes the prompt that drives the subagent (no access to conversation history):\n\n```yaml\n---\nname: deep-research\ndescription: Research a topic thoroughly\ncontext: fork\nagent: Explore\n---\n\nResearch $ARGUMENTS thoroughly:\n\n1. Find relevant files using Glob and Grep\n2. Read and analyze the code\n3. Summarize findings with specific file references\n```\n\nThe `agent` field specifies which subagent to use. Options: built-in agents (`Explore`, `Plan`, `general-purpose`) or custom subagents from `.claude\u002Fagents\u002F`. Default: `general-purpose`.\n\n> **Warning:** `context: fork` only makes sense for skills with explicit instructions. Guidelines without a task will return without meaningful output.\n\n#### Extended Thinking\n\nTo enable extended thinking in a skill, include the word `ultrathink` anywhere in your skill content:\n\n```yaml\n---\nname: architecture-review\ndescription: Deep architectural analysis\n---\n\nUse ultrathink to analyze the architecture deeply.\n\nReview the overall structure, identify patterns, and suggest improvements.\n```\n\n### Practical Examples\n\n**Example: Code Review Skill**\n\n`.claude\u002Fskills\u002Fcode-reviewer\u002FSKILL.md`:\n```yaml\n---\nname: code-reviewer\ndescription: Reviews code for security vulnerabilities, bugs, performance issues, and style problems. Use when user asks to review, audit, or check code quality.\nallowed-tools: [Read, Grep, Glob]\n---\n\n# Code Review Skill\n\n## When to Activate\nUse this skill when the user asks to:\n- Review code for issues\n- Audit security or find vulnerabilities\n- Check code quality or best practices\n\n## Review Process\n\n### 1. Scope Detection\n- Use Glob to identify files to review\n- Prioritize recently modified files\n- Focus on user-specified areas if mentioned\n\n### 2. Analysis Layers\n- **Security**: SQL injection, XSS, auth issues, exposed secrets\n- **Bugs**: Logic errors, null checks, error handling\n- **Performance**: N+1 queries, unnecessary loops, memory leaks\n- **Style**: Naming conventions, code organization, readability\n\n### 3. Reporting\nProvide structured feedback organized by severity:\n- **Critical\u002FHigh**: Security issues\n- **Medium**: Performance issues\n- **Low**: Style and best practices\n\nEach issue: file path, description, and fix suggestion.\n```\n\n**Example: Test Generator Skill**\n\n`.claude\u002Fskills\u002Ftest-generator\u002FSKILL.md`:\n```yaml\n---\nname: test-generator\ndescription: Generates comprehensive unit and integration tests. Use when user asks to write tests, add test coverage, or create test cases.\nallowed-tools: [Read, Write, Grep, Glob, Bash]\n---\n\n# Test Generator Skill\n\n## When to Activate\nUse this skill when user requests:\n- \"Write tests for...\"\n- \"Add test coverage\"\n- \"Generate test cases\"\n\n## Test Generation Process\n\n### 1. Analyze Target Code\n- Read the file\u002Ffunction to test\n- Identify inputs, outputs, side effects\n- Check existing test patterns\n\n### 2. Generate Comprehensive Tests\nCover all scenarios:\n- Happy path (expected usage)\n- Error cases (invalid inputs)\n- Edge cases (empty, null, boundary values)\n- Side effects (database, API calls)\n\n### 3. Follow Project Patterns\n- Check CLAUDE.md for testing conventions\n- Match existing test file structure\n- Use project's test framework\n```\n\n**Example: Security Review Skill**\n\n`.claude\u002Fskills\u002Fsecurity-review\u002FSKILL.md`:\n```yaml\n---\nname: security-review\ndescription: Comprehensive security audit of codebase. Use when asked to review security, audit vulnerabilities, or check for exploits.\nallowed-tools: [Read, Grep, Glob]\ndisable-model-invocation: true\n---\n\n# Security Review: $ARGUMENTS\n\nPerform a thorough security audit focusing on: $ARGUMENTS\n\n## Review Checklist\n\n### 1. Authentication & Authorization\n- Check for weak password policies\n- Verify JWT token validation\n- Review session management\n- Check for broken access control\n\n### 2. Input Validation\n- SQL injection vulnerabilities\n- XSS (Cross-Site Scripting) risks\n- Command injection possibilities\n- Path traversal vulnerabilities\n\n### 3. Data Protection\n- Sensitive data exposure\n- Encryption at rest and in transit\n- API keys and secrets in code\n- Database credential security\n\n### 4. Dependencies\n- Known vulnerabilities in packages\n- Outdated dependencies\n- License compliance issues\n\n### 5. Configuration\n- Security headers (CSP, HSTS, etc.)\n- CORS configuration\n- Error messages leaking information\n- Debug mode in production\n\n**Output Format** - Provide a detailed report with sections:\n- Critical Issues (Fix Immediately)\n- High Priority\n- Medium Priority\n- Low Priority \u002F Recommendations\n- Security Strengths\n- Action Plan (prioritized list of fixes)\n```\n\n**Usage:**\n```bash\n\u002Fsecurity-review \"authentication and API endpoints\"\n```\n\n**Example: API Documentation Generator Skill**\n\n`.claude\u002Fskills\u002Fapi-docs\u002FSKILL.md`:\n```yaml\n---\nname: api-docs\ndescription: Generate comprehensive API documentation from code. Use when asked to document APIs, create API docs, or generate OpenAPI specs.\nallowed-tools: [Read, Write, Grep, Glob]\ndisable-model-invocation: true\n---\n\n# Generate API Documentation\n\nAnalyze the codebase and create comprehensive API documentation for: $ARGUMENTS\n\n## Process\n\n### 1. Discovery\n- Find all API routes\u002Fendpoints\n- Identify request\u002Fresponse types\n- Note authentication requirements\n- Document query parameters\n\n### 2. Documentation\nFor each endpoint, document:\n- Method and path\n- Description\n- Authentication requirements\n- Request body\u002Fparameters\n- Response codes and bodies\n- Example requests\n\n### 3. Output\n- Create `\u002Fdocs\u002FAPI.md` with full documentation\n- Create `\u002Fopenapi.yaml` with OpenAPI spec if applicable\n```\n\n**Usage:**\n```bash\n\u002Fapi-docs \"all endpoints\"\n\u002Fapi-docs \"authentication routes\"\n```\n\n### File References with @ Syntax [OFFICIAL]\n\nReference files with `@` prefix for quick file inclusion:\n\n```bash\n# Reference single file\n\u002Freview-code @src\u002Fauth.ts\n\n# Reference multiple files\n\u002Freview-code @src\u002Fauth.ts @src\u002Fapi.ts @tests\u002Fauth.test.ts\n\n# Works in regular prompts too\n> \"Review @src\u002Fservices\u002Fpayment.ts for security issues\"\n\n# Reference files with skill arguments\n\u002Fanalyze-file @src\u002Fcomponents\u002FUserProfile.tsx\n```\n\n**How @ References Work:**\n- `@filename` automatically expands to include file content\n- Works with both absolute and relative paths\n- Can reference multiple files in one command\n- Files are read and included in context automatically\n- Reduces need to explicitly say \"read file X first\"\n\n**Use Cases:**\n```bash\n# Code review with context\n> \"Compare @src\u002Fapi\u002Fv1.ts and @src\u002Fapi\u002Fv2.ts and list differences\"\n\n# Refactoring across files\n> \"Make @src\u002Fmodels\u002FUser.ts consistent with @src\u002Ftypes\u002Fuser.d.ts\"\n\n# Bug investigation\n> \"This error occurs in @src\u002Fservices\u002Fauth.ts, check @logs\u002Ferror.log for clues\"\n\n# Test generation\n> \"Generate tests for @src\u002Futils\u002Fvalidator.ts\"\n```\n\n**Best Practices:**\n- Use @ references when you know exact file paths\n- Combine with skills for reusable workflows\n- Great for focused analysis of specific files\n- Reduces token usage vs. reading entire directories\n\n### MCP Integration [OFFICIAL]\n\nMCP servers can expose prompts that become invocable skills automatically:\n\n```json\n{\n  \"prompts\": [\n    {\n      \"name\": \"search-docs\",\n      \"description\": \"Search internal documentation\",\n      \"arguments\": [{\"name\": \"query\", \"description\": \"Search query\"}]\n    }\n  ]\n}\n```\n\nThis becomes available as `\u002Fsearch-docs` in Claude Code.\n\n```bash\n# Add MCP server\nclaude mcp add github -- gh-mcp\n\n# MCP prompts become skills:\n\u002Fgithub-pr-review      # Review current PR\n\u002Fgithub-issues         # List open issues\n\u002Fgithub-create-pr      # Create PR from current branch\n```\n\n### Skill Best Practices [OFFICIAL]\n\n#### 1. Write Clear, Specific Descriptions\n\nThe `description` field is critical — it helps Claude decide when to activate:\n\n**Good:**\n```yaml\ndescription: \"Generates API documentation from code comments. Use when user asks to document APIs, create API docs, update endpoint documentation, or generate OpenAPI specs.\"\n```\n\n**Bad:**\n```yaml\ndescription: \"Documentation generator\"  # Too vague\n```\n\n#### 2. Use Natural Trigger Words\n\nInclude terms users would naturally say:\n\n```yaml\n# For security review skill\ndescription: \"Reviews code for security. Use when asked to: review security, audit code, find vulnerabilities, check for exploits, analyze risks.\"\n\n# For performance optimization skill\ndescription: \"Optimizes code performance. Use when asked to: improve performance, optimize speed, reduce memory usage, make faster, profile code.\"\n```\n\n#### 3. Restrict Tools Appropriately\n\n```yaml\n# Analysis only (can't modify code)\nallowed-tools: [Read, Grep, Glob]\n\n# Can create\u002Fmodify code\nallowed-tools: [Read, Write, Edit, Bash]\n\n# Research and implementation\nallowed-tools: [Read, Write, Edit, WebFetch, WebSearch]\n```\n\n#### 4. Keep Skills Focused\n\n**Good (focused):**\n- `sql-optimizer` — Optimizes SQL queries only\n- `api-docs-generator` — Generates API documentation\n- `security-scanner` — Finds security issues\n\n**Bad (too broad):**\n- `database-everything` — Too vague\n- `code-helper` — What kind of help?\n\n#### 5. Provide Clear Instructions\n\nStructure your SKILL.md:\n1. **When to Activate** — Clear triggers\n2. **Process** — Step-by-step what to do\n3. **Output Format** — How to present results\n4. **Examples** — Show expected behavior\n\n#### 6. Mind the Context Budget\n\nSkill descriptions are loaded into context so Claude knows what's available. If you have many skills, they may exceed the character budget (2% of context window, fallback 16,000 characters). Run `\u002Fcontext` to check for warnings about excluded skills.\n\nOverride the limit with the `SLASH_COMMAND_TOOL_CHAR_BUDGET` environment variable.\n\n### Troubleshooting Skills [OFFICIAL]\n\n**Skill not triggering:**\n1. Check the description includes keywords users would naturally say\n2. Verify the skill appears when you ask \"What skills are available?\"\n3. Try rephrasing your request to match the description\n4. Invoke directly with `\u002Fskill-name` to confirm it works\n\n**Skill triggers too often:**\n1. Make the description more specific\n2. Add `disable-model-invocation: true` for manual-only invocation\n\n**Claude doesn't see all skills:**\n- Too many skill descriptions may exceed the character budget\n- Run `\u002Fcontext` to check for a warning about excluded skills\n- Set `SLASH_COMMAND_TOOL_CHAR_BUDGET` to a higher value\n\n### Migration: Commands to Skills\n\nCustom slash commands (`.claude\u002Fcommands\u002F` files) have been merged into the skills system. **Your existing command files keep working unchanged.** Skills are recommended for new work because they support:\n\n- **Supporting files** — Bundle templates, scripts, and reference docs alongside your skill\n- **Invocation control** — Choose whether you, Claude, or both can invoke\n- **Subagent execution** — Run skills in isolated forked contexts\n- **Nested discovery** — Automatic loading from subdirectories (monorepo support)\n\n**Migration path:**\n```bash\n# Old structure (still works)\n.claude\u002Fcommands\u002Freview.md\n\n# New structure (recommended)\n.claude\u002Fskills\u002Freview\u002FSKILL.md\n```\n\nBoth create `\u002Freview` and work the same way. If both exist, the skill takes precedence.\n\n**Source:** [Agent Skills](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fskills)\n\n---\n\n## Built-in Commands\n\n**Built-in commands are native CLI commands for managing your Claude Code session.** They are hardcoded into Claude Code and are NOT skills — you cannot customize or override them.\n\n> **Note:** For custom workflow commands, use [Skills](#skills-system) instead. Built-in commands like `\u002Fhelp` and `\u002Fcompact` are not available through the Skill tool.\n\n### Command Reference [OFFICIAL]\n\n```bash\n# Session Management\n\u002Fhelp              # Show all available commands\n\u002Fexit              # End current session\n\u002Fclear             # Clear conversation history\n\u002Fcompact [instr]   # Compact context (optionally specify what to focus on)\n\u002Frewind            # Undo code changes in conversation\n\n# Session & History\n\u002Frename \u003Cname>     # Give current session a name\n\u002Fresume [name|id]  # Resume a previous session by name or ID\n\u002Fexport            # Export conversation to file\n\u002Fcopy              # Copy last response to clipboard [NEW]\n\n# Usage & Stats\n\u002Fusage             # View plan limits and usage (NEW)\n\u002Fstats             # Usage stats, engagement metrics (supports 7\u002F30\u002Fall-time) (NEW)\n\u002Fextra-usage       # Enable extra usage for Max plan subscribers [NEW]\n\u002Ffast              # Toggle fast mode (uses faster model, available after \u002Fextra-usage) [NEW]\n\n# Background Process Management\n\u002Fbashes            # List all background processes\n\u002Ftasks             # List all background tasks (agents, shells, etc.)\n\u002Fkill \u003Cid>         # Stop a background process\n\n# Discovery & Debugging\n\u002Fbug               # Report bugs (sends conversation to Anthropic)\n\u002Fcommands          # List all skills and commands\n\u002Fdebug             # Troubleshoot session issues [NEW v2.1.30]\n\u002Fhooks             # Show configured hooks\n\u002Fskills            # List available Skills\n\u002Fplugin            # Plugin management interface\n\u002Fcontext           # View current context usage as a colored grid\n\u002Fcost              # Show token usage statistics\n\u002Fdoctor            # Run diagnostics (shows Updates section with auto-update channel)\n\n# Configuration\n\u002Fconfig            # General settings (type to search and filter)\n\u002Fpermissions       # Manage tool permissions (with search)\n\u002Fprivacy-settings  # View and update privacy settings\n\u002Fstatus            # Show session status (Status tab)\n\u002Fstatusline        # Configure status line display\n\u002Fmodel             # Switch between models\n\u002Foutput-style      # Set output style directly or from selection menu\n\u002Ftheme             # Theme picker (Ctrl+T toggles syntax highlighting)\n\u002Fterminal-setup    # Configure terminal (Kitty, Alacritty, Zed, Warp)\n\u002Fvim               # Enter vim mode for alternating insert\u002Fcommand modes\n\u002Fsandbox           # Enable sandboxed bash with filesystem\u002Fnetwork isolation\n\n# Workspace Management\n\u002Fadd-dir \u003Cpath>    # Add additional directory to workspace\n\u002Fagents            # Manage custom AI subagents\n\u002Finit              # Initialize project with CLAUDE.md guide\n\u002Fmemory            # Edit CLAUDE.md memory files\n\u002Finstall-github-app # Set up Claude GitHub Actions for repository\n\u002Fpr-comments       # View pull request comments\n\u002Freview            # Request code review\n\u002Fsecurity-review   # Complete security review of pending changes\n\u002Ftodos             # List current TODO items\n\n# MCP Server Management\n\u002Fmcp               # MCP server management and OAuth authentication\n\u002Fmcp enable \u003Csrv>  # Enable an MCP server\n\u002Fmcp disable \u003Csrv> # Disable an MCP server\n\n# Remote Sessions (claude.ai subscribers)\n\u002Fteleport          # Resume remote session from claude.ai by session ID\n\u002Fremote-env        # Configure remote session environment\n\n# Account & Updates\n\u002Flogin             # Switch Anthropic accounts\n\u002Flogout            # Sign out from Anthropic account\n\u002Frelease-notes     # View release notes\n\n# Plan Mode\n\u002Fplan              # Enter plan mode for structured planning\n```\n\n**Source:** [CLI Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference), [Interactive Mode](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Finteractive-mode#built-in-commands)\n\n---\n\n## Hooks System\n\n**Hooks are automated scripts that execute at specific points in Claude Code's workflow.**\n\n### What Are Hooks? [OFFICIAL]\n\nHooks let you **intercept and control** Claude's actions:\n\n```bash\n# Examples of what hooks can do:\n- Block editing of sensitive files (.env)\n- Inject context at session start\n- Run linting before file edits\n- Validate git commits\n- Audit all commands executed\n- Add custom security checks\n```\n\n**Two Types:**\n1. **Bash Command Hooks** (`type: \"command\"`) - Run shell scripts\n2. **Prompt-Based Hooks** (`type: \"prompt\"`) - Use LLM for context-aware decisions\n\n### Hook Configuration [OFFICIAL]\n\nHooks are configured in `.claude\u002Fsettings.json` or `~\u002F.claude\u002Fsettings.json`:\n\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"ToolPattern\",\n        \"hooks\": [\n          {\"type\": \"command\", \"command\": \"script\"}\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Hook Events [OFFICIAL]\n\n| Event | When It Fires | Can Block |\n|-------|---------------|-----------|\n| **Setup** | Via `--init`, `--init-only`, or `--maintenance` flags | No |\n| **SessionStart** | Session begins or resumes | No |\n| **SessionEnd** | Session terminates | No |\n| **UserPromptSubmit** | User submits a prompt | Yes |\n| **PreToolUse** | Before tool execution | Yes |\n| **PostToolUse** | After tool succeeds | No |\n| **PostToolUseFailure** | After tool fails | No |\n| **PermissionRequest** | When permission dialog appears | Yes |\n| **SubagentStart** | When spawning a subagent | No |\n| **SubagentStop** | When subagent finishes | Yes |\n| **Stop** | Claude finishes responding | Yes |\n| **Notification** | Claude sends notification | No |\n| **PreCompact** | Before context compaction | No |\n| **TeammateIdle** | Agent team teammate about to go idle [NEW] | Yes |\n| **TaskCompleted** | Task being marked as completed [NEW] | Yes |\n\n### Example: Protect Sensitive Files [OFFICIAL]\n\n`.claude\u002Fsettings.json`:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'FILE=$(echo \\\"$HOOK_INPUT\\\" | jq -r \\\".tool_input.file_path \u002F\u002F empty\\\"); if [[ \\\"$FILE\\\" == *\\\".env\\\"* ]] || [[ \\\"$FILE\\\" == \\\".git\u002F\\\"* ]]; then echo \\\"Cannot modify sensitive files\\\" >&2; exit 2; fi'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**How it works:**\n- Runs before any Edit or Write tool\n- Checks if file path contains \".env\" or \".git\u002F\"\n- Exits with code 2 to block the operation\n- Claude receives error and doesn't edit the file\n\n### Example: Session Context Injection [OFFICIAL]\n\n```json\n{\n  \"hooks\": {\n    \"SessionStart\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"cat .claude\u002Fsession-context.txt\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Creates:** `.claude\u002Fsession-context.txt`\n```\nToday's Focus: Working on authentication refactor\nRecent Context: Migrated from sessions to JWT\nCurrent Branch: feature\u002Fjwt-auth\nImportant: Don't modify legacy auth code in \u002Fold-auth\n```\n\nThis context is injected at every session start.\n\n### Example: Intelligent Decision Hook [OFFICIAL]\n\n```json\n{\n  \"hooks\": {\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"prompt\",\n            \"prompt\": \"Evaluate if the current task is complete. Arguments: $ARGUMENTS. Check if all subtasks are done, tests pass, and documentation updated. Respond with {\\\"decision\\\": \\\"stop\\\" or \\\"continue\\\", \\\"reason\\\": \\\"explanation\\\"}\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\nUses an LLM (Haiku) to intelligently decide if Claude should stop working.\n\n### Hook Input\u002FOutput [OFFICIAL]\n\n**Input (via stdin as JSON):**\n```json\n{\n  \"sessionId\": \"abc123\",\n  \"tool_name\": \"Edit\",\n  \"tool_input\": {\n    \"file_path\": \"\u002Fsrc\u002Fapp.ts\",\n    \"old_string\": \"...\",\n    \"new_string\": \"...\"\n  },\n  \"project_dir\": \"\u002Fhome\u002Fuser\u002Fproject\"\n}\n```\n\n**Output (exit codes):**\n- `0` - Success, continue\n- `2` - Block the action\n- Other - Non-blocking error (logged)\n\n**JSON Output (optional):**\n```json\n{\n  \"decision\": \"stop\",\n  \"reason\": \"All tasks complete\",\n  \"continue\": false\n}\n```\n\n### Security Best Practices [OFFICIAL]\n\n⚠️ **Critical:** \"By using hooks, you are solely responsible for configured commands, which can modify or delete files your user can access.\"\n\n**Best Practices:**\n```bash\n# 1. Always quote variables\nFILE=\"$HOOK_INPUT\"  # Good\nFILE=$HOOK_INPUT    # Bad - can break with spaces\n\n# 2. Validate paths\nif [[ \"$FILE\" == ..\u002F* ]]; then\n  echo \"Path traversal attempt\" >&2\n  exit 2\nfi\n\n# 3. Use absolute paths\ncd \"$CLAUDE_PROJECT_DIR\" || exit 1\n\n# 4. Sanitize inputs\njq -r '.tool_input.file_path' \u003C\u003C\u003C \"$HOOK_INPUT\"  # Good\neval \"$SOME_VAR\"  # Bad - code injection risk\n\n# 5. Block sensitive operations\ncase \"$FILE\" in\n  *.env|.git\u002F*|.ssh\u002F*)\n    echo \"Blocked: sensitive file\" >&2\n    exit 2\n    ;;\nesac\n```\n\n### Debugging Hooks [OFFICIAL]\n\n```bash\n# Run Claude with debug mode\nclaude --debug\n\n# Check hook configuration\n> \u002Fhooks\n\n# Test hook command manually\necho '{\"tool_name\":\"Edit\",\"tool_input\":{\"file_path\":\".env\"}}' | bash your-hook-script.sh\n\n# View logs\ntail -f ~\u002F.claude\u002Flogs\u002Fclaude.log\n```\n\n### Hook Recipes Library [OFFICIAL + COMMUNITY]\n\n**Comprehensive collection of production-ready hook patterns for common automation needs.**\n\n#### 1. Auto-Format Code on Save [COMMUNITY]\n\nAutomatically formats code after Claude edits files using language-appropriate formatters.\n\n**Configuration (`.claude\u002Fsettings.json`):**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|MultiEdit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fformat-code.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Script (`~\u002F.claude\u002Fhooks\u002Fformat-code.sh`):**\n```bash\n#!\u002Fbin\u002Fbash\n# Extract file path from JSON input\nFILE=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.file_path \u002F\u002F empty')\n\n[[ -z \"$FILE\" ]] && exit 0\n\n# Format based on extension\ncase \"$FILE\" in\n  *.ts|*.tsx|*.js|*.jsx)\n    # Try Biome first, fall back to Prettier\n    if command -v biome &> \u002Fdev\u002Fnull; then\n      biome format --write \"$FILE\" &> \u002Fdev\u002Fnull || true\n    elif command -v prettier &> \u002Fdev\u002Fnull; then\n      prettier --write \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    ;;\n  *.py)\n    # Python: Ruff\n    if command -v ruff &> \u002Fdev\u002Fnull; then\n      ruff format \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    ;;\n  *.go)\n    # Go: goimports + gofmt\n    if command -v goimports &> \u002Fdev\u002Fnull; then\n      goimports -w \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    go fmt \"$FILE\" &> \u002Fdev\u002Fnull || true\n    ;;\n  *.md)\n    # Markdown: Prettier\n    if command -v prettier &> \u002Fdev\u002Fnull; then\n      prettier --write \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    ;;\nesac\n```\n\n**Make executable:** `chmod +x ~\u002F.claude\u002Fhooks\u002Fformat-code.sh`\n\n---\n\n#### 2. ESLint Auto-Fix on Edit [COMMUNITY]\n\nAutomatically runs ESLint with `--fix` on JavaScript\u002FTypeScript files.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|MultiEdit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'FILE=$(echo \\\"$HOOK_INPUT\\\" | jq -r \\\".tool_input.file_path \u002F\u002F empty\\\"); if [[ \\\"$FILE\\\" =~ \\\\.(ts|tsx|js|jsx)$ ]] && command -v eslint &>\u002Fdev\u002Fnull; then eslint --fix \\\"$FILE\\\" &>\u002Fdev\u002Fnull || true; fi'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n---\n\n#### 3. Block .gitignore Reads [COMMUNITY]\n\nPrevents Claude from reading files matching `.claudeignore` patterns.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Read\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"claude-ignore\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Installation:** `npm install -g claude-ignore && claude-ignore init`\n\n---\n\n#### 4. Run Tests Before Commits [COMMUNITY]\n\nValidates that tests pass before allowing git commits.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fpre-commit-test.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Script (`~\u002F.claude\u002Fhooks\u002Fpre-commit-test.sh`):**\n```bash\n#!\u002Fbin\u002Fbash\nCOMMAND=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.command \u002F\u002F empty')\n\n# Only intercept git commit commands\nif [[ \"$COMMAND\" == git*commit* ]]; then\n  echo \"Running tests before commit...\" >&2\n\n  # Run tests\n  if npm test &>\u002Fdev\u002Fnull; then\n    echo \"✅ Tests passed\" >&2\n    exit 0\n  else\n    echo \"❌ Tests failed - blocking commit\" >&2\n    exit 2\n  fi\nfi\n\nexit 0\n```\n\n---\n\n#### 5. Audit Logging Hook [COMMUNITY]\n\nLogs all tool usage for security auditing.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'echo \\\"$(date -Iseconds) $TOOL_NAME: $(echo \\\\\\\"$HOOK_INPUT\\\\\\\" | jq -c .)\\\" >> ~\u002F.claude\u002Faudit.log'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n---\n\n#### 6. Token Usage Tracker [COMMUNITY]\n\nMonitors and logs token usage per session.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"SessionEnd\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Flog-session.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Script:**\n```bash\n#!\u002Fbin\u002Fbash\nSESSION_ID=$(echo \"$HOOK_INPUT\" | jq -r '.session_id \u002F\u002F \"unknown\"')\nTRANSCRIPT=$(echo \"$HOOK_INPUT\" | jq -r '.transcript_path \u002F\u002F empty')\n\nif [[ -f \"$TRANSCRIPT\" ]]; then\n  TOKENS=$(jq '[.[] | select(.role==\"assistant\") | .usage.total_tokens] | add' \"$TRANSCRIPT\" 2>\u002Fdev\u002Fnull || echo 0)\n  echo \"$(date -Iseconds) Session $SESSION_ID: $TOKENS tokens\" >> ~\u002F.claude\u002Ftoken-usage.log\nfi\n```\n\n---\n\n#### 7. Commit Message Validation [COMMUNITY]\n\nEnforces conventional commit message format.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fvalidate-commit.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Script:**\n```bash\n#!\u002Fbin\u002Fbash\nCOMMAND=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.command \u002F\u002F empty')\n\nif [[ \"$COMMAND\" == git*commit*-m* ]]; then\n  MSG=$(echo \"$COMMAND\" | sed -n 's\u002F.*-m[[:space:]]*[\"'\"'\"']\\([^\"'\"'\"']*\\)[\"'\"'\"'].*\u002F\\1\u002Fp')\n\n  # Check conventional commit format: type(scope): message\n  if [[ ! \"$MSG\" =~ ^(feat|fix|docs|style|refactor|test|chore)(\\(.+\\))?: ]]; then\n    echo \"❌ Commit message must follow format: type(scope): message\" >&2\n    echo \"Valid types: feat, fix, docs, style, refactor, test, chore\" >&2\n    exit 2\n  fi\nfi\n\nexit 0\n```\n\n---\n\n#### 8. Security Secret Scanner [COMMUNITY]\n\nPrevents committing files containing potential secrets.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fdetect-secrets.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Script:**\n```bash\n#!\u002Fbin\u002Fbash\nFILE=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.file_path \u002F\u002F empty')\nNEW_CONTENT=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.new_string \u002F\u002F .tool_input.content \u002F\u002F empty')\n\n# Check for common secret patterns\nif echo \"$NEW_CONTENT\" | grep -iE '(api[_-]?key|password|secret|token|auth)[\"\\s:=]+\\S{16,}' &>\u002Fdev\u002Fnull; then\n  echo \"⚠️  Potential secret detected in $FILE\" >&2\n  echo \"Please review and use environment variables instead\" >&2\n  exit 2\nfi\n\nexit 0\n```\n\n---\n\n#### 9. Auto-Documentation Update [COMMUNITY]\n\nUpdates README when code changes are made.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|MultiEdit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'echo \\\"📝 Consider updating documentation for recent changes\\\" >&2'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n---\n\n#### 10. Performance Profiling [COMMUNITY]\n\nTracks execution time of tool operations.\n\n**Configuration:**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'echo \\\"$HOOK_INPUT\\\" > \u002Ftmp\u002Fclaude-pre-$$.json; date +%s%N > \u002Ftmp\u002Fclaude-time-$$.txt'\"\n          }\n        ]\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fprofile-tool.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**Script:**\n```bash\n#!\u002Fbin\u002Fbash\nSTART=$(cat \u002Ftmp\u002Fclaude-time-$$.txt 2>\u002Fdev\u002Fnull || echo 0)\nEND=$(date +%s%N)\nDURATION=$(( (END - START) \u002F 1000000 ))  # milliseconds\nTOOL=$(echo \"$HOOK_INPUT\" | jq -r '.tool_name \u002F\u002F \"unknown\"')\n\necho \"$(date -Iseconds) $TOOL: ${DURATION}ms\" >> ~\u002F.claude\u002Fperformance.log\n\nrm -f \u002Ftmp\u002Fclaude-pre-$$.json \u002Ftmp\u002Fclaude-time-$$.txt\n```\n\n---\n\n**Source:** [Hooks Reference](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks), [Hooks Guide](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks-guide), Community GitHub repositories\n\n---\n\n## MCP Integration\n\n**Model Context Protocol (MCP) connects Claude Code to external data sources and tools.**\n\n### What is MCP? [OFFICIAL]\n\nMCP allows Claude Code to:\n- Access external data (Google Drive, Slack, Jira, Notion, etc.)\n- Use specialized tools (databases, APIs, services)\n- Integrate with enterprise systems\n- Extend capabilities beyond local filesystem\n\n**Common Use Cases:**\n- Read\u002Fwrite Google Drive documents\n- Search Slack conversations\n- Query databases directly\n- Fetch from internal APIs\n- Access design files (Figma)\n- Manage project tasks (Jira, Linear)\n\n### MCP Server Installation [OFFICIAL]\n\nMCP servers can be added via CLI or configuration files:\n\n**CLI Installation (Recommended):**\n```bash\n# Remote HTTP Server (recommended for hosted services)\nclaude mcp add --transport http notion https:\u002F\u002Fmcp.notion.com\u002Fmcp\nclaude mcp add --transport http github https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\n\n# With authentication headers\nclaude mcp add --transport http secure-api https:\u002F\u002Fapi.example.com\u002Fmcp \\\n  --header \"Authorization: Bearer your-token\"\n\n# Local Stdio Server (for local packages)\nclaude mcp add --transport stdio airtable -- npx -y airtable-mcp-server\nclaude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol\u002Fserver-postgres \"$DATABASE_URL\"\n\n# With environment variables\nclaude mcp add --transport stdio --env AIRTABLE_API_KEY=your_key airtable -- npx -y airtable-mcp-server\n\n# Windows (requires cmd \u002Fc wrapper)\nclaude mcp add --transport stdio myserver -- cmd \u002Fc npx -y @some\u002Fpackage\n```\n\n**MCP Server Management:**\n```bash\nclaude mcp list              # List all configured servers\nclaude mcp get github        # Get details for specific server\nclaude mcp remove github     # Remove a server\n\u002Fmcp                         # Interactive management in Claude Code\n```\n\n**Installation Scopes:**\n```bash\n# Local scope (default) - stored in ~\u002F.claude.json under project path\nclaude mcp add --transport http stripe https:\u002F\u002Fmcp.stripe.com\n\n# Project scope - stored in .mcp.json (shared via git)\nclaude mcp add --scope project --transport http paypal https:\u002F\u002Fmcp.paypal.com\u002Fmcp\n\n# User scope - stored in ~\u002F.claude.json (available across all projects)\nclaude mcp add --scope user --transport http hubspot https:\u002F\u002Fmcp.hubspot.com\n```\n\n**Configuration File (`.mcp.json`):**\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"type\": \"http\",\n      \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\"\n    },\n    \"postgres\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-postgres\", \"${DATABASE_URL}\"],\n      \"env\": {\n        \"DB_URL\": \"${DB_URL}\",\n        \"API_KEY\": \"${API_KEY:-default-value}\"\n      }\n    },\n    \"slack\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-slack\"],\n      \"env\": {\n        \"SLACK_BOT_TOKEN\": \"${SLACK_BOT_TOKEN}\",\n        \"SLACK_TEAM_ID\": \"${SLACK_TEAM_ID}\"\n      }\n    }\n  }\n}\n```\n\n### OAuth Authentication [OFFICIAL]\n\nMany MCP servers support OAuth for secure authentication:\n\n```bash\n# Add server that requires OAuth\nclaude mcp add --transport http sentry https:\u002F\u002Fmcp.sentry.dev\u002Fmcp\n\n# Within Claude Code, authenticate via browser\n\u002Fmcp\n# Follow browser steps to complete OAuth login\n```\n\n**Manual OAuth Configuration:**\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"type\": \"http\",\n      \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n      \"oauth\": {\n        \"provider\": \"github\",\n        \"scopes\": [\"repo\", \"read:user\"]\n      }\n    }\n  }\n}\n```\n\nClaude Code opens a browser to complete the OAuth flow on first use.\n\n### Using MCP Tools [OFFICIAL]\n\nOnce configured, MCP tools appear with the pattern `mcp__\u003Cserver>__\u003Ctool>`:\n\n```bash\n# Example: Google Drive search\n> \"Search our Google Drive for Q4 planning documents\"\n\n# Claude uses: mcp__google-drive__search_files\n\n# Example: Database query\n> \"Show all users created in the last week\"\n\n# Claude uses: mcp__postgres__query with SQL\n\n# Example: Slack search\n> \"Find conversations about the API redesign\"\n\n# Claude uses: mcp__slack__search_messages\n```\n\n### MCP in Hooks [OFFICIAL]\n\nYou can reference MCP tools in hooks:\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"mcp__postgres__query\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo 'Database query requires review' && read -p 'Approve? (y\u002Fn) ' -n 1 -r && [[ $REPLY =~ ^[Yy]$ ]]\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Popular MCP Servers [COMMUNITY]\n\n```bash\n# Official Servers\n@modelcontextprotocol\u002Fserver-google-drive      # Google Drive access\n@modelcontextprotocol\u002Fserver-slack             # Slack integration\n@modelcontextprotocol\u002Fserver-github            # GitHub API\n@modelcontextprotocol\u002Fserver-postgres          # PostgreSQL database\n@modelcontextprotocol\u002Fserver-sqlite            # SQLite database\n@modelcontextprotocol\u002Fserver-filesystem        # Extended file access\n\n# Community Servers\n# Check GitHub for community-built MCP servers\n```\n\n### MCP Configuration Management [OFFICIAL]\n\n```bash\n# Enable all project MCP servers automatically\n{\n  \"enableAllProjectMcpServers\": true\n}\n\n# Whitelist specific servers\n{\n  \"enabledMcpjsonServers\": [\"google-drive\", \"postgres\"]\n}\n\n# Blacklist servers\n{\n  \"disabledMcpjsonServers\": [\"risky-server\"]\n}\n\n# Enterprise: Restrict to managed servers only\n{\n  \"useEnterpriseMcpConfigOnly\": true,\n  \"allowedMcpServers\": [\"approved-server-1\", \"approved-server-2\"]\n}\n```\n\n### MCP Tool Search [NEW]\n\nWhen MCP tool definitions exceed a threshold of the context window, they're automatically deferred via an MCPSearch tool:\n\n```bash\n# Configure tool search threshold (% of context window)\nENABLE_TOOL_SEARCH=auto:5 claude    # Activate at 5%\nENABLE_TOOL_SEARCH=auto:10 claude   # Activate at 10% (default)\nENABLE_TOOL_SEARCH=true claude      # Always enabled\nENABLE_TOOL_SEARCH=false claude     # Always disabled\n\n# Or configure in settings.json\n{\n  \"permissions\": {\n    \"deny\": [\"MCPSearch\"]  # Disable MCP tool search\n  }\n}\n```\n\n**Source:** [MCP Documentation](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fmcp), [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n### MCP Setup Examples [OFFICIAL]\n\n**Quick-start configurations for popular MCP servers.**\n\n#### GitHub Integration\n\n```bash\n# Installation\nclaude mcp add --transport stdio github -- npx -y @modelcontextprotocol\u002Fserver-github\n\n# Or via .mcp.json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n**Common operations:** Create issues, manage PRs, search code, review repositories.\n\n#### Slack Integration\n\n```bash\n# Installation\nclaude mcp add --transport stdio slack -- npx -y @modelcontextprotocol\u002Fserver-slack\n\n# Configuration\n{\n  \"mcpServers\": {\n    \"slack\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-slack\"],\n      \"env\": {\n        \"SLACK_BOT_TOKEN\": \"${SLACK_BOT_TOKEN}\",\n        \"SLACK_TEAM_ID\": \"T01234567\"\n      }\n    }\n  }\n}\n```\n\n**Usage:** `> \"Search Slack for conversations about API redesign\"`\n\n#### Google Drive Integration\n\n```bash\n# Installation with OAuth\nclaude mcp add --transport http gdrive https:\u002F\u002Fmcp.google.com\u002Fdrive\n\n# Or stdio with credentials\n{\n  \"mcpServers\": {\n    \"gdrive\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-gdrive\"],\n      \"env\": {\n        \"GDRIVE_CREDENTIALS_PATH\": \"${HOME}\u002F.gdrive-credentials.json\"\n      }\n    }\n  }\n}\n```\n\n**Authenticate:** Run `\u002Fmcp` in Claude Code and follow OAuth flow.\n\n#### PostgreSQL Database\n\n```bash\n# Installation\nclaude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol\u002Fserver-postgres postgresql:\u002F\u002Fuser:pass@localhost\u002Fdb\n\n# Configuration\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"-y\",\n        \"@modelcontextprotocol\u002Fserver-postgres\",\n        \"${DATABASE_URL}\"\n      ]\n    }\n  }\n}\n```\n\n**Usage:** `> \"Show all users created in the last week from the database\"`\n\n#### Notion Integration\n\n```bash\n# Installation\nclaude mcp add --transport http notion https:\u002F\u002Fmcp.notion.com\u002Fmcp\n\n# Requires Notion OAuth - authenticate via \u002Fmcp command\n```\n\n**Common operations:** Query databases, create pages, search workspace.\n\n#### Stripe Payment Integration\n\n```bash\n# Configuration\n{\n  \"mcpServers\": {\n    \"stripe\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@stripe\u002Fmcp-server\"],\n      \"env\": {\n        \"STRIPE_API_KEY\": \"${STRIPE_API_KEY}\"\n      }\n    }\n  }\n}\n```\n\n**Usage:** `> \"List recent Stripe transactions and summarize revenue\"`\n\n### MCP Troubleshooting [COMMUNITY]\n\n**Common issues and solutions from GitHub issues and production usage.**\n\n#### Issue: MCP Server Not Showing in List\n\n```bash\n# Problem\nclaude mcp list\n# Output: \"No MCP servers configured\"\n\n# Solutions\n1. Check file location:\n   - User scope: ~\u002F.claude\u002Fsettings.json\n   - Project scope: .mcp.json (in project root)\n\n2. Verify JSON syntax:\n   cat .mcp.json | jq .\n\n3. Check scope setting:\n   claude mcp add --scope project \u003Cname> ...\n\n4. Restart Claude Code after config changes\n```\n\n#### Issue: Tools Not Available Despite \"Connected\"\n\n```bash\n# Problem\n\u002Fmcp shows \"✓ Connected\" but tools don't appear\n\n# Solutions\n1. Check tool output size (max 25,000 tokens):\n   export MAX_MCP_OUTPUT_TOKENS=50000\n\n2. Verify server actually started:\n   ps aux | grep mcp\n\n3. Check debug logs:\n   claude --debug\n   tail -f ~\u002F.claude\u002Flogs\u002Fclaude.log\n\n4. Reset project approvals:\n   claude mcp reset-project-choices\n```\n\n#### Issue: OAuth Authentication Fails\n\n```bash\n# Problem\nBrowser opens but OAuth fails or doesn't complete\n\n# Solutions\n1. Use \u002Fmcp command (not direct URL)\n\n2. Check network\u002Fproxy settings:\n   # Try without VPN\u002FCloudflare Warp\n\n3. Clear OAuth cache:\n   rm -rf ~\u002F.claude\u002Foauth-cache\n\n4. Verify redirect URI in provider settings\n```\n\n#### Issue: Windows \"Connection Closed\" Error\n\n```bash\n# Problem\nMCP server immediately closes on Windows\n\n# Solution - Use cmd \u002Fc wrapper:\nclaude mcp add --transport stdio myserver -- cmd \u002Fc npx -y package-name\n\n# In .mcp.json:\n{\n  \"mcpServers\": {\n    \"myserver\": {\n      \"command\": \"cmd\",\n      \"args\": [\"\u002Fc\", \"npx\", \"-y\", \"package-name\"]\n    }\n  }\n}\n```\n\n#### Issue: Environment Variables Not Expanding\n\n```bash\n# Problem\n${VAR} shows literally instead of expanding\n\n# Solutions\n1. Check .env file exists and is loaded\n\n2. Use default syntax:\n   \"${API_KEY:-default_value}\"\n\n3. Set in shell before running:\n   export API_KEY=xxx && claude\n\n4. Use settings.local.json for sensitive values\n```\n\n#### Issue: MCP Server Process Crashes\n\n```bash\n# Debug steps:\n1. Test server directly:\n   npx @modelcontextprotocol\u002Fserver-github\n\n2. Check stdout\u002Fstderr:\n   claude --debug | grep mcp\n\n3. Verify dependencies installed:\n   npm list -g | grep mcp\n\n4. Check memory\u002Fresource limits:\n   ulimit -a\n```\n\n---\n\n## Sub-Agents\n\n**Sub-agents are specialized AI assistants configured for specific tasks.**\n\n### What Are Sub-Agents? [OFFICIAL]\n\nSub-agents are instances of Claude optimized for particular workflows:\n\n```bash\n# Built-in Sub-Agents\n- general-purpose: Complex multi-step tasks\n- Explore: Fast codebase exploration\n\n# Custom Sub-Agents\n- You can create your own with custom prompts and tools\n```\n\n### Using Sub-Agents [OFFICIAL]\n\nLaunch with the `Task` tool:\n\n```bash\n# Explore codebase\n> \"Find all database queries in the codebase\"\n\n# Claude uses:\nTask subagent_type=\"Explore\"\n     prompt=\"Find all database queries and list files containing SQL, Prisma, or ORM code\"\n\n# General purpose research\n> \"Research best practices for API rate limiting and suggest implementation\"\n\n# Claude uses:\nTask subagent_type=\"general-purpose\"\n     prompt=\"Research API rate limiting approaches, compare options, and recommend implementation for Express.js\"\n```\n\n### Creating Custom Sub-Agents [OFFICIAL]\n\nSub-agents are defined as Markdown files in `.claude\u002Fagents\u002F` or `~\u002F.claude\u002Fagents\u002F`:\n\n**Example: Debug Assistant**\n\n`.claude\u002Fagents\u002Fdebugger.md`:\n```markdown\n---\nname: debugger\ndescription: Specialized debugging agent for production issues\nmodel: claude-sonnet-4\nallowedTools: [Read, Grep, Glob, Bash]\n---\n\n# Debug Assistant\n\nYou are a specialized debugging agent. Your role is to systematically investigate and identify the root cause of issues.\n\n## Debugging Process\n\n### 1. Gather Context\n- Read error messages and stack traces\n- Check recent code changes (git log)\n- Review related log files\n- Understand expected vs actual behavior\n\n### 2. Hypothesis Generation\n- List possible causes\n- Prioritize by likelihood\n- Consider recent changes first\n\n### 3. Systematic Investigation\n- Test each hypothesis methodically\n- Use Grep to find related code\n- Read implementation details\n- Check for similar patterns elsewhere\n\n### 4. Root Cause Analysis\n- Identify the precise cause\n- Explain why it happens\n- Trace the execution path\n\n### 5. Solution Proposal\n- Suggest specific fixes\n- Explain tradeoffs\n- Provide code examples\n- Recommend tests to prevent recurrence\n\n## Constraints\n- DO NOT modify code (read-only analysis)\n- DO provide detailed explanations\n- DO reference specific file:line locations\n- DO consider edge cases\n```\n\n**Example: Code Review Agent**\n\n`.claude\u002Fagents\u002Freviewer.md`:\n```markdown\n---\nname: reviewer\ndescription: Code review specialist focusing on quality and best practices\nmodel: claude-sonnet-4\nallowedTools: [Read, Grep, Glob]\n---\n\n# Code Reviewer\n\nYou are a senior code reviewer. Provide constructive, actionable feedback.\n\n## Review Criteria\n\n### Code Quality\n- Readability and maintainability\n- Naming conventions\n- Code organization\n- DRY principle adherence\n\n### Correctness\n- Logic errors\n- Edge cases handling\n- Error handling\n- Null\u002Fundefined checks\n\n### Performance\n- Algorithm efficiency\n- Unnecessary computations\n- Memory usage\n- Database query optimization\n\n### Security\n- Input validation\n- SQL injection risks\n- XSS vulnerabilities\n- Authentication\u002Fauthorization\n\n### Testing\n- Test coverage\n- Test quality\n- Edge cases tested\n\n## Output Format\nProvide structured feedback:\n- **Strengths**: What's done well\n- **Issues**: Problems found (with severity)\n- **Suggestions**: Improvements\n- **Examples**: Code snippets for fixes\n```\n\n### Sub-Agent Features [OFFICIAL]\n\n#### Model Selection\n\nChoose different models per agent:\n\n```markdown\n---\nname: fast-explorer\nmodel: claude-haiku-4  # Fast, cost-effective\n---\n```\n\n```markdown\n---\nname: deep-analyzer\nmodel: claude-opus-4  # Most capable\n---\n```\n\n#### Tool Restrictions\n\nLimit tools for focused operation:\n\n```markdown\n---\nname: readonly-analyzer\nallowedTools: [Read, Grep, Glob]  # Analysis only\n---\n```\n\n```markdown\n---\nname: implementation-agent\nallowedTools: [Read, Write, Edit, Bash]  # Can modify code\n---\n```\n\n### Sub-Agent Patterns [COMMUNITY]\n\n#### Parallel Analysis\n\n```bash\n> \"Have multiple agents analyze different aspects\"\n\n# Launches multiple agents in parallel:\n- Security review agent\n- Performance analysis agent\n- Code style agent\n- Test coverage agent\n\n# Aggregates results\n```\n\n#### Sequential Pipeline\n\n```bash\n> \"Research → Design → Implement authentication\"\n\n# Sequential sub-agents:\n1. Research agent: Find best practices\n2. Design agent: Create architecture\n3. Implementation agent: Write code\n4. Review agent: Verify implementation\n```\n\n#### Specialized Teams\n\n```json\n{\n  \"frontend-agent\": \"React\u002FUI specialist\",\n  \"backend-agent\": \"API\u002Fdatabase specialist\",\n  \"devops-agent\": \"Deployment\u002Finfrastructure specialist\"\n}\n```\n\n**Source:** [Sub-Agents](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsub-agents)\n\n---\n\n## Agent Teams\n\n**Agent Teams enable multiple Claude Code instances to collaborate on complex tasks with shared context and direct communication.**\n\n### What Are Agent Teams? [OFFICIAL]\n\nAgent Teams (experimental) allow you to coordinate multiple Claude Code sessions working together:\n\n```bash\n# Key differences from Sub-Agents:\n- Sub-Agents: Run within a single session, report only to main agent\n- Agent Teams: Independent sessions that can communicate directly with each other\n\n# When to use Agent Teams:\n✅ Research and review (multiple perspectives simultaneously)\n✅ New modules\u002Ffeatures (teammates own separate pieces)\n✅ Debugging with competing hypotheses (parallel investigation)\n✅ Cross-layer coordination (frontend, backend, tests)\n\n# When NOT to use Agent Teams:\n❌ Sequential tasks with dependencies\n❌ Same-file edits (coordination overhead)\n❌ Simple tasks (overkill)\n```\n\n### Enable Agent Teams [OFFICIAL]\n\nAgent Teams are disabled by default. Enable in settings:\n\n```json\n{\n  \"env\": {\n    \"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS\": \"1\"\n  }\n}\n```\n\nOr set the environment variable:\n\n```bash\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\nclaude\n```\n\n### Starting a Team [OFFICIAL]\n\n```bash\n# Describe the task and team structure\n> \"Create an agent team to review PR #142. Spawn three reviewers:\n   - One focused on security implications\n   - One checking performance impact\n   - One validating test coverage\n   Have them each review and report findings.\"\n\n# Claude creates the team and coordinates work\n# Use Shift+Up\u002FDown to select and message teammates directly\n```\n\n### Team Display Modes [OFFICIAL]\n\n| Mode | Description | Best For |\n|------|-------------|----------|\n| `in-process` | All teammates in main terminal | Any terminal, simple setup |\n| `tmux` | Each teammate in own pane | Parallel visibility, tmux\u002FiTerm2 |\n| `auto` (default) | Uses tmux if already in tmux session | Automatic selection |\n\nConfigure in settings:\n\n```json\n{\n  \"teammateMode\": \"in-process\"\n}\n```\n\nOr via CLI flag:\n\n```bash\nclaude --teammate-mode in-process\n```\n\n### Team Controls [OFFICIAL]\n\n```bash\n# Select teammates\nShift+Up\u002FDown          # Cycle through teammates\n\n# View teammate session\nEnter                  # View selected teammate's session\nEscape                 # Interrupt teammate's turn\n\n# Manage tasks\nCtrl+T                 # Toggle shared task list\n\n# Delegate mode\nShift+Tab              # Toggle delegate mode (lead only coordinates, doesn't implement)\n\n# Shut down\n> \"Ask the researcher teammate to shut down\"\n> \"Clean up the team\"\n```\n\n### Team Architecture [OFFICIAL]\n\n| Component | Description |\n|-----------|-------------|\n| **Team Lead** | Main session that creates team, spawns teammates, coordinates work |\n| **Teammates** | Independent Claude Code instances working on assigned tasks |\n| **Task List** | Shared work items that teammates claim and complete |\n| **Mailbox** | Messaging system for inter-agent communication |\n\n**Storage Locations:**\n- Team config: `~\u002F.claude\u002Fteams\u002F{team-name}\u002Fconfig.json`\n- Task list: `~\u002F.claude\u002Ftasks\u002F{team-name}\u002F`\n\n### Team Hooks [OFFICIAL]\n\nUse hooks to enforce quality gates:\n\n```json\n{\n  \"hooks\": {\n    \"TeammateIdle\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'if [ ! -f .\u002Fdist\u002Foutput.js ]; then echo \\\"Build artifact missing\\\" >&2; exit 2; fi'\"\n          }\n        ]\n      }\n    ],\n    \"TaskCompleted\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'if ! npm test 2>&1; then echo \\\"Tests failing\\\" >&2; exit 2; fi'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n- **TeammateIdle**: Runs when teammate about to go idle. Exit code 2 sends feedback and keeps teammate working.\n- **TaskCompleted**: Runs when task marked complete. Exit code 2 prevents completion with feedback.\n\n### Current Limitations [OFFICIAL]\n\n- No session resumption with in-process teammates\n- Task status can lag (stuck tasks need manual intervention)\n- Slow shutdown (teammates finish current work first)\n- One team per session\n- No nested teams (teammates can't spawn teams)\n- Fixed lead (can't promote teammates)\n- Permissions set at spawn (can't pre-set per-teammate)\n- Split panes require tmux or iTerm2\n\n**Source:** [Agent Teams](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fagent-teams)\n\n---\n\n## Plugins\n\n**Plugins bundle Skills, Hooks, and MCP servers for easy sharing.**\n\n### What Are Plugins? [OFFICIAL]\n\nPlugins are packages that extend Claude Code:\n\n```bash\n# A plugin can contain:\n- Skills (capabilities and workflow templates)\n- Hooks (automation)\n- MCP Servers (external integrations)\n- Sub-Agent definitions\n```\n\n### Plugin Management [OFFICIAL]\n\n```bash\n# Interactive plugin management\n> \u002Fplugin\n\n# Options:\n- Browse marketplace\n- Install plugins\n- Enable\u002Fdisable plugins\n- Remove plugins\n- Add custom marketplaces\n- Search installed plugins [v2.1.14]\n```\n\n**Plugin Pinning** [NEW v2.1.14]: Plugins can now be pinned to specific git commit SHAs for version stability:\n\n```json\n{\n  \"plugins\": {\n    \"enabledPlugins\": {\n      \"security-toolkit@official#abc123def\": true\n    }\n  }\n}\n```\n\n### Plugin Structure [OFFICIAL]\n\n```\nmy-plugin\u002F\n├── .claude-plugin\u002F\n│   └── plugin.json          # Metadata\n├── commands\u002F                 # Legacy commands (treated as skills)\n│   └── my-command.md\n├── skills\u002F                   # Skills\n│   └── my-skill\u002F\n│       └── SKILL.md\n├── hooks.json               # Hook definitions\n└── agents\u002F                  # MCP servers & sub-agents\n    └── mcp.json\n```\n\n**plugin.json:**\n```json\n{\n  \"name\": \"my-plugin\",\n  \"version\": \"1.0.0\",\n  \"description\": \"My awesome plugin\",\n  \"author\": \"Your Name\",\n  \"homepage\": \"https:\u002F\u002Fgithub.com\u002Fuser\u002Fplugin\",\n  \"keywords\": [\"productivity\", \"testing\"]\n}\n```\n\n### Installing Plugins [OFFICIAL]\n\n```bash\n# From marketplace\n> \u002Fplugin\n# Select \"Browse marketplace\"\n# Choose and install\n\n# Team Configuration\n# .claude\u002Fsettings.json\n{\n  \"plugins\": {\n    \"enabledPlugins\": {\n      \"security-toolkit@official\": true,\n      \"custom-workflows@team\": true\n    }\n  }\n}\n```\n\n### Creating Custom Marketplaces [OFFICIAL]\n\n```json\n{\n  \"extraKnownMarketplaces\": [\n    {\n      \"name\": \"company-internal\",\n      \"type\": \"github\",\n      \"url\": \"https:\u002F\u002Fgithub.com\u002Fcompany\u002Fclaude-plugins\"\n    },\n    {\n      \"name\": \"local-dev\",\n      \"type\": \"directory\",\n      \"path\": \"\u002Fpath\u002Fto\u002Fplugins\"\n    }\n  ]\n}\n```\n\n### Plugin Auto-Install for Teams [OFFICIAL]\n\nConfigure in `.claude\u002Fsettings.json` (committed to git):\n\n```json\n{\n  \"plugins\": {\n    \"enabledPlugins\": {\n      \"team-workflows@company\": true\n    }\n  },\n  \"extraKnownMarketplaces\": [\n    {\n      \"name\": \"company\",\n      \"type\": \"github\",\n      \"url\": \"https:\u002F\u002Fgithub.com\u002Fcompany\u002Fclaude-plugins\"\n    }\n  ]\n}\n```\n\nWhen team members trust the repository, plugins install automatically.\n\n### VSCode Plugin Features [NEW]\n\nWhen using Claude Code in VSCode:\n- **Install count display**: See how many users have installed each plugin\n- **Trust warnings**: Security prompts when installing plugins from untrusted sources\n- **Native plugin management** [v2.1.16]: Built-in plugin management support in VSCode extension\n- **Remote session browsing** [v2.1.16]: OAuth users can browse and resume remote Claude sessions directly from the Sessions dialog\n- **`\u002Fusage` command** [v2.1.14]: Display current plan usage directly in VSCode\n- **Session forking and rewind** [v2.1.19]: Fork sessions and rewind functionality now enabled for all users\n- **Python virtual environment activation** [v2.1.21]: Automatic activation ensures `python` and `pip` use the correct interpreter (configure via `claudeCode.usePythonEnvironment` setting)\n- **Claude in Chrome integration** [v2.1.27]: Connect Claude Code to Chrome browser for web automation and testing\n\n**Source:** [Plugins](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fplugins)\n\n### Desktop App Features [NEW]\n\nThe Claude desktop app provides a native interface for running Claude Code sessions locally and integrating with Claude Code on the web.\n\n**Key Features:**\n- **Diff view**: Review Claude's changes file by file before creating a PR, with inline commenting\n- **Parallel local sessions with git worktrees**: Run multiple sessions in the same repository, each with isolated worktrees\n- **`.worktreeinclude` file**: Automatically copy gitignored files (like `.env`) to new worktrees\n- **Launch cloud sessions**: Start Claude Code on the web directly from the desktop app\n- **Bundled Claude Code version**: Includes a stable, managed version of Claude Code\n\n**Diff View:**\n- Click the diff stats indicator (`+12 -1`) to open the diff viewer\n- Click any line to add inline comments\n- Press Enter to accept each comment, Cmd+Enter to send all\n\n**Git Worktrees:**\nCreate a `.worktreeinclude` file in your repository root:\n```\n.env\n.env.local\n**\u002F.claude\u002Fsettings.local.json\n```\n\nFiles matching these patterns that are also in `.gitignore` will be copied to new worktrees.\n\n**Installation:**\n- macOS: https:\u002F\u002Fclaude.ai\u002Fapi\u002Fdesktop\u002Fdarwin\u002Funiversal\u002Fdmg\u002Flatest\u002Fredirect\n- Windows x64: https:\u002F\u002Fclaude.ai\u002Fapi\u002Fdesktop\u002Fwin32\u002Fx64\u002Fexe\u002Flatest\u002Fredirect\n- Windows ARM64: https:\u002F\u002Fclaude.ai\u002Fapi\u002Fdesktop\u002Fwin32\u002Farm64\u002Fexe\u002Flatest\u002Fredirect\n\n**Source:** [Desktop Documentation](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fdesktop)\n\n---\n\n## Development Workflows\n\n### Core Development Approach [COMMUNITY]\n\n**Phase 1: Understand**\n```bash\n# Start by understanding the codebase\n> \"Read the project structure and explain the architecture\"\n> \"What testing framework is used?\"\n> \"Show me the authentication flow\"\n\n# Claude will:\n- Read README, package.json, etc.\n- Analyze project structure\n- Identify key patterns\n```\n\n**Phase 2: Plan**\n```bash\n# For complex features, plan first\n> \"I need to add user roles and permissions. Create a plan\"\n\n# Claude will:\n- Break down the feature\n- Identify affected files\n- Consider edge cases\n- Create TodoWrite tasks\n```\n\n**Phase 3: Implement**\n```bash\n# Implement incrementally\n> \"Implement step 1: Add roles to user model\"\n\n# Then verify\n> \"Run the tests\"\n\n# Continue\n> \"Implement step 2: Add permission checks to API\"\n```\n\n**Phase 4: Verify**\n```bash\n# Always verify changes\n> \"Run all tests\"\n> \"Check for TypeScript errors\"\n> \"Review the changes we made\"\n\n# Create commit\n> \"Create a git commit for these changes\"\n```\n\n### Task Management with TodoWrite [COMMUNITY]\n\nFor complex multi-step work:\n\n```bash\n> \"Add user authentication system\"\n\n# Claude creates todos:\nTodoWrite todos=[\n  {\"content\": \"Create User model with password hashing\", \"status\": \"in_progress\", ...},\n  {\"content\": \"Implement JWT token generation\", \"status\": \"pending\", ...},\n  {\"content\": \"Add login\u002Fregister endpoints\", \"status\": \"pending\", ...},\n  {\"content\": \"Add authentication middleware\", \"status\": \"pending\", ...},\n  {\"content\": \"Write integration tests\", \"status\": \"pending\", ...}\n]\n\n# As work progresses, todos update:\n# ✅ \"Create User model...\" - completed\n# ⏳ \"Implement JWT tokens...\" - in_progress\n# ⏸️ \"Add login\u002Fregister...\" - pending\n```\n\n### Parallel vs Sequential Work [COMMUNITY]\n\n**Parallel (Independent Tasks):**\n```bash\n> \"Create these three independent components\"\n\n# Claude can work on all simultaneously:\n- Component A (no dependencies)\n- Component B (no dependencies)\n- Component C (no dependencies)\n```\n\n**Sequential (Dependencies):**\n```bash\n> \"Set up database, then add user model, then create API\"\n\n# Must be done in order:\n1. Database setup (others depend on this)\n2. User model (API depends on this)\n3. API endpoints (depends on model)\n```\n\n### Quality Assurance Patterns [COMMUNITY]\n\n**Automated Validation:**\n```bash\n# After changes, verify automatically\n> \"Run the following checks:\n   - TypeScript compilation\n   - Linting\n   - All tests\n   - Build process\"\n\n# Or create a skill:\n\u002Fverify-changes\n```\n\n**Multi-Perspective Review:**\n```bash\n# Use sub-agents for thorough review\n> \"Review these changes from multiple perspectives:\n   - Security issues\n   - Performance implications\n   - Code quality\n   - Test coverage\"\n\n# Launches specialized review agents\n```\n\n---\n\n## Tool Synergies\n\nClaude Code's features form a layered automation stack. Understanding how they combine unlocks powerful workflows.\n\n### Quick Reference: 15 Synergy Patterns\n\n| # | Synergy | Use Case |\n|---|---------|----------|\n| 1 | [Explore → Plan → Code → Commit](#synergy-1-explore--plan--code--commit-official) | Standard development workflow |\n| 2 | [Test-Driven Development](#synergy-2-test-driven-development-community) | Quality-first coding |\n| 3 | [MCP + Skills](#synergy-3-mcp--skills-official) | External tool integrations |\n| 4 | [Skills + Hooks](#synergy-4-skills--hooks-auto-apply--enforce-official) | Auto-apply expertise + enforce rules |\n| 5 | [Sub-agents + Background](#synergy-5-sub-agents--background-tasks-official) | Parallel isolated work |\n| 6 | [Multi-Claude Workflows](#synergy-6-multi-claude-workflows-community) | Git worktrees for parallelism |\n| 7 | [Context Preservation](#synergy-7-context-preservation-across-sessions-community) | Session continuity |\n| 8 | [Quality Pipeline](#synergy-8-quality-pipeline-hooks--tests--lint-community) | Automated quality enforcement |\n| 9 | [Visual-Driven Development](#synergy-9-visual-driven-development-community) | Screenshots\u002Fmockups → code |\n| 10 | [Log Analysis Pipeline](#synergy-10-log-analysis-pipeline-official) | Unix pipes + Claude |\n| 11 | [Schema-Driven Development](#synergy-11-schema-driven-development-community) | DB schema → types\u002FAPI\u002Ftests |\n| 12 | [Dependency Management](#synergy-12-dependency-management-community) | Update + test + fix cycle |\n| 13 | [Documentation Generation](#synergy-13-documentation-generation-community) | Codebase → living docs |\n| 14 | [Refactoring with Safety](#synergy-14-refactoring-with-safety-net-community) | Large changes without breaking |\n| 15 | [Incident Response](#synergy-15-incident-response-community) | Production debugging workflow |\n\n### The Feature Stack [OFFICIAL]\n\nEach feature serves a distinct purpose and they build on each other:\n\n| Layer | Feature | Purpose | Invocation |\n|-------|---------|---------|------------|\n| **Connection** | MCP | External tools (GitHub, Jira, DBs) | Automatic when configured |\n| **Capability** | Skills | Domain expertise + workflows | Auto-activated or via `\u002Fskill-name` |\n| **Enforcement** | Hooks | Quality gates, auto-actions | Lifecycle events |\n| **Isolation** | Sub-agents | Parallel specialized work | Task delegation |\n| **Bundling** | Plugins | Package all of the above | Install once |\n\n**Key insight:** MCP connects external systems. Skills provide expertise and workflows (both auto-activated and user-invoked). Hooks enforce standards. Sub-agents isolate heavy work.\n\n### Synergy 1: Explore → Plan → Code → Commit [OFFICIAL]\n\nThe recommended workflow from [Anthropic's best practices](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fclaude-code-best-practices):\n\n```bash\n# Step 1: Explore - understand what exists\n\"Read src\u002Fauth\u002F and explain the current authentication flow.\nList all files involved and their responsibilities.\"\n\n# Step 2: Plan - use extended thinking\n\"Think hard about how to add OAuth2 support. Create a detailed plan\ncovering: files to modify, new files needed, dependencies, and test strategy.\"\n\n# Step 3: Code - implement with explicit files\n\"Implement the OAuth2 changes following the plan. Start with\nsrc\u002Fauth\u002Foauth.ts, then update src\u002Fauth\u002Findex.ts to export it.\"\n\n# Step 4: Commit - structured message\n\"Create a commit with message: 'feat(auth): add OAuth2 provider support'\"\n```\n\n**Why it works:** Each step builds context. Exploring first prevents wrong assumptions. Planning with \"think hard\" engages extended reasoning. Explicit file names reduce ambiguity.\n\n### Synergy 2: Test-Driven Development [COMMUNITY]\n\nWrite tests first, then implement:\n\n```bash\n# 1. Write failing tests first\n\"Write tests for a new validateEmail function in src\u002Futils\u002Fvalidation.ts.\nCover: valid emails, invalid formats, empty input, null input.\nUse Jest. The function doesn't exist yet - tests should fail.\"\n\n# 2. Confirm tests fail\n\"Run npm test -- --testPathPattern=validation\"\n\n# 3. Commit the failing tests\n\"Commit with message: 'test(validation): add email validation tests (red)'\"\n\n# 4. Implement to pass\n\"Now implement validateEmail in src\u002Futils\u002Fvalidation.ts to pass all tests.\nUse a standard regex pattern. No external dependencies.\"\n\n# 5. Verify and commit\n\"Run the tests again. If passing, commit: 'feat(validation): implement email validation (green)'\"\n```\n\n**Why it works:** Tests define the contract before implementation. Claude iterates against concrete targets. Git history shows the TDD discipline.\n\n### Synergy 3: MCP + Skills [OFFICIAL]\n\nMCP servers expose prompts that become skills:\n\n```bash\n# Add MCP server\nclaude mcp add github -- gh-mcp\n\n# Now available as commands:\n\u002Fgithub-pr-review      # Review current PR\n\u002Fgithub-issues         # List open issues\n\u002Fgithub-create-pr      # Create PR from current branch\n\n# Example workflow - complete ticket\n\u002Fgithub-issues         # \"Show me issue #42\"\n# Claude fetches issue details via MCP\n\n\"Implement the feature described in issue #42.\nFollow our patterns in src\u002Ffeatures\u002F.\"\n\n\u002Fgithub-create-pr      # Creates PR linked to issue\n```\n\n**Real MCP integrations:** GitHub, Jira, Linear, Notion, PostgreSQL, Slack, Figma, Google Drive. Each adds domain-specific commands.\n\n### Synergy 4: Skills + Hooks (Auto-Apply + Enforce) [OFFICIAL]\n\nSkills activate automatically; hooks enforce at lifecycle events:\n\n```\n.claude\u002F\n├── skills\u002F\n│   └── security-review\u002F\n│       └── SKILL.md        # Auto-activates on security-related tasks\n└── settings.json           # Hook: block commits if security issues found\n```\n\n**Skill definition** (`.claude\u002Fskills\u002Fsecurity-review\u002FSKILL.md`):\n```markdown\n---\nname: security-review\ndescription: Analyzes code for security vulnerabilities. Activates when\nreviewing auth code, API endpoints, or user input handling.\nallowed-tools: [Read, Grep, Glob]\n---\n\nWhen activated, check for:\n- SQL injection (string concatenation in queries)\n- XSS (unescaped user input in HTML)\n- Exposed secrets (API keys, passwords in code)\n- Broken auth (missing token validation)\n\nReport findings with file:line references and severity.\n```\n\n**Hook definition** (in `settings.json`):\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [{\n      \"tool\": \"Bash\",\n      \"command\": \"git commit\",\n      \"script\": \".claude\u002Fhooks\u002Fsecurity-check.sh\"\n    }]\n  }\n}\n```\n\n**Workflow:**\n```bash\n\"Review the authentication code in src\u002Fauth\u002F for security issues\"\n# Skill auto-activates, finds issues\n\n\"Fix the SQL injection vulnerability in src\u002Fauth\u002Flogin.ts:45\"\n# You fix it\n\n\"Commit the security fix\"\n# Hook runs security-check.sh before allowing commit\n# Blocks if issues remain, allows if clean\n```\n\n### Synergy 5: Sub-agents + Background Tasks [OFFICIAL]\n\nIsolate work and run in parallel:\n\n```bash\n# Start services in background (Ctrl+B or explicit)\n\"Run npm run dev in background\"\n\"Run npm test -- --watch in background\"\n\n# Check running tasks\n\u002Ftasks\n\n# Main session: Use explorer agent for research\n\"Use the explorer agent to find all API endpoints and their handlers\"\n\n# Parallel work happening:\n# - Background: Dev server on port 3000\n# - Background: Test watcher re-running on changes\n# - Sub-agent: Scanning codebase for endpoints\n# - Main session: Available for next task\n\n# Later, retrieve agent results\n\"What did the explorer agent find?\"\n```\n\n**Sub-agent types:** `Explore` (codebase search), `Plan` (architecture), custom agents defined in `.claude\u002Fagents\u002F`.\n\n### Synergy 6: Multi-Claude Workflows [COMMUNITY]\n\nRun multiple Claude instances for independent work:\n\n```bash\n# Terminal 1: Feature development\ncd feature-branch-worktree\nclaude\n\"Implement the user dashboard feature\"\n\n# Terminal 2: Code review (same repo, different worktree)\ncd review-worktree\nclaude\n\"Review the changes in the user-dashboard branch for security and performance\"\n\n# Terminal 3: Documentation\ncd docs-worktree\nclaude\n\"Update API documentation based on recent changes\"\n```\n\n**Advanced: Claude reviewing Claude:**\n```bash\n# Claude 1 writes code\n\"Implement rate limiting for the API endpoints in src\u002Fapi\u002F\"\n\n# Claude 2 reviews (different session)\n\"Review the rate limiting implementation. Check for:\n- Edge cases (what happens at exactly the limit?)\n- Race conditions (concurrent requests)\n- Configuration flexibility (can limits be changed without deploy?)\"\n```\n\n### Synergy 7: Context Preservation Across Sessions [COMMUNITY]\n\nCombine CLAUDE.md + skills for continuity:\n\n**Project CLAUDE.md:**\n```markdown\n# Project: E-commerce API\n\n## Current Sprint\n- [ ] Implement payment webhooks\n- [ ] Add inventory tracking\n- [x] User authentication (completed Jan 10)\n\n## Key Decisions\n- Using Stripe for payments (see docs\u002Fadr\u002F001-payment-provider.md)\n- PostgreSQL for inventory (see src\u002Fdb\u002Fschema.sql)\n\n## Commands\nnpm run dev      # Start on port 3000\nnpm test         # Run Jest tests\nnpm run db:seed  # Seed test data\n```\n\n**Skill for context loading** (`.claude\u002Fskills\u002Fresume\u002FSKILL.md`):\n```markdown\n---\nname: resume\ndescription: Resume work on current sprint\n---\n\nRead CLAUDE.md and the current sprint tasks.\nCheck git log for recent commits.\nSummarize: what's done, what's in progress, what's next.\nAsk what I want to work on.\n```\n\n**Usage:**\n```bash\nclaude\n\u002Fresume\n# Claude reads context, summarizes state, ready to continue\n```\n\n### Synergy 8: Quality Pipeline (Hooks + Tests + Lint) [COMMUNITY]\n\nAutomated quality enforcement:\n\n**Hook configuration:**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [{\n      \"tool\": \"Write\",\n      \"script\": \"npm run lint:fix -- $FILE\"\n    }, {\n      \"tool\": \"Edit\",\n      \"script\": \"npm run lint:fix -- $FILE\"\n    }],\n    \"PreToolUse\": [{\n      \"tool\": \"Bash\",\n      \"command\": \"git commit\",\n      \"script\": \".claude\u002Fhooks\u002Fpre-commit.sh\"\n    }]\n  }\n}\n```\n\n**Pre-commit hook script:**\n```bash\n#!\u002Fbin\u002Fbash\nnpm run lint || exit 1\nnpm test || exit 1\necho \"All checks passed\"\n```\n\n**Result:** Every file edit auto-lints. Every commit requires passing tests. Quality enforced without manual intervention.\n\n### Synergy 9: Visual-Driven Development [COMMUNITY]\n\nUse screenshots and mockups as implementation targets:\n\n```bash\n# Share a design mockup\n\"Here's the Figma mockup for the new dashboard @mockups\u002Fdashboard.png\nImplement this in src\u002Fcomponents\u002FDashboard.tsx using our existing\nButton, Card, and Chart components. Match the layout exactly.\"\n\n# Iterate on visual feedback\n\"Here's a screenshot of the current result @screenshots\u002Fcurrent.png\nCompare to the mockup. Fix: the spacing between cards is wrong,\nand the chart colors don't match.\"\n\n# Debug visual issues\n\"This screenshot shows a layout bug on mobile @bugs\u002Fmobile-layout.png\nThe sidebar overlaps the content. Fix the responsive styles in\nsrc\u002Fstyles\u002Flayout.css\"\n```\n\n**Why it works:** Claude can see images. Concrete visual targets reduce ambiguity. Iteration is fast.\n\n### Synergy 10: Log Analysis Pipeline [OFFICIAL]\n\nUnix pipes + Claude for real-time analysis:\n\n```bash\n# Monitor logs for anomalies\ntail -f \u002Fvar\u002Flog\u002Fapp.log | claude -p \"Alert me if you see errors or unusual patterns\"\n\n# Analyze crash dumps\ncat crash.log | claude -p \"Analyze this crash. Identify root cause and suggest fix.\"\n\n# Parse and summarize\ngrep \"ERROR\" app.log | claude -p \"Categorize these errors by type and frequency. Which is most critical?\"\n\n# CI\u002FCD integration\nnpm test 2>&1 | claude -p \"If tests failed, explain why and suggest fixes\"\n```\n\n**Why it works:** Claude integrates with Unix pipelines. Composable with existing tools.\n\n### Synergy 11: Schema-Driven Development [COMMUNITY]\n\nDatabase schema as source of truth:\n\n```bash\n# Generate types from schema\n\"Read prisma\u002Fschema.prisma and generate TypeScript interfaces\nin src\u002Ftypes\u002Fdatabase.ts. Include JSDoc comments explaining each field.\"\n\n# Create API endpoints from schema\n\"Based on the User model in schema.prisma, create CRUD endpoints\nin src\u002Fapi\u002Fusers.ts. Include validation using zod.\"\n\n# Generate test fixtures\n\"Read the schema and create realistic test fixtures in\ntests\u002Ffixtures\u002Fusers.ts. Cover edge cases: empty strings,\nmax lengths, special characters.\"\n\n# Migration safety check\n\"Compare prisma\u002Fschema.prisma with the current database.\nIdentify breaking changes. Suggest migration strategy.\"\n```\n\n**Why it works:** Schema is the contract. Generate everything from it. Single source of truth.\n\n### Synergy 12: Dependency Management [COMMUNITY]\n\nUpdate, test, and fix in one flow:\n\n```bash\n# Check for updates\n\"Run npm outdated. For each major update, explain breaking changes\nand effort to upgrade.\"\n\n# Upgrade with safety net\n\"Upgrade lodash to v5. Run tests. If anything breaks, fix it.\nCommit only when tests pass.\"\n\n# Security audit flow\n\"Run npm audit. For each vulnerability:\n1. Check if we actually use the affected code path\n2. If yes, upgrade or find alternative\n3. If no, document why it's acceptable\"\n\n# License compliance\n\"Check licenses of all dependencies. Flag any GPL or unknown\nlicenses. We need MIT\u002FApache\u002FBSD only.\"\n```\n\n**Why it works:** Dependency management is tedious. Claude handles the research and fixes.\n\n### Synergy 13: Documentation Generation [COMMUNITY]\n\nCodebase exploration → living documentation:\n\n```bash\n# API documentation\n\"Explore src\u002Fapi\u002F and generate OpenAPI spec in docs\u002Fapi.yaml.\nInclude request\u002Fresponse examples from actual code.\"\n\n# Architecture documentation\n\"Analyze the codebase structure. Create docs\u002FARCHITECTURE.md\nexplaining: folder structure, data flow, key patterns used.\"\n\n# Onboarding guide\n\"Create docs\u002FONBOARDING.md for new developers. Include:\nsetup steps, key files to understand first, common tasks,\ngotchas you found in the code.\"\n\n# Changelog from commits\n\"Read git log for the last month. Generate CHANGELOG.md\ngrouped by: Features, Fixes, Breaking Changes.\"\n```\n\n**Why it works:** Documentation stays in sync with code. Generated from source, not memory.\n\n### Synergy 14: Refactoring with Safety Net [COMMUNITY]\n\nLarge refactors without breaking things:\n\n```bash\n# Rename with confidence\n\"Rename the User class to Account across the entire codebase.\nUpdate all imports, types, and documentation. Run tests after.\"\n\n# Extract component\n\"The Dashboard component is 500 lines. Extract the chart logic\ninto src\u002Fcomponents\u002FDashboardChart.tsx. Keep all behavior identical.\nTests must still pass.\"\n\n# Change data structure\n\"Migrate from storing user.fullName to user.firstName + user.lastName.\nUpdate: database schema, API responses, frontend display, tests.\nCreate migration script for existing data.\"\n\n# Upgrade patterns\n\"Replace all callback-style async code in src\u002Fservices\u002F with\nasync\u002Fawait. One file at a time. Test after each file.\"\n```\n\n**Why it works:** TodoWrite tracks progress. Tests verify correctness. Safe incremental changes.\n\n### Synergy 15: Incident Response [COMMUNITY]\n\nDebug production issues systematically:\n\n```bash\n# Initial triage\n\"Production is returning 500 errors. Here's the error log:\n[paste log]\nIdentify the most likely cause. List files to investigate.\"\n\n# Root cause analysis\n\"Read the files identified. Trace the code path from\nAPI endpoint to error. Explain exactly where and why it fails.\"\n\n# Fix with minimal blast radius\n\"Implement the smallest possible fix. Don't refactor.\nJust stop the bleeding. Add a TODO for proper fix later.\"\n\n# Post-mortem documentation\n\"Create docs\u002Fincidents\u002F2024-01-15-500-errors.md documenting:\nwhat happened, root cause, fix applied, prevention measures.\"\n```\n\n**Why it works:** Structured approach prevents panic. Documentation prevents recurrence.\n\n### Prompting Best Practices [OFFICIAL]\n\nBased on [Anthropic's guidance](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fclaude-code-best-practices):\n\n| Instead of... | Write... |\n|---------------|----------|\n| \"Add tests\" | \"Write Jest tests for src\u002Futils\u002Fdate.ts covering: formatDate with valid dates, invalid inputs, and timezone handling\" |\n| \"Fix the bug\" | \"The login fails when email contains '+'. Fix src\u002Fauth\u002Fvalidate.ts:23 to handle plus signs in email addresses\" |\n| \"Review this\" | \"Review src\u002Fapi\u002Fusers.ts for: N+1 queries, missing error handling, and SQL injection risks\" |\n| \"Make it faster\" | \"Profile the \u002Fapi\u002Fproducts endpoint. Identify the slowest operation and optimize it. Target: \u003C100ms response\" |\n\n**Thinking modes** (escalating reasoning depth):\n- `\"think\"` - Standard extended thinking\n- `\"think hard\"` - More thorough analysis\n- `\"think harder\"` - Deep exploration of options\n- `\"ultrathink\"` - Maximum reasoning budget\n\n**File references:**\n```bash\n# Use tab-completion or explicit paths\n\"Read @src\u002Fauth\u002Flogin.ts and explain the authentication flow\"\n\n# Multiple files\n\"Compare @src\u002Fapi\u002Fv1\u002Fusers.ts and @src\u002Fapi\u002Fv2\u002Fusers.ts - what changed?\"\n```\n\n### Key Principles [COMMUNITY]\n\n**1. Understand the \"when\" of each feature:**\n\n| Feature | Activates When... |\n|---------|-------------------|\n| MCP | External data\u002Faction needed |\n| Skills | Context matches description (automatic) |\n| Commands | User types `\u002Fcommand` (manual) |\n| Hooks | Lifecycle event fires (PreToolUse, PostToolUse, etc.) |\n| Sub-agents | Task delegated for isolated work |\n\n**2. Combinations multiply value:**\n```\nMCP alone           = 1x (fetch data)\nMCP + Skill         = 3x (fetch + auto-expertise)\nMCP + Skill + Hook  = 9x (fetch + expertise + enforce)\n```\nEach layer multiplies the previous. Invest in setup.\n\n**3. Prompting is the foundation:**\nAll synergies fail with vague prompts. Master specificity first:\n- Name exact files\n- State exact requirements\n- Define exact success criteria\n\n**4. We showed 15 synergies. There are many more.**\nThese patterns are starting points. Combine them, adapt them, discover your own. The best workflows are the ones tailored to your project.\n\n**5. Setup cost amortizes:**\nOne hour configuring `.claude\u002F` saves hundreds of hours across future sessions. Treat it as infrastructure.\n\n---\n\n## Examples Library\n\n### Example 1: Adding Authentication\n\n```bash\n# Understanding current system\n> \"Analyze the current user management system\"\n\n# Planning\n> \"Create a plan to add JWT-based authentication\"\n\n# Implementation\n> \"Implement the authentication system following the plan\"\n# (Claude creates TodoWrite tasks and works through them)\n\n# Testing\n> \"Create comprehensive tests for authentication\"\n\n# Security review\n> \"Review the authentication implementation for security issues\"\n\n# Documentation\n> \"Update the API documentation with authentication endpoints\"\n\n# Commit\n> \"Create a git commit for the authentication feature\"\n```\n\n### Example 2: Performance Optimization\n\n```bash\n# Identify issues\n> \"Analyze the codebase for performance bottlenecks\"\n\n# Create optimization plan\n> \"Create a plan to optimize the most critical issues found\"\n\n# Implement optimizations\n> \"Implement the database query optimizations\"\n\n# Benchmark\n> \"Create benchmarks to measure the improvements\"\n\n# Verify\n> \"Run the benchmarks and compare before\u002Fafter\"\n```\n\n### Example 3: Bug Investigation\n\n```bash\n# Provide context\n> \"Users report login fails intermittently. Here's the error log: [paste log]\"\n\n# Investigation with Debug agent\n> \"Use the debugger agent to investigate this issue\"\n\n# Root cause analysis\n> \"Explain what's causing this and why it's intermittent\"\n\n# Fix\n> \"Implement a fix for this issue\"\n\n# Prevention\n> \"Add tests and logging to prevent this in the future\"\n\n# Documentation\n> \"Update CLAUDE.md with what we learned about this issue\"\n```\n\n### Example 4: API Migration\n\n```bash\n# Analyze current API\n> \"Document all endpoints in the v1 API\"\n\n# Plan migration\n> \"Create a migration plan from v1 to v2 with these changes: [list changes]\"\n\n# Implement new version\n> \"Implement the v2 API alongside v1\"\n\n# Ensure backward compatibility\n> \"Create a compatibility layer so v1 clients still work\"\n\n# Testing\n> \"Create tests ensuring both v1 and v2 work correctly\"\n\n# Documentation\n> \"Generate migration guide for API consumers\"\n```\n\n### Example 5: Setting Up CI\u002FCD\n\n```bash\n# Research\n> \"Research GitHub Actions best practices for Node.js projects\"\n\n# Create workflow\n> \"Create a GitHub Actions workflow that:\n   - Runs on pull requests\n   - Checks TypeScript compilation\n   - Runs linting\n   - Runs all tests\n   - Reports coverage\"\n\n# Security scanning\n> \"Add security scanning to the workflow\"\n\n# Deployment\n> \"Add automatic deployment to staging on merge to main\"\n\n# Documentation\n> \"Document the CI\u002FCD setup in README.md\"\n```\n\n### Example 6: Multi-Directory Project\n\n```bash\n# Add directories\n> \"Add the frontend and backend directories to the workspace\"\n\n# Synchronized changes\n> \"Update the User type definition in backend and propagate to frontend\"\n\n# Cross-project validation\n> \"Ensure the frontend API calls match the backend endpoints\"\n\n# Parallel testing\n> \"Run backend tests and frontend tests in parallel in background\"\n\n# Monitor both\n> \"Start both dev servers and monitor for errors\"\n```\n\n### Example 7: Background Development Workflow\n\n```bash\n# Start all development services in background\n> \"Start the frontend dev server in background\"\n> \"Start the backend API server in background\"\n> \"Run tests in watch mode in background\"\n\n# Configure status line to track all services\n\u002Fstatusline\n\n# Monitor all services simultaneously\n> \"Monitor all background processes for errors\"\n\n# Claude watches logs from all background tasks\n# Identifies issues across services\n# Suggests fixes without stopping services\n\n# Fix issues dynamically\n> \"I see an API timeout error\"\n# Claude checks backend logs, identifies cause, suggests solution\n\n# Check all background tasks\n\u002Fbashes\n\n# Stop specific service if needed\n\u002Fkill \u003Cid>\n```\n\n### Example 8: Smart Context Management\n\n```bash\n# Start major feature development\n> \"Build a complete user authentication system with JWT, refresh tokens, and password reset\"\n\n# Work progresses, context accumulates...\n# After reading many files and multiple operations\n# Context is getting large\n\n# Use microcompact for intelligent cleanup\n\u002Fcompact \"focus\"\n# Keeps: Current auth work, recent changes, patterns learned\n# Removes: Old file reads, completed searches, stale context\n\n# Continue seamlessly with clean context\n> \"Add two-factor authentication to the system\"\n# Full context available for current authentication work\n\n# Major context switch to new feature\n\u002Fcompact\n# Complete reset for fresh start\n\n> \"Implement Stripe payment integration\"\n# Clean slate for payment feature\n```\n\n### Example 9: Security-First Development\n\n```bash\n# Plan with security considerations\n> \"Design a user input handling system for our forms. Focus on security best practices\"\n\n# Implement with immediate security review\n> \"Implement the form validation system\"\n> \"Review the form validation code for security vulnerabilities\"\n\n# Fix identified issues\n> \"Fix the XSS vulnerability in the email field validation\"\n> \"Verify the fix addresses all injection vectors\"\n\n# Document security patterns\n> \"Update CLAUDE.md with our input validation security patterns\"\n\n# Set up continuous security monitoring\n> \"Create a GitHub Action that runs security scans on every PR\"\n```\n\n### Example 10: Full-Stack Multi-Repo Development\n\n```bash\n# Initialize multi-repo workspace\n\u002Fadd-dir ~\u002Fprojects\u002Fbackend\n\u002Fadd-dir ~\u002Fprojects\u002Ffrontend\n\u002Fadd-dir ~\u002Fprojects\u002Fshared-types\n\n# Synchronize type definitions across projects\n> \"Update the User type in shared-types and ensure backend and frontend are consistent\"\n\n# Parallel type checking\n> \"Run TypeScript type checking in all three projects simultaneously in background\"\n\n# Monitor and fix type errors\n> \"Check background tasks for any type errors\"\n> \"Fix type mismatches found in frontend\"\n\n# Cross-repo validation\n> \"Verify that all API types in backend match the frontend client expectations\"\n\n# Start all dev servers\n> \"Start backend server, frontend server, and type watching in background\"\n\n# Unified development experience\n> \"Build the checkout flow, coordinating changes across backend API and frontend UI\"\n# Claude makes coordinated changes across all repos\n```\n\n---\n\n## Best Practices\n\n### For Developers [COMMUNITY]\n\n**1. Set Up CLAUDE.md First**\n```markdown\n- Document your project structure\n- List important commands\n- Note conventions and patterns\n- Add known gotchas\n- Update it as you learn\n```\n\n**2. Use Descriptive Requests**\n```bash\n# Good\n> \"Add input validation to the login endpoint, checking email format and password length\"\n\n# Less effective\n> \"Fix login\"\n```\n\n**3. Verify Changes**\n```bash\n# Always review before committing\n> \"Show me all the changes made\"\n> \"Run tests to verify the changes\"\n```\n\n**4. Incremental Development**\n```bash\n# Break large features into steps\n> \"First, let's add the database model\"\n> \"Now add the API endpoint\"\n> \"Finally, add the frontend form\"\n```\n\n**5. Leverage Tools Intelligently**\n```bash\n# Use Grep for finding patterns\n> \"Find all database queries using raw SQL\"\n\n# Use Glob for file discovery\n> \"Find all test files\"\n\n# Use sub-agents for exploration\n> \"Have an Explore agent map out the authentication flow\"\n```\n\n### Decision Patterns [COMMUNITY]\n\nQuick decision trees for common scenarios:\n\n**Something's not working:**\n```\n→ Can you reproduce it?\n  → Yes: Debug systematically\n  → No: Gather more info first\n→ Did it work before?\n  → Yes: Check recent changes (git diff)\n  → No: Check assumptions\n→ Is error message clear?\n  → Yes: Address directly\n  → No: Trace execution with logging\n```\n\n**Adding a new feature:**\n```\n→ Similar feature exists?\n  → Yes: Follow that pattern\n  → No: Research best practices\n→ Touches existing code?\n  → Yes: Understand it first (read, analyze)\n  → No: Design in isolation\n→ Has complex logic?\n  → Yes: Break down first (use TodoWrite)\n  → No: Implement directly\n```\n\n**Code seems slow:**\n```\n→ Measured it? → No: Profile first\n→ Know the bottleneck? → No: Find it (use ultrathink)\n→ Have solution? → No: Research, then implement and measure again\n```\n\n**Recovery When Things Go Wrong:**\n```bash\n# Establish facts\n> \"What's the current state of the codebase?\"\n\n# Find smallest step forward\n> \"What's the simplest fix that would work?\"\n\n# Question assumptions\n> \"Let me re-read the relevant code\"\n\n# Find solid ground\n> \"Let's revert to the last working state with \u002Frewind\"\n```\n\n**Complexity-Driven Approach:**\n| Task Type | Approach |\n|-----------|----------|\n| Trivial (typo fix) | Just fix it |\n| Simple (add button) | Quick implementation |\n| Medium (new feature) | Plan → Implement → Test |\n| Complex (architecture) | Research → Design → Prototype → Implement → Migrate |\n| Unknown | Explore to assess, then choose approach |\n\n### For Teams [COMMUNITY]\n\n**1. Share Configuration**\n```bash\n# Commit to git:\n.claude\u002F\n├── settings.json      # Shared permissions and config\n├── commands\u002F          # Team workflows\n├── skills\u002F            # Team Skills\n└── agents\u002F            # MCP servers & sub-agents\n\n# Git-ignore:\n.claude\u002Fsettings.local.json  # Personal overrides\n```\n\n**2. Document Patterns in CLAUDE.md**\n```markdown\n## Team Conventions\n- All API routes follow RESTful patterns\n- Database migrations use Prisma\n- Tests use the AAA pattern (Arrange, Act, Assert)\n- Never commit directly to main\n```\n\n**3. Create Workflow Skills**\n```bash\n# .claude\u002Fskills\u002F\n├── code-review\u002F\n│   └── SKILL.md\n├── deploy-staging\u002F\n│   └── SKILL.md\n├── run-checks\u002F\n│   └── SKILL.md\n└── security-audit\u002F\n    └── SKILL.md\n```\n\n**4. Use Hooks for Standards**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\"type\": \"command\", \"command\": \"eslint-check.sh\"}\n        ]\n      }\n    ]\n  }\n}\n```\n\n### For Security [COMMUNITY]\n\n**1. Protect Sensitive Files**\n```json\n{\n  \"permissions\": {\n    \"deny\": {\n      \"Write\": [\"*.env\", \".env.*\", \"*.key\", \"*.pem\"],\n      \"Edit\": [\"*.env\", \".env.*\", \"*.key\", \"*.pem\", \".git\u002F*\"]\n    }\n  }\n}\n```\n\n**2. Review Before Execution**\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"ask\"\n  }\n}\n```\n\n**3. Use Hooks for Auditing**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo \\\"$(date): $TOOL_NAME\\\" >> .claude\u002Faudit.log\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**4. Regular Security Reviews**\n```bash\n# Use security review Skill or command\n> \"Perform a security audit of the authentication system\"\n```\n\n---\n\n## Troubleshooting\n\n### Common Issues [COMMUNITY]\n\n**Issue: \"Context too large\" error**\n```bash\n# Solution 1: Compact context\n> \u002Fcompact\n\n# Solution 2: Smart cleanup\n> \u002Fcompact \"focus\"\n\n# Prevention: Regular compaction in long sessions\n```\n\n**Issue: Edit tool fails with \"string not found\"**\n```bash\n# Solution: Read the file first to see exact content\n> Read the file to see the exact string\n\n# Ensure exact match including:\n- Whitespace and indentation\n- Line breaks\n- Special characters\n\n# Use larger context if string appears multiple times\n```\n\n**Issue: Permission denied**\n```bash\n# Solution 1: Grant permission when asked\n\n# Solution 2: Pre-configure in settings.json\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": [\"npm test\"],\n      \"Edit\": {}\n    }\n  }\n}\n\n# Check current permissions\n> \u002Fhooks  # Shows hook configuration\n```\n\n**Issue: Claude doesn't see recent file changes**\n```bash\n# Solution: Explicitly ask to re-read\n> \"Read the app.ts file again\"\n\n# Or provide the changes\n> \"I just updated the config, here's what changed: [paste]\"\n```\n\n**Issue: Background task not responding**\n```bash\n# Check status\n> \u002Fbashes\n\n# Kill if stuck\n> \u002Fkill \u003Cid>\n\n# Restart\n> \"Start the dev server again in background\"\n```\n\n**Issue: Git operations fail**\n```bash\n# Check git status\n> \"Run git status\"\n\n# Common fixes:\n- Unstaged changes: \"git add the files first\"\n- Merge conflicts: \"Show me the conflicts and help resolve\"\n- Branch issues: \"Switch to the correct branch\"\n```\n\n**Issue: MCP server not working**\n```bash\n# Check configuration\n> \"Show me the MCP configuration\"\n\n# Verify server is running\n> \"Check if the MCP server started correctly\"\n\n# Check logs\n~\u002F.claude\u002Flogs\u002Fmcp-\u003Cserver-name>.log\n\n# Reinstall\n> \"Reinstall the MCP server package\"\n```\n\n### Error Recovery Patterns [COMMUNITY]\n\n**Systematic approaches to common error scenarios.**\n\n#### Session Recovery After Disconnect\n\n```bash\n# If session disconnects mid-task:\n1. Check recent history:\n   > \"What was I working on?\"\n\n2. Review file changes:\n   git diff\n\n3. Reconstruct state:\n   > \"Based on recent changes, continue where we left off\"\n```\n\n#### Hook Failures\n\n```bash\n# If hook blocks unexpectedly:\n1. Check hook output:\n   claude --debug\n\n2. Test hook manually:\n   echo '{\"tool_name\":\"Edit\",\"tool_input\":{...}}' | ~\u002F.claude\u002Fhooks\u002Fscript.sh\n\n3. Temporarily disable:\n   mv ~\u002F.claude\u002Fsettings.json ~\u002F.claude\u002Fsettings.json.bak\n\n4. Fix and restore:\n   # Fix the hook script, then restore settings\n```\n\n#### Context Overflow Mid-Task\n\n```bash\n# When \"context too large\" appears during complex work:\n\n# Quick recovery:\n> \u002Fcompact \"focus\"\n> \"Continue with [brief task summary]\"\n\n# Full reset if needed:\n> \u002Fcompact\n> \"Let me brief you: [key context]\"\n\n# Prevention:\n- Use \u002Fcompact \"focus\" every ~50 operations\n- Start fresh sessions for new features\n```\n\n#### Tool Permission Issues\n\n```bash\n# When permissions repeatedly requested:\n\n# Grant permanently:\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": {},      # Allow all bash\n      \"Edit\": {},      # Allow all edits\n      \"Write\": {}      # Allow all writes\n    }\n  }\n}\n\n# Or specific patterns:\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": [\"npm test\", \"npm run build\"]\n    }\n  }\n}\n```\n\n#### Network\u002FAPI Timeouts\n\n```bash\n# If operations timeout:\n\n# Retry with backoff:\n1st attempt → fails\nWait 2s → retry\nWait 4s → retry\nWait 8s → retry\n\n# Switch model if persistent:\n> \"Use a different model to try this\"\n\n# Check network:\nping anthropic.com\ncurl -v https:\u002F\u002Fapi.anthropic.com\n```\n\n#### Lost Work Recovery\n\n```bash\n# If changes weren't saved:\n\n1. Check git:\n   git status\n   git diff\n\n2. Check file backups:\n   ls -la ~\u002F.claude\u002Fbackups\u002F\n\n3. Review session transcript:\n   # Transcripts saved in ~\u002F.claude\u002Ftranscripts\u002F\n\n4. Reconstruct from memory:\n   > \"Based on our conversation, recreate the [feature]\"\n```\n\n#### Debug Mode for Persistent Issues\n\n```bash\n# Enable comprehensive debugging:\nclaude --debug --log-level trace\n\n# Follow logs in real-time:\ntail -f ~\u002F.claude\u002Flogs\u002Fclaude.log\n\n# Filter for specific issues:\ngrep -i error ~\u002F.claude\u002Flogs\u002Fclaude.log\ngrep -i \"mcp\" ~\u002F.claude\u002Flogs\u002Fclaude.log\n```\n\n---\n\n## Security Considerations\n\n### Security Model [OFFICIAL]\n\nClaude Code operates with:\n\n**1. Permission System**\n- Tools require explicit permission\n- Permissions are session-specific\n- Can be pre-configured in settings\n\n**2. Sandboxing** (macOS\u002FLinux)\n```json\n{\n  \"sandbox\": {\n    \"enabled\": true,\n    \"allowUnsandboxedCommands\": false\n  }\n}\n```\n\n**3. File Access Control**\n```json\n{\n  \"permissions\": {\n    \"additionalDirectories\": [\"\u002Fallowed\u002Fpath\"],\n    \"deny\": {\n      \"Read\": [\"*.key\", \"*.pem\"],\n      \"Write\": [\"*.env\"],\n      \"Edit\": [\".git\u002F*\"]\n    }\n  }\n}\n```\n\n### Best Security Practices [COMMUNITY]\n\n**1. Never Commit Secrets**\n```bash\n# Block in settings\n{\n  \"permissions\": {\n    \"deny\": {\n      \"Write\": [\"*.env\", \"*.key\", \"*.pem\", \"*secret*\"],\n      \"Edit\": [\"*.env\", \"*.key\", \"*.pem\", \"*secret*\"]\n    }\n  }\n}\n\n# Use hooks to scan for secrets\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Write|Edit\",\n        \"hooks\": [\n          {\"type\": \"command\", \"command\": \"detect-secrets-hook.sh\"}\n        ]\n      }\n    ]\n  }\n}\n```\n\n**2. Review AI-Generated Code**\n```bash\n# Always review before deploying\n> \"Explain the security implications of this code\"\n> \"Review this for potential vulnerabilities\"\n```\n\n**3. Limit Tool Access**\n```json\n\u002F\u002F For sub-agents doing analysis\n{\n  \"allowedTools\": [\"Read\", \"Grep\", \"Glob\"]  \u002F\u002F No modifications\n}\n\n\u002F\u002F For implementation agents\n{\n  \"allowedTools\": [\"Read\", \"Write\", \"Edit\", \"Bash\"]  \u002F\u002F Can modify\n}\n```\n\n**4. Audit Trails**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"logger.sh\"  \u002F\u002F Log all operations\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**5. Network Restrictions**\n```json\n{\n  \"sandbox\": {\n    \"network\": {\n      \"allowUnixSockets\": [\"\u002Fvar\u002Frun\u002Fdocker.sock\"],\n      \"allowLocalBinding\": true,\n      \"httpProxyPort\": 8080\n    }\n  }\n}\n```\n\n**Source:** [Settings](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings), [Sandboxing](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsandboxing)\n\n---\n\n## SDK Integration\n\n**Claude Code can be used programmatically via TypeScript\u002FPython SDKs.**\n\n### Use Cases [OFFICIAL]\n\n- Automate workflows in CI\u002FCD\n- Build custom tools on top of Claude Code\n- Create automated code review systems\n- Integrate into existing development tools\n- Batch process multiple projects\n\n### TypeScript SDK Example [OFFICIAL]\n\n```typescript\nimport { ClaudeCodeSDK } from '@anthropic-ai\u002Fclaude-code';\n\nconst sdk = new ClaudeCodeSDK({\n  apiKey: process.env.ANTHROPIC_API_KEY\n});\n\n\u002F\u002F Start a session\nconst session = await sdk.startSession({\n  projectDir: '\u002Fpath\u002Fto\u002Fproject',\n  systemPrompt: 'You are a code reviewer'\n});\n\n\u002F\u002F Send a task\nconst response = await session.chat({\n  message: 'Review this codebase for security issues'\n});\n\nconsole.log(response.content);\n\n\u002F\u002F End session\nawait session.end();\n```\n\n### Python SDK Example [OFFICIAL]\n\n```python\nfrom anthropic_sdk import ClaudeCodeSDK\n\nsdk = ClaudeCodeSDK(api_key=os.environ[\"ANTHROPIC_API_KEY\"])\n\n# Start session\nsession = sdk.start_session(\n    project_dir=\"\u002Fpath\u002Fto\u002Fproject\",\n    system_prompt=\"You are a test generator\"\n)\n\n# Send task\nresponse = session.chat(\n    message=\"Generate tests for all API endpoints\"\n)\n\nprint(response.content)\n\n# End session\nsession.end()\n```\n\n**Source:** [SDK Overview](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsdk\u002Fsdk-overview)\n\n---\n\n## Experimental Concepts\n\n> ⚠️ **Warning**: This section contains theoretical concepts and patterns that are NOT verified in official documentation. These are experimental ideas for power users to explore.\n\n### Concept: Cognitive Modes [EXPERIMENTAL]\n\n**Unverified theory** about optimizing Claude's approach based on task type:\n\n```bash\n# Simple Creation Mode\n> \"Create 5 similar React components\"\n# Theory: Parallel processing, template-based\n\n# Optimization Mode\n> \"Optimize this algorithm\"\n# Theory: Deep analysis, multiple approaches\n\n# Research Mode\n> \"Research and implement best practice for X\"\n# Theory: Web search → analysis → implementation pipeline\n```\n\n**Status**: No official documentation supports \"modes\". Claude Code uses the same model for all tasks.\n\n### Concept: Kernel Architecture [EXPERIMENTAL]\n\n**Unverified theoretical framework** about multi-layered intelligence:\n\n```\nTheory:\n┌─────────────────┐\n│   Orchestrator  │\n└────────┬────────┘\n         │\n    ┌────┴────┬────────┬─────────┐\n    │         │        │         │\n  Memory   Intent  Extract  Validate\n  Kernel   Kernel  Kernel   Kernel\n```\n\n**Status**: This is a conceptual model, not an actual Claude Code feature. Claude Code uses:\n- Sub-agents (real feature)\n- Skills (real feature)\n- Hooks (real feature)\n\nBut NOT a \"kernel architecture\" system.\n\n### Concept: Meta-Todo System [EXPERIMENTAL]\n\n**Unverified theory** about advanced task management with AI validation:\n\n```bash\n# Theory: Multi-agent task validation\n1. Intent Capture (4 approaches)\n2. Multi-Agent Validation\n3. Background Execution\n4. Learning Integration\n```\n\n**Status**: TodoWrite is a real tool, but \"meta-todo\" with multi-agent validation is theoretical. Use the actual TodoWrite tool as documented.\n\n### Why These Are Separate [EDITORIAL]\n\nThe original guide mixed:\n- **Real features** (Skills, Hooks, MCP)\n- **Usage patterns** (how to use features)\n- **Theoretical frameworks** (unverified concepts)\n\nThis caused confusion about what Claude Code actually does vs. conceptual ideas.\n\n**For AI Agents reading this**: Focus on sections marked `[OFFICIAL]` and `[COMMUNITY]`. Treat `[EXPERIMENTAL]` as ideas to test, not established features.\n\n---\n\n## Additional Resources\n\n### Official Documentation [OFFICIAL]\n- **Main Docs**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview\n- **CLI Reference**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference\n- **Settings**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings\n- **Skills**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fskills\n- **Hooks**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks\n- **MCP**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fmcp\n- **Sub-Agents**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsub-agents\n- **Plugins**: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fplugins\n\n### Community Resources [COMMUNITY]\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\n- **Awesome Claude Code**: https:\u002F\u002Fgithub.com\u002Fhesreallyhim\u002Fawesome-claude-code\n- **Awesome Claude Skills**: https:\u002F\u002Fgithub.com\u002Ftravisvn\u002Fawesome-claude-skills\n\n### Getting Help\n- **GitHub Issues**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Fissues\n- **Discord**: Check Anthropic's community channels\n- **Documentation**: https:\u002F\u002Fcode.claude.com\n\n---\n\n## Changelog\n\n### Claude Code CLI Releases [OFFICIAL]\n\nFor complete details, see the [official CHANGELOG.md](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Fblob\u002Fmain\u002FCHANGELOG.md).\n\n**Version 2.1.39** (February 10, 2026) - Latest\n- ⚡ Improved terminal rendering performance\n- 🐛 Fixed fatal errors being swallowed instead of displayed\n- 🐛 Fixed process hanging after session close\n- 🐛 Fixed character loss at terminal screen boundary\n- 🐛 Fixed blank lines in verbose transcript view\n\n**Version 2.1.38** (February 10, 2026)\n- 🐛 Fixed VS Code terminal scroll-to-top regression (introduced in 2.1.37)\n- 🐛 Fixed Tab key queueing slash commands instead of autocompleting\n- 🐛 Fixed bash permission matching for commands using environment variable wrappers\n- 🐛 Fixed text between tool uses disappearing when not using streaming\n- 🐛 Fixed duplicate sessions when resuming in VS Code extension\n- 🔒 Improved heredoc delimiter parsing to prevent command smuggling\n- 🔒 Blocked writes to `.claude\u002Fskills` directory in sandbox mode\n\n**Version 2.1.37** (February 7, 2026)\n- 🐛 Fixed `\u002Ffast` not being immediately available after enabling `\u002Fextra-usage`\n\n**Version 2.1.36** (February 7, 2026)\n- ⚡ **Fast mode is now available for Opus 4.6** [NEW]\n\n**Version 2.1.34** (February 6, 2026)\n- 🐛 Fixed crash when agent teams setting changed between renders\n- 🐛 Fixed commands excluded from sandboxing bypassing Bash ask permission when `autoAllowBashIfSandboxed` was enabled\n\n**Version 2.1.33** (February 6, 2026)\n- 🤖 Agent teammate sessions in tmux now correctly send and receive messages\n- 🪝 Added `TeammateIdle` and `TaskCompleted` hook events for multi-agent workflows [NEW]\n- 🔧 Added support for restricting sub-agents via `Task(agent_type)` syntax\n- 📝 Added `memory` frontmatter field for agents (`user`, `project`, or `local` scope)\n- 🔌 Plugin names now shown in skill descriptions for better discoverability\n- 🐛 Fixed extended thinking interruption when submitting new messages\n- 🐛 Fixed API proxy 404 errors on streaming endpoints\n- 🐛 Fixed proxy settings via `settings.json` environment variables not applying to WebFetch\n- 📊 Improved `\u002Fresume` session picker with clean titles (removed raw XML markup)\n- 📝 Enhanced error messages for API connection failures (shows specific causes like ECONNREFUSED, SSL errors)\n- 🔌 [VSCode] Added remote session support with OAuth\n- 🔌 [VSCode] Added git branch and message count to session picker with branch name search\n- 🔌 [VSCode] Fixed scroll-to-bottom under-scrolling on session load\u002Fswitch\n\n**Version 2.1.32** (February 5, 2026)\n- ✨ **Claude Opus 4.6 is now available!** [NEW]\n- 🤖 Added research preview **Agent Teams** feature for multi-agent collaboration [NEW]\n- 🧠 Claude now automatically records and recalls **memories** as it works [NEW]\n- 📊 Added \"Summarize from here\" to message selector for partial conversation summarization\n- 📁 Skills in `.claude\u002Fskills\u002F` within additional directories (`--add-dir`) now load automatically\n- 🐛 Fixed `@` file completion showing incorrect relative paths from subdirectories\n- 🔄 `--resume` now re-uses `--agent` value from previous conversation\n- 🐛 Fixed bash \"Bad substitution\" errors with heredocs containing JavaScript template literals\n- 📊 Skill character budget now scales with context window (2% of context)\n- 🐛 Fixed Thai\u002FLao spacing vowels rendering issues\n- 🔌 [VSCode] Fixed slash commands incorrectly executing with preceding text\n- 🔌 [VSCode] Added spinner when loading past conversations\n\n**Version 2.1.31** (February 4, 2026)\n- 💡 Added session resume hint on exit showing how to continue conversations later\n- 🌐 Added full-width (zenkaku) space input support from Japanese IME in checkbox selection\n- 🤖 Improved system prompts to guide model toward dedicated tools (Read, Edit, Glob, Grep) instead of bash equivalents\n- 🐛 Fixed PDF too large errors permanently locking up sessions\n- 🐛 Fixed bash commands incorrectly reporting \"Read-only file system\" errors in sandbox mode\n- 🐛 Fixed crashes after entering plan mode with missing default fields in `~\u002F.claude.json`\n- 🐛 Fixed `temperatureOverride` being ignored in streaming API path\n- 🐛 Fixed LSP shutdown\u002Fexit compatibility with strict language servers\n- ⚡ Reduced terminal layout jitter during spinner animations\n- 📝 Better PDF and request size error messages (shows actual limits: 100 pages, 20MB)\n- 💰 Removed misleading Anthropic API pricing display for third-party provider users (Bedrock, Vertex, Foundry)\n\n**Version 2.1.30** (February 3, 2026)\n- 📄 Added `pages` parameter for Read tool with PDFs (e.g., `pages: \"1-5\"`) [NEW]\n- 📄 Large PDFs (>10 pages) now return lightweight reference when @mentioned\n- 🔑 Added pre-configured OAuth credentials for MCP servers without Dynamic Client Registration\n- 🔍 Added `\u002Fdebug` command for troubleshooting sessions [NEW]\n- 📊 Added token count, tool uses, and duration metrics in Task results\n- ♿ Added reduced motion mode configuration option (`prefersReducedMotion` setting) [NEW]\n- 🐛 Fixed phantom \"(no content)\" text blocks in API conversation history\n- 🐛 Fixed prompt cache invalidation (now correctly revalidates on tool description\u002Fschema changes)\n- 🐛 Fixed 400 errors after `\u002Flogin` with thinking blocks in conversation\n- 🐛 Fixed hangs when resuming sessions with corrupted transcripts\n- 🐛 Fixed rate limit messages for Max 20x users\n- 🐛 Fixed subagents unable to access SDK-provided MCP tools\n- 🐛 Fixed Windows bash execution failure with `.bashrc` files\n- 🐛 Fixed duplicate sessions in VSCode\n- ⚡ 68% memory reduction for `--resume` with many sessions\n- 📊 `TaskStop` tool now displays stopped command\u002Ftask description\n- ⚡ `\u002Fmodel` executes immediately instead of queuing\n- ⌨️ [VSCode] Multiline input in question dialogs (Shift+Enter)\n\n**Version 2.1.29** (January 31, 2026)\n- ⚡ Fixed startup performance issues when resuming sessions with `saved_hook_context`\n\n**Version 2.1.27** (January 30, 2026)\n- 🔗 Added `--from-pr` flag to resume sessions linked to specific GitHub PR number or URL\n- 🔗 Sessions now automatically link to PRs when created via `gh pr create`\n- 🔒 Permissions now respect content-level `ask` over tool-level `allow` (e.g., `allow: [\"Bash\"], ask: [\"Bash(rm *)\"]`)\n- 🔍 Tool call failures and denials now added to debug logs\n- 🐛 Fixed `\u002Fcontext` command colored output display\n- 🐛 Fixed status bar duplicating background task indicator with PR status\n- 🔌 [VSCode] Enabled Claude in Chrome integration\n- 🪟 [Windows] Fixed bash command execution failing for users with `.bashrc` files\n- 🪟 [Windows] Fixed console windows flashing when spawning child processes\n- 🔌 [VSCode] Fixed OAuth token expiration causing 401 errors after extended sessions\n\n**Version 2.1.25** (January 29, 2026)\n- 🔧 Fixed beta header validation error for gateway users on Bedrock and Vertex\n- 💡 Workaround: Set `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` to avoid the error\n\n**Version 2.1.23** (January 29, 2026)\n- ⚙️ Added customizable spinner verbs setting (`spinnerVerbs`)\n- 🔧 Fixed mTLS and proxy connectivity for users behind corporate proxies or using client certificates\n- 🔧 Fixed per-user temp directory isolation to prevent permission conflicts on shared systems\n- 🐛 Fixed race condition causing 400 errors when prompt caching scope was enabled\n- 🐛 Fixed pending async hooks not being cancelled when headless streaming sessions ended\n- 🐛 Fixed tab completion not updating the input field when accepting a suggestion\n- 🐛 Fixed ripgrep search timeouts silently returning empty results instead of reporting errors\n- ⚡ Improved terminal rendering performance with optimized screen data layout\n- ⏱️ Changed Bash commands to show timeout duration alongside elapsed time\n- 🟣 Changed merged pull requests to show purple status indicator in prompt footer\n- 🔌 [IDE] Fixed model options displaying incorrect region strings for Bedrock users in headless mode\n\n**Version 2.1.22** (January 28, 2026)\n- 🔧 Fixed structured outputs for non-interactive (-p) mode\n\n**Version 2.1.21** (January 28, 2026)\n- 🌐 Added support for full-width (zenkaku) number input from Japanese IME in option selection prompts\n- 🐛 Fixed shell completion cache files being truncated on exit\n- 🐛 Fixed API errors when resuming sessions that were interrupted during tool execution\n- 🐛 Fixed auto-compact triggering too early on models with large output token limits\n- 🐛 Fixed task IDs potentially being reused after deletion\n- 🐛 Fixed file search not working in VS Code extension on Windows\n- 📊 Improved read\u002Fsearch progress indicators to show \"Reading…\" while in progress and \"Read\" when complete\n- 🤖 Improved Claude to prefer file operation tools (Read, Edit, Write) over bash equivalents (cat, sed, awk)\n- 🐍 [VSCode] Added automatic Python virtual environment activation (`claudeCode.usePythonEnvironment` setting)\n- 🔌 [VSCode] Fixed message action buttons having incorrect background colors\n\n**Version 2.1.20** (January 27, 2026)\n- ⌨️ Arrow key history navigation in vim normal mode\n- ⌨️ External editor shortcut (Ctrl+G) added to help menu\n- 📊 PR review status indicator in prompt footer (approved\u002Fchanges requested\u002Fpending\u002Fdraft)\n- 📁 Support for loading `CLAUDE.md` from additional directories via `--add-dir` (requires `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`)\n- 🗑️ Task deletion via `TaskUpdate` tool\n- 📱 Dynamic task list adjustment based on terminal height\n- 📋 `\u002Fcopy` command now available to all users\n- ⚙️ Config backups now timestamped and rotated (keeps 5 most recent)\n- 🐛 Fixed session compaction issues causing full history to load on resume\n- 🐛 Fixed agents ignoring user messages during active work\n- 🐛 Fixed wide character (emoji, CJK) rendering artifacts\n- 🐛 Fixed JSON parsing errors with special Unicode in MCP responses\n- 🐛 Fixed draft prompt loss when navigating command history\n- 🐛 Fixed crashes when cancelling tool use\n\n**Version 2.1.19** (January 23, 2026)\n- ✨ Added env var `CLAUDE_CODE_ENABLE_TASKS` - set to `false` to use legacy task system\n- ✨ Added shorthand `$0`, `$1`, etc. for accessing individual arguments in custom commands\n- 🔄 Changed indexed argument syntax from `$ARGUMENTS.0` to `$ARGUMENTS[0]` (bracket syntax)\n- ✅ Skills without additional permissions\u002Fhooks no longer require approval\n- 🐛 Fixed crashes on processors without AVX instruction support\n- 🐛 Fixed dangling Claude Code processes when terminal is closed (EIO error handling, SIGKILL fallback)\n- 🐛 Fixed `\u002Frename` and `\u002Ftag` not updating correct session when resuming from different directory\n- 🐛 Fixed resuming sessions by custom title from different directories\n- 🐛 Fixed pasted text loss when using prompt stash (Ctrl+S)\n- 🐛 Fixed agent list displaying \"Sonnet (default)\" instead of \"Inherit (default)\"\n- 🐛 Fixed backgrounded hook commands not returning early\n- 🐛 Fixed file write preview omitting empty lines\n- 🔌 [SDK] Added replay of `queued_command` attachment messages as `SDKUserMessageReplay` events\n- 🔌 [VSCode] Enabled session forking and rewind functionality for all users\n\n**Version 2.1.17** (January 22, 2026)\n- 🔧 Fixed crashes on processors without AVX instruction support\n\n**Version 2.1.16** (January 22, 2026)\n- ✨ New task management system with dependency tracking\n- 🔌 [VSCode] Native plugin management support\n- 🔌 [VSCode] OAuth users can browse and resume remote Claude sessions from Sessions dialog\n- 🐛 Fixed out-of-memory crashes when resuming sessions with heavy subagent usage\n- 🐛 Fixed \"context remaining\" warning not hiding after running `\u002Fcompact`\n- 🐛 Fixed session titles on resume screen not respecting user's language setting\n- 🪟 [IDE] Fixed race condition on Windows where Claude Code sidebar view container would not appear on start\n\n**Version 2.1.15** (January 21, 2026)\n- ⚠️ Added deprecation notification for npm installations - users directed to run `claude install` or visit https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fgetting-started\n- ⚡ Improved UI rendering performance with React Compiler\n- 🐛 Fixed \"Context left until auto-compact\" warning not disappearing after `\u002Fcompact`\n- 🐛 Fixed MCP stdio server timeout not killing child process, causing UI freezes\n\n**Version 2.1.14** (January 20, 2026)\n- ⌨️ History-based autocomplete in bash mode (`!`) - press Tab to complete partial commands\n- 🔍 Added search to installed plugins list\n- 📌 Support for pinning plugins to specific git commit SHAs\n- 🔧 Fixed context window blocking limit calculated too aggressively (~65% instead of ~98%)\n- 🐛 Fixed memory issues causing crashes with parallel subagents\n- 🐛 Fixed memory leak in long-running sessions with stream resource cleanup\n- 🐛 Fixed `@` symbol triggering file autocomplete in bash mode\n- 📊 [VSCode] Added `\u002Fusage` command to display current plan usage\n\n**Version 2.1.12** (January 17, 2026)\n- 🔧 Fixed message rendering bug\n\n**Version 2.1.11** (January 17, 2026)\n- 🔧 Fixed excessive MCP connection requests for HTTP\u002FSSE transports\n\n**Version 2.1.10** (January 17, 2026)\n- 🪝 New `Setup` hook event triggered via `--init`, `--init-only`, or `--maintenance` CLI flags\n- ⌨️ Keyboard shortcut 'c' to copy OAuth URL during login\n- 🐛 Fixed bash commands with heredocs containing JavaScript template literals\n- ⚡ Improved startup to capture keystrokes before REPL is ready\n- 📎 File suggestions now show as removable attachments\n- 🔌 [VSCode] Added install count display and trust warning for plugins\n\n**Version 2.1.9** (January 16, 2026)\n- ✨ `auto:N` syntax for MCP tool search auto-enable threshold (context window %)\n- 📁 `plansDirectory` setting to customize plan file storage location\n- ⌨️ External editor support (Ctrl+G) in AskUserQuestion \"Other\" input\n- 🔗 Session URL attribution to commits and PRs from web sessions\n- 🪝 `PreToolUse` hooks can now return `additionalContext` to the model\n- 🔧 `${CLAUDE_SESSION_ID}` string substitution for skills\n- 🐛 Fixed long sessions with parallel tool calls failing with orphan tool_result errors\n- 🐛 Fixed MCP server reconnection hanging on cached connection promise\n- 🐛 Fixed Ctrl+Z suspend not working in Kitty keyboard protocol terminals\n\n**Version 2.1.7** (January 14, 2026)\n- ⚙️ `showTurnDuration` setting to hide turn duration messages\n- 💬 Feedback ability for permission prompts\n- 📱 Inline agent response display in task notifications\n- 🔒 Security fix: wildcard permission rules vulnerability\n- 🪟 Windows file sync compatibility improvements\n- 🔧 MCP tool search auto mode enabled by default\n- 🔗 OAuth\u002FAPI Console URL migration to `platform.claude.com`\n\n**Version 2.1.6** (January 13, 2026)\n- 🔍 Search functionality in `\u002Fconfig` command\n- 📊 Date range filtering in `\u002Fstats` (7\u002F30 days, all-time)\n- 🔄 Updates section in `\u002Fdoctor` command\n- 📁 Nested `.claude\u002Fskills` directory discovery\n- 📈 `context_window.used_percentage` and `remaining_percentage` status fields\n- 🔒 Permission bypass security fix (shell line continuation)\n\n**Version 2.1.5** (January 12, 2026)\n- 📁 `CLAUDE_CODE_TMPDIR` environment variable for temp directory override\n\n**Version 2.1.3** (January 9, 2026)\n- 🔀 Merged slash commands and skills (simplified mental model)\n- 📻 Release channel toggle (`stable`\u002F`latest`) in `\u002Fconfig`\n- ⚠️ Permission rules unreachability detection and warnings\n- 📝 Fixed plan file persistence across `\u002Fclear`\n- ⏱️ 10-minute tool hook execution timeout\n\n**Version 2.1.2** (January 9, 2026)\n- 🖼️ Source path metadata for dragged images\n- 🔗 OSC 8 hyperlinks for file paths (iTerm support)\n- 🪟 Windows Package Manager (winget) support\n- ⌨️ Shift+Tab in plan mode for \"auto-accept edits\"\n- 🔒 Command injection vulnerability fix in bash processing\n- 🧹 Memory leak fix in tree-sitter parse trees\n- 💾 Large output persistence to disk instead of truncation\n\n**Version 2.1.0** (December 23, 2025)\n- 🔄 Automatic skill hot-reload\n- 🔀 `context: fork` support for skill sub-agents\n- 🌐 `language` setting for Claude's response language\n- ⌨️ Shift+Enter works out-of-box in iTerm2, WezTerm, Ghostty, Kitty\n- 📁 `respectGitignore` setting for per-project control\n- 🎯 Wildcard pattern matching for Bash tool permissions (`*` syntax)\n- ⌨️ Unified `Ctrl+B` backgrounding for bash commands and agents\n- 🌐 `\u002Fteleport` and `\u002Fremote-env` commands for claude.ai subscribers\n- ⚡ Agents can define hooks in frontmatter\n- ✂️ New Vim motions: `;` and `,` repeat, `y` operator, `p`\u002F`P` paste\n- 🔧 `--tools` flag for restricting tool use\n- 📄 `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` environment variable\n- 🖼️ Cmd+V image paste support in iTerm2\n\n**Version 2.0.74** (December 19, 2025)\n- 🔍 **LSP Tool**: Language Server Protocol for code intelligence\n- 📍 Go-to-definition, find references, hover documentation\n- 🖥️ `\u002Fterminal-setup` support for Kitty, Alacritty, Zed, Warp\n- 🎨 `Ctrl+T` shortcut in `\u002Ftheme` for syntax highlighting toggle\n\n**Version 2.0.72** (December 18, 2025)\n- 🌐 Claude in Chrome (Beta) with Chrome extension control\n- ⚡ ~3x faster `@` file suggestions in git repositories\n- ⌨️ Changed thinking toggle from Tab to Alt+T\n\n**Version 2.0.70** (December 16, 2025)\n- ⌨️ Enter key submits prompt suggestions immediately (Tab edits)\n- 🎯 Wildcard syntax `mcp__server__*` for MCP tool permissions\n- 🧠 Improved memory usage (3x reduction for large conversations)\n\n**Version 2.0.67** (December 12, 2025)\n- 💡 Claude now suggests prompts (Tab accepts or Enter submits)\n- 🧠 Thinking mode enabled by default for Opus 4.5\n- 🔍 Search functionality in `\u002Fpermissions` command\n\n**Version 2.0.65** (December 11, 2025)\n- ⌨️ Alt+P (Linux\u002FWindows) or Option+P (macOS) to switch models while typing\n- 📊 Context window information in status line\n- 🔧 `CLAUDE_CODE_SHELL` environment variable for shell detection\n\n**Version 2.0.64** (December 10, 2025)\n- ⚡ Instant auto-compacting\n- 🔄 Asynchronous agents and bash commands with wake-up messages\n- 📊 `\u002Fstats` provides usage stats and engagement metrics\n- 📝 Named session support: `\u002Frename` and `\u002Fresume \u003Cname>`\n- 📁 `.claude\u002Frules\u002F` directory support\n\n**Version 2.0.60** (December 6, 2025)\n- 🔄 Background agent support (agents run while working)\n- 🔧 `--disable-slash-commands` CLI flag\n- 📝 Model name in \"Co-Authored-By\" commit messages\n- 🔀 `\u002Fmcp enable|disable [server-name]` quick toggles\n\n**Version 2.0.51** (November 24, 2025)\n- 🧠 Opus 4.5 released\n- 🖥️ Claude Code for Desktop introduced\n- 📝 Plan Mode builds more precise plans\n\n**Version 2.0.45** (November 19, 2025)\n- ☁️ Azure AI Foundry support\n- 🔐 `PermissionRequest` hook for auto-approve\u002Fdeny logic\n\n**Version 2.0.24** (October 21, 2025)\n- 🛡️ Sandbox mode for BashTool on Linux\u002FMac\n- 🌐 Claude Code Web → CLI teleport support\n\n**Version 2.0.20** (October 17, 2025)\n- ⭐ Claude Skills for reusable prompt templates\n\n**Version 2.0.12** (October 9, 2025)\n- 🔌 Plugin System Released\n- `\u002Fplugin install`, `\u002Fplugin enable\u002Fdisable`, `\u002Fplugin marketplace`\n\n**Version 2.0.10** (October 8, 2025)\n- ✨ Rewrote terminal renderer (buttery smooth UI)\n- 🔀 `@mention` to enable\u002Fdisable MCP servers\n- ⌨️ Tab completion for shell commands in bash mode\n- ✏️ PreToolUse hooks can modify tool inputs\n- ⌨️ Press `Ctrl-G` to edit prompt in system text editor\n\n**Version 2.0.0** (September 29, 2025)\n- 🆕 New native VS Code extension\n- ✨ Fresh UI throughout app\n- ⏪ `\u002Frewind` to undo code changes\n- 📊 `\u002Fusage` for plan limits viewing\n- ⌨️ Tab toggles thinking (sticky)\n- 🔍 Ctrl-R searches history\n- 🤖 SDK became Claude Agent SDK\n- 🔧 `--agents` flag for dynamic subagents\n\n### Breaking Changes & Deprecations [OFFICIAL]\n\n**Version 2.1.x Breaking Changes:**\n\n| Change | Migration Path |\n|--------|----------------|\n| **Windows managed settings path** | Migrate from `C:\\ProgramData\\ClaudeCode\\managed-settings.json` to `C:\\Program Files\\ClaudeCode\\managed-settings.json` |\n| **@-mention MCP enable\u002Fdisable removed** | Use `\u002Fmcp enable \u003Cname>` or `\u002Fmcp disable \u003Cname>` instead |\n| **Tool hook timeout increased** | Now 10 minutes (was 60 seconds) - update scripts if relying on quick timeouts |\n| **SDK minimum zod version** | Requires zod ^4.0.0 as peer dependency |\n\n---\n\n### This Guide's Changelog\n\n**Version 2026.1.13 (February 11, 2026)**\n- Updated to v2.1.39 (latest release)\n- Added v2.1.38 and v2.1.39 changelog entries:\n  - v2.1.39: Terminal rendering performance improvements, fatal error display fix, process hanging fix, screen boundary character fix, verbose transcript blank lines fix\n  - v2.1.38: VSCode scroll-to-top regression fix, Tab key autocomplete fix, bash permission matching fix, streaming text fix, duplicate sessions fix, heredoc security improvements, sandbox skills directory protection\n- Added **Fast Mode** section to Advanced Features with full documentation:\n  - Toggle methods (`\u002Ffast` command, settings)\n  - Pricing table (standard vs fast mode)\n  - Requirements (subscription, extra usage, admin enablement)\n  - Use case guidance (when to use vs avoid)\n  - Rate limit behavior and fallback\n\n**Version 2026.1.12 (February 9, 2026)**\n- Updated to v2.1.37 (latest release)\n- Added v2.1.36 and v2.1.37 changelog entries:\n  - v2.1.37: Fixed `\u002Ffast` not being immediately available after enabling `\u002Fextra-usage`\n  - v2.1.36: **Fast mode now available for Opus 4.6**\n- Added `\u002Fextra-usage` and `\u002Ffast` slash commands to Usage & Stats section\n\n**Version 2026.1.11 (February 7, 2026)**\n- Updated to v2.1.34\n- Added v2.1.32 through v2.1.34 changelog entries:\n  - v2.1.34: Fixed agent teams settings crash, fixed sandbox permission bypass for excluded commands\n  - v2.1.33: TeammateIdle and TaskCompleted hook events, Task(agent_type) restriction syntax, memory frontmatter for agents, improved session picker, VSCode remote session OAuth, multiple bug fixes\n  - v2.1.32: **Claude Opus 4.6 available**, **Agent Teams** feature (research preview), **Auto-Memory** feature, \"Summarize from here\" message selector, skills in --add-dir directories, multiple bug fixes\n- Added new **Agent Teams** section with comprehensive documentation:\n  - Team architecture (lead, teammates, task list, mailbox)\n  - Display modes (in-process, tmux, auto)\n  - Team hooks (TeammateIdle, TaskCompleted)\n  - Keyboard controls and limitations\n- Added **Auto-Memory** feature documentation\n- Added `--teammate-mode` CLI flag for agent team display configuration\n- Added `TeammateIdle` and `TaskCompleted` hook events to hooks table\n- Added `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` and `CLAUDE_CODE_DISABLE_AUTO_MEMORY` environment variables\n- Updated Contents table with Agent Teams link\n\n**Version 2026.1.10 (February 5, 2026)**\n- Updated to v2.1.31 (latest release)\n- Added v2.1.30 and v2.1.31 changelog entries:\n  - v2.1.31: Session resume hint on exit, Japanese IME full-width space support, improved tool preference prompts, PDF error handling fixes, sandbox bash fixes, plan mode crash fix, temperature override fix, LSP compatibility improvements, spinner animation improvements, better error messages\n  - v2.1.30: PDF `pages` parameter for Read tool, `\u002Fdebug` command, `prefersReducedMotion` setting, pre-configured OAuth for MCP, Task result metrics, 68% memory reduction for session resume, VSCode multiline input, multiple bug fixes\n- Added PDF `pages` parameter documentation to Read tool section\n- Added `\u002Fdebug` slash command for troubleshooting sessions\n- Added `prefersReducedMotion` accessibility setting documentation\n- Updated PDF limits documentation (100 pages, 20MB)\n\n**Version 2026.1.9 (February 1, 2026)**\n- Updated to v2.1.29 (latest release)\n- Added v2.1.29 changelog entry:\n  - Startup performance fix for sessions with `saved_hook_context`\n\n**Version 2026.1.8 (January 31, 2026)**\n- Updated to v2.1.27 (latest release at time of update)\n- Added v2.1.25 and v2.1.27 changelog entries:\n  - v2.1.27: `--from-pr` flag for resuming PR-linked sessions, sessions auto-link when created via `gh pr create`, permission priority (content-level `ask` over tool-level `allow`), VSCode Chrome integration, Windows fixes\n  - v2.1.25: Beta header validation fix for gateway users, `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` workaround\n- Added `--from-pr` flag to CLI flags reference\n- Added `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` environment variable documentation\n- Added VSCode Chrome integration feature\n- Added permission priority documentation (content-level rules override tool-level rules)\n\n**Version 2026.1.7 (January 29, 2026)**\n- Updated to v2.1.23 (latest release)\n- Added v2.1.21 through v2.1.23 changelog entries:\n  - v2.1.23: Customizable spinner verbs setting, mTLS\u002Fproxy connectivity fixes, terminal rendering improvements, bash timeout display\n  - v2.1.22: Fixed structured outputs for non-interactive mode\n  - v2.1.21: Japanese IME support, Python virtual environment activation in VSCode, session resume fixes, improved file operation preferences\n- Added `spinnerVerbs` setting documentation for customizing spinner messages\n- Added VSCode Python virtual environment activation feature (`claudeCode.usePythonEnvironment`)\n- Added merged PR purple status indicator behavior\n\n**Version 2026.1.6 (January 27, 2026)**\n- Updated to v2.1.20\n- Added v2.1.20 changelog entries:\n  - Arrow key history navigation in vim normal mode\n  - External editor shortcut (Ctrl+G) in help menu\n  - PR review status indicator in prompt footer\n  - CLAUDE.md loading from `--add-dir` directories (with env var)\n  - Task deletion via TaskUpdate tool\n  - Dynamic task list based on terminal height\n  - `\u002Fcopy` command now available to all users\n  - Config backup rotation (keeps 5 most recent)\n  - Multiple bug fixes (session compaction, wide characters, MCP Unicode, etc.)\n- Added new hook events: `PostToolUseFailure`, `SubagentStart`\n- Added `\u002Fcopy` slash command documentation\n- Added `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` environment variable\n- Added comprehensive Desktop App Features section:\n  - Diff view with inline commenting\n  - Git worktrees for parallel sessions\n  - `.worktreeinclude` file documentation\n  - Installation links for macOS and Windows\n\n**Version 2026.1.5 (January 25, 2026)**\n- Updated to v2.1.19 (latest release)\n- Added v2.1.19 changelog entries:\n  - `CLAUDE_CODE_ENABLE_TASKS` env var to use legacy task system\n  - Shorthand argument syntax (`$0`, `$1`) for custom commands\n  - Changed indexed argument syntax from `$ARGUMENTS.0` to `$ARGUMENTS[0]` (bracket syntax)\n  - Skills without additional permissions\u002Fhooks no longer require approval\n  - VSCode session forking and rewind functionality for all users\n  - Multiple bug fixes (process cleanup, session resume, prompt stash, etc.)\n- Added new CLI flags from official docs:\n  - `--json-schema` for validated JSON output\n  - `--permission-prompt-tool` for MCP permission handling\n  - `--setting-sources` for configuration source control\n  - `--allow-dangerously-skip-permissions` for composable permission bypass\n  - `--include-partial-messages` for streaming events\n  - `--init`, `--init-only`, `--maintenance` Setup hook flags\n- Added indexed arguments documentation with bracket syntax and shorthand\n- Added VSCode session forking and rewind feature\n- Added monitoring\u002Ftelemetry environment variables section\n- Added advanced environment variables (`MAX_THINKING_TOKENS`, `MAX_MCP_OUTPUT_TOKENS`, etc.)\n\n**Version 2026.1.4 (January 23, 2026)**\n- Updated to v2.1.17 (latest release with AVX instruction fix)\n- Added v2.1.14 through v2.1.17 changelog entries:\n  - v2.1.17: Fixed crashes on processors without AVX instruction support\n  - v2.1.16: New task management system with dependency tracking, VSCode native plugin management, OAuth session browsing\n  - v2.1.15: npm installation deprecation notice, React Compiler performance improvements\n  - v2.1.14: History-based autocomplete in bash mode, plugin pinning to git commit SHAs, plugin search\n- Added npm deprecation notice to installation section\n- Added TodoWrite dependency tracking documentation\n- Expanded VSCode Plugin Features section (native plugin management, remote session browsing, `\u002Fusage` command)\n- Added Bash Mode Autocomplete keyboard shortcut section\n- Added Plugin Pinning documentation for git commit SHA pinning\n\n**Version 2026.1.3 (January 18, 2026)**\n- Added v2.1.10 changelog (Setup hook, OAuth copy shortcut, VSCode plugin features)\n- Added new `Setup` hook event for `--init`, `--init-only`, `--maintenance` flags\n- Added `PermissionRequest` hook event documentation\n- Added keyboard shortcut 'c' for copying OAuth URL during login\n- Added VSCode plugin features section (install count display, trust warnings)\n- Fixed hook events table to include all documented events\n\n**Version 2026.1.2 (January 18, 2026)**\n- Updated to v2.1.12 (latest release with message rendering fix)\n- Expanded CLI flags reference with 30+ new flags including:\n  - Remote session flags (`--remote`, `--teleport`, `--fork-session`)\n  - System prompt customization (`--system-prompt`, `--append-system-prompt`)\n  - Tool\u002Fpermission management (`--tools`, `--allowedTools`, `--permission-mode`)\n  - Budget limits (`--max-budget-usd`, `--max-turns`)\n  - MCP configuration (`--mcp-config`, `--strict-mcp-config`)\n- Added 15+ new slash commands from official docs:\n  - `\u002Fbug`, `\u002Fcost`, `\u002Fprivacy-settings`, `\u002Foutput-style`, `\u002Fvim`, `\u002Fsandbox`\n  - `\u002Fagents`, `\u002Finit`, `\u002Finstall-github-app`, `\u002Fpr-comments`, `\u002Freview`\n  - `\u002Fsecurity-review`, `\u002Ftodos`, `\u002Flogin`, `\u002Flogout`, `\u002Frelease-notes`\n- Rewrote MCP Installation section with new transport types:\n  - HTTP transport (recommended for hosted services)\n  - Stdio transport (for local packages)\n  - Installation scopes (local, project, user)\n  - CLI commands (`claude mcp add\u002Flist\u002Fget\u002Fremove`)\n- Fixed `\u002Fmicrocompact` references (now `\u002Fcompact` with optional instructions)\n- Updated OAuth authentication examples for MCP\n\n**Version 2026.1.1 (January 17, 2026)**\n- Updated to v2.1.11 (latest release)\n- Added v2.1.9 through v2.1.11 changelog entries\n- Updated all documentation URLs from docs.anthropic.com to code.claude.com\n- Added new installation methods (curl scripts, Homebrew, WinGet)\n- Added MCP Tool Search `auto:N` syntax documentation\n- Added `plansDirectory` setting documentation\n- Added `${CLAUDE_SESSION_ID}` skill variable substitution\n- Added Breaking Changes & Deprecations section\n- Added PreToolUse `additionalContext` hook feature\n\n**Version 2026.1 (January 2026)**\n- Major update covering v2.0.34 through v2.1.7\n- Added **LSP Tool** documentation (go-to-definition, find references, hover)\n- Added **Thinking Mode** section (Tab toggle, ultrathink, Alt+T)\n- Added **Plan Mode** documentation\n- Added **Background Tasks & Agents** section (Ctrl+B)\n- Added comprehensive **Keyboard Shortcuts** reference\n- Added **Environment Variables** comprehensive list\n- Added **Prompt Suggestions** documentation\n- Added 20+ new slash commands (\u002Frewind, \u002Fstats, \u002Fusage, \u002Fconfig, \u002Fdoctor, \u002Fterminal-setup, \u002Frename, \u002Fresume, \u002Fteleport, \u002Fremote-env, etc.)\n- Added new settings documentation (language, attribution, respectGitignore, etc.)\n- Added `.claude\u002Frules\u002F` directory documentation\n- Added wildcard permissions syntax\n- Updated changelog to v2.1.7\n\n**Version 2025.0 (January 2025)**\n- Complete rewrite focused on verified features\n- Clear separation of official vs. experimental content\n- Added Skills System documentation\n- Added Plugins documentation\n- Added `\u002Fstatusline` and `\u002Fadd-dir` commands\n- Added CLI flags reference section\n- Enhanced `@filename` reference syntax documentation\n- Comprehensive examples and patterns\n- All claims verified against official docs\n\n**Previous versions** mixed Claude.ai web features (REPL, Artifacts) with Claude Code CLI features, causing confusion. This version focuses exclusively on Claude Code CLI.\n\n---\n\n## Auto-Update Pipeline\n\nThis guide is a **living document** that automatically stays current with Claude Code's development.\n\n### How It Works\n\nA bi-daily pipeline (every 2 days at 3am UTC) runs Claude Code to:\n\n1. **Check official sources:**\n   - [Official Docs](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview) - Official documentation\n   - [GitHub Releases](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Freleases) - Version changelog\n   - [Anthropic Changelog](https:\u002F\u002Fwww.anthropic.com\u002Fchangelog) - Product updates\n\n2. **Compare against current guide content**\n\n3. **Update with verified changes:**\n   - New features and capabilities\n   - Changed CLI flags or commands\n   - New tools or integrations\n   - Bug fixes or deprecations\n\n4. **Auto-commit changes** with detailed commit messages\n\n### Update Log\n\nSee [update-log.md](.\u002Fupdate-log.md) for the history of automated updates.\n\n### Manual Trigger\n\nThe update can also be run manually:\n```bash\n.\u002Fscripts\u002Fupdate-guide.sh\n```\n\n---\n\n## License\n\nThis guide is community-maintained and not officially affiliated with Anthropic. Information is gathered from official documentation (code.claude.com) and community experience.\n\nFor official information, always refer to: https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview\n\n---\n\n**End of Guide**\n\n> **For AI Agents**: You've reached the end of the verified Claude Code guide. All features marked `[OFFICIAL]` are documented at code.claude.com. Features marked `[COMMUNITY]` are widely-used patterns. Content in the `[EXPERIMENTAL]` section is theoretical and should be tested before relying on it.\n\n","# 全面的 Claude Code CLI 指南\n\n[![官方文档](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FOfficial_Docs-code.claude.com-blue)](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview) [![GitHub](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FGitHub-anthropics%2Fclaude--code-black)](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code) [![NPM](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FNPM-@anthropic--ai%2Fclaude--code-red)](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@anthropic-ai\u002Fclaude-code) [![自动更新](https:\u002F\u002Fimg.shields.io\u002Fbadge\u002FAuto--Updated-Every%202%20Days-brightgreen)](#auto-update-pipeline)\n\n**快速链接：** [开始使用](#what-is-claude-code) · [命令](#quick-reference) · [MCP 设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fmcp) · [设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings) · [SDK](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsdk) · [变更日志](#changelog)\n\n> **🔄 实时指南**：每 2 天从 [官方文档](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview)、[GitHub 发布](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Freleases) 和 [Anthropic 变更日志](https:\u002F\u002Fwww.anthropic.com\u002Fchangelog) 自动更新。请参阅 [update-log.md](.\u002Fupdate-log.md)。\n\n> **🤖 适用于 AI 代理**：针对人类和 AI 均进行了优化。`[OFFICIAL]` = 来自 code.claude.com。`[COMMUNITY]` = 观察到的模式。`[EXPERIMENTAL]` = 尚未验证。\n\n---\n\n## 什么是 Claude Code？\n\n**Claude Code 是一款驻留在终端中的智能体式 AI 编程助手。** 它能够理解你的代码库，直接编辑文件、运行命令，并通过自然语言对话帮助你更快地编写代码。\n\n**主要功能：**\n- 💬 终端中的自然语言界面\n- 📝 直接编辑文件和执行命令\n- 🔍 全面的项目上下文感知\n- 🔗 通过 MCP（模型上下文协议）实现外部集成\n- 🤖 可通过技能、钩子和插件进行扩展\n- 🛡️ 沙箱执行以确保安全性\n\n**安装方法：**\n```bash\n# 快速安装（macOS、Linux、WSL）\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash\n\n# Windows PowerShell\nirm https:\u002F\u002Fclaude.ai\u002Finstall.ps1 | iex\n\n# Windows CMD\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.cmd -o install.cmd && install.cmd && del install.cmd\n\n# 替代方案：Homebrew（macOS\u002FLinux）\nbrew install --cask claude-code\n\n# 替代方案：WinGet（Windows）\nwinget install Anthropic.ClaudeCode\n\n# 替代方案：NPM（⚠️ 已弃用 - 请使用原生安装方式）\nnpm install -g @anthropic-ai\u002Fclaude-code\n\nclaude --version  # 验证安装\n```\n\n**官方文档：** https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview\n\n---\n\n## 目录\n\n| 入门 | 核心功能 | 实际应用 | 参考 |\n|-----------------|---------------|-----------------|-----------|\n| [什么是 Claude Code？](#what-is-claude-code) | [技能系统](#skills-system) | [开发工作流](#development-workflows) | [安全性](#security-considerations) |\n| [核心概念](#core-concepts) | [内置命令](#built-in-commands) | [工具协同](#tool-synergies) | [SDK 集成](#sdk-integration) |\n| [快速入门指南](#quick-start-guide) | [钩子系统](#hooks-system) | [示例库](#examples-library) | [故障排除](#troubleshooting) |\n| [快速参考](#quick-reference) | [MCP 集成](#mcp-integration) | [最佳实践](#best-practices) | [变更日志](#changelog) |\n| | [子代理](#sub-agents) | | [自动更新流水线](#auto-update-pipeline) |\n| | [代理团队](#agent-teams) | | |\n| | [插件](#plugins) | | |\n\n---\n\n## 快速参考\n\n### 基本命令 [OFFICIAL]\n\n```bash\n# 启动 Claude Code\nclaude                    # 启动交互式会话\nclaude -p \"task\"          # 打印模式（非交互式）\nclaude --continue         # 继续上次会话\nclaude --resume \u003Cid>      # 恢复特定会话\n\n# 会话管理\n\u002Fhelp                     # 显示可用命令\n\u002Fexit                     # 结束会话\n\u002Fcompact                  # 减少上下文大小\n\u002Fcompact [instructions]  # 带有可选重点指令的精简对话\n\n# 后台任务\n\u002Fbashes                   # 列出后台进程\n\u002Fkill \u003Cid>               # 停止后台进程\n\n# 发现\n\u002Fcommands                 # 列出技能和命令\n\u002Fhooks                   # 显示已配置的钩子\n\u002Fskills                  # 列出可用技能（NEW）\n\u002Fplugin                  # 管理插件\n```\n\n**来源：** [CLI 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n### CLI 标志参考 [OFFICIAL]\n\n```bash\n# 输出控制\nclaude -p, --print \"task\"          # 打印模式：非交互式，打印结果并退出\nclaude --output-format json         # 输出格式：文本、json 或 stream-json\nclaude --input-format text          # 输入格式：文本或 stream-json\nclaude --verbose                    # 启用详细日志记录（全程逐轮输出）\n\n# 会话管理\nclaude --continue                   # 从上次会话继续\nclaude --resume \u003Csession-id>        # 根据 ID 或名称恢复特定会话\nclaude --from-pr \u003Cpr>               # 恢复与 GitHub PR 编号或 URL 关联的会话 [NEW]\nclaude --fork-session               # 创建新的会话 ID，而非重复使用原有 ID\nclaude --session-id \u003Cuuid>          # 使用特定会话 ID（必须是有效的 UUID）\n\n# 远程会话（claude.ai 订阅用户）\nclaude --remote \"task\"              # 在 claude.ai 上创建网页会话\nclaude --teleport                   # 将网页会话恢复到本地终端\n\n# 调试与日志记录\nclaude --debug                      # 启用调试模式（可选择性过滤类别）\nclaude --debug \"api,mcp\"            # 调试特定类别\nclaude --debug \"!statsig,!file\"     # 排除某些类别\n\n# 模型与代理配置\nclaude --model \u003Cname>               # 指定模型（sonnet、opus、haiku 或完整名称）\nclaude --fallback-model \u003Cname>      # 默认模型过载时的备用模型（打印模式）\nclaude --agent \u003Cname>               # 指定自定义代理（覆盖设置）\nclaude --agents '\u003Cjson>'            # 通过 JSON 动态定义自定义子代理\n\n# 系统提示自定义\nclaude --system-prompt \"prompt\"     # 替换整个默认系统提示\nclaude --system-prompt-file \u003Cpath>  # 用文件内容替换（仅限打印模式）\nclaude --append-system-prompt \"...\"  # 在默认系统提示后追加内容\nclaude --append-system-prompt-file \u003Cpath>  # 在默认系统提示后追加文件内容（仅限打印模式）\n\n# 工具与权限管理\nclaude --tools \"Bash,Read,Edit\"     # 限制内置工具（使用 \"\" 可禁用所有工具）\nclaude --allowedTools \"Bash(git:*)\" # 不需提示即可执行的工具\nclaude --disallowedTools \"Edit\"     # 从上下文中移除特定工具\nclaude --permission-mode plan       # 以指定权限模式开始\nclaude --dangerously-skip-permissions  # 跳过所有权限提示 ⚠️\nclaude --allow-dangerously-skip-permissions  # 启用绕过选项而不激活 [NEW]\nclaude --permission-prompt-tool \u003Cmcp-tool>  # 用于权限提示的 MCP 工具（非交互式）[NEW]\n\n# 预算与执行限制（打印模式）\nclaude --max-budget-usd 5.00        # API 调用的最大美元金额\nclaude --max-turns 3                # 代理轮次的限制数量\nclaude --json-schema '\u003Cschema>'     # 获取符合模式的验证 JSON 输出（打印模式）[新增]\n\n# 目录与配置\nclaude --add-dir ..\u002Fapps ..\u002Flib     # 添加额外的工作目录\nclaude --plugin-dir .\u002Fmy-plugins    # 从目录加载插件\nclaude --settings .\u002Fsettings.json   # 设置 JSON 文件的路径\nclaude --setting-sources user,project  # 以逗号分隔的设置来源列表 [新增]\nclaude --mcp-config .\u002Fmcp.json      # 从 JSON 文件加载 MCP 服务器\nclaude --strict-mcp-config          # 仅使用 --mcp-config 中的 MCP 服务器\n\n# IDE 与浏览器集成\nclaude --ide                        # 启动时自动连接到 IDE\nclaude --chrome                     # 启用 Chrome 浏览器集成\nclaude --no-chrome                  # 禁用 Chrome 浏览器集成\n\n# 代理团队 [新增]\nclaude --teammate-mode in-process   # 团队成员显示在主终端中\nclaude --teammate-mode tmux         # 每个团队成员在自己的窗格中（需要 tmux\u002FiTerm2）\nclaude --teammate-mode auto         # 自动检测（默认）\n\n# 设置与维护\nclaude --init                       # 运行设置钩子并启动交互模式\nclaude --init-only                  # 运行设置钩子并退出（无交互会话）\nclaude --maintenance                # 运行带有维护触发器的设置钩子并退出\n\n# 其他选项\nclaude --disable-slash-commands     # 禁用所有技能和斜杠命令\nclaude --no-session-persistence     # 禁用会话持久化（打印模式）\nclaude --betas interleaved-thinking # API 请求的测试版头信息\nclaude --include-partial-messages   # 包含部分流式事件（配合 stream-json 使用）[新增]\n```\n\n**常见标志组合：**\n\n```bash\n# 一次性任务并输出 JSON\nclaude --print \"分析这段代码\" --output-format json\n\n# 调试 MCP 和 API 问题\nclaude --debug \"api,mcp\"\n\n# 使用特定模型恢复会话\nclaude --resume auth-refactor --model opus\n\n# 非交互式且有预算限制（CI\u002FCD）\nclaude -p --max-budget-usd 5.00 --output-format json \"运行测试\"\n\n# 用于专业工作的自定义子代理\nclaude --agents '{\"reviewer\":{\"description\":\"代码审查员\",\"prompt\":\"检查代码中的错误\"}}'\n\n# claude.ai 订阅用户的远程会话\nclaude --remote \"修复登录漏洞\"\n```\n\n**来源:** [CLI 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n### 核心工具 [官方]\n\n| 工具 | 用途 | 所需权限 |\n|------|------|----------|\n| **Read** | 读取文件、图片、PDF | 无 |\n| **Write** | 创建新文件 | 是 |\n| **Edit** | 修改现有文件 | 是 |\n| **Bash** | 执行 Shell 命令 | 是 |\n| **Grep** | 使用正则表达式搜索内容 | 无 |\n| **Glob** | 按模式查找文件 | 无 |\n| **TodoWrite** | 任务管理 | 无 |\n| **Task** | 启动子代理 | 无 |\n| **WebFetch** | 获取网页内容 | 是 |\n| **WebSearch** | 搜索网络 | 是 |\n| **NotebookEdit** | 编辑 Jupyter 笔记本 | 是 |\n| **NotebookRead** | 读取 Jupyter 笔记本 | 无 |\n\n**来源:** [设置参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n---\n\n## 核心概念\n\n### 1. Claude Code 的工作原理 [官方]\n\nClaude Code 通过您终端中的 **对话式界面** 运行：\n\n```bash\n# 您描述所需内容\n$ claude\n> “为 API 添加用户认证功能”\n\n# Claude Code:\n1. 分析您的代码库结构\n2. 制定实现计划\n3. 首次请求文件编辑权限\n4. 直接将代码写入您的文件\n5. 可以运行测试并验证更改\n6. 如有要求，创建 Git 提交\n```\n\n**关键原则：**\n- **自然语言**：只需描述需求，无需特殊语法\n- **直接操作**：在获得您的许可后编辑文件并执行命令\n- **上下文感知**：理解整个项目结构\n- **逐步信任**：根据需要请求新操作的权限\n- **可脚本化**：可通过 SDK 自动化\n\n**来源:** [概述](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview)\n\n### 2. 权限模型 [官方]\n\nClaude Code 使用 **渐进式权限系统** 以确保安全：\n\n```bash\n# 权限模式\n“ask”    # 每次使用时提示（新操作的默认设置）\n“allow”  # 不提示直接允许\n“deny”   # 完全阻止\n\n# 权限优先级 [新增 v2.1.27]\n# 内容级规则优先于工具级规则\n# 示例: allow: [\"Bash\"], ask: [\"Bash(rm *)\"]\n#   -> Bash 总体上被允许，但“rm *”命令需要确认\n\n# 需要权限的工具\n- Bash（执行命令）\n- Write\u002FEdit\u002FNotebookEdit（修改文件）\n- WebFetch\u002FWebSearch（访问网络）\n- Skill（技能和自定义命令）\n\n# 不需要权限的工具（安全操作）\n- Read\u002FNotebookRead（读取文件）\n- Grep\u002FGlob（搜索）\n- TodoWrite（任务跟踪）\n- Task（子代理）\n```\n\n**配置权限：**\n\n在您的项目中创建 `.claude\u002Fsettings.json`，或在全局级别创建 `~\u002F.claude\u002Fsettings.json`：\n\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"ask\",\n    \"allow\": {\n      \"Bash\": [\"git status\", \"git diff\", \"git log\", \"npm test\", \"npm run*\"],\n      \"Read\": {},\n      \"Edit\": {}\n    },\n    \"deny\": {\n      \"Write\": [\"*.env\", \".env.*\", \".git\u002F*\"],\n      \"Edit\": [\"*.env\", \".env.*\"]\n    },\n    \"additionalDirectories\": [\n      \"\u002Fpath\u002Fto\u002Fother\u002Fproject\"\n    ]\n  }\n}\n```\n\n**来源:** [设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n### 3. 项目背景 - CLAUDE.md [社区]\n\n项目根目录下的 **CLAUDE.md** 文件可在不同会话间提供持久化的上下文：\n\n\u003Cdetails>\n\u003Csummary>\u003Cstrong>CLAUDE.md 文件示例（点击展开）\u003C\u002Fstrong>\u003C\u002Fsummary>\n\n    # 项目：我的应用\n\n    ## 关键背景信息（请先阅读）\n    - 语言：TypeScript + Node.js\n    - 框架：Express + React\n    - 数据库：PostgreSQL，使用 Prisma ORM\n    - 测试：Jest + React Testing Library\n\n    ## 可用命令\n    npm run dev          # 启动开发服务器（端口 3000）\n    npm test             # 运行所有测试\n    npm run lint         # 运行 ESLint 检查\n    npm run typecheck    # TypeScript 类型检查\n    npm run db:migrate   # 执行 Prisma 数据库迁移\n\n    ## 重要规范\n    - 所有 API 路由位于 \u002Fsrc\u002Froutes，采用 RESTful 风格\n    - 数据库查询使用 Prisma Client\n    - 认证基于 JWT 令牌实现，代码位于 \u002Fsrc\u002Fauth\n    - 前端组件存放在 \u002Fsrc\u002Fcomponents\n    - API 响应格式：{success: boolean, data: any, error?: string}\n\n    ## 常见陷阱及注意事项\n    - 请勿修改 \u002Fgenerated 目录（由 Prisma 自动生成）\n    - 请勿提交 .env 文件，应使用 .env.example\n    - 拉取到新的数据库模式变更后，务必运行 npm run db:migrate\n    - 在 TypeScript 中请避免使用 `any` 类型，请使用明确的类型定义\n\n    ## 文件结构\n    \u002Fsrc\n      \u002Froutes       # Express API 路由\n      \u002Fservices     # 业务逻辑\n      \u002Fmodels       # 类型定义\n      \u002Fmiddleware   # Express 中间件\n      \u002Futils        # 共享工具\n      \u002Fauth         # 认证逻辑\n\n    ## 最新学习心得\n    - [2026-01-15] 处理 Stripe 支付 Webhook 时需要使用 raw body 解析器\n    - [2026-01-10] Redis 连接池配置：{maxRetriesPerRequest: 3}\n\n\u003C\u002Fdetails>\n\n**CLAUDE.md 的作用：**\n- ✅ 在每次会话开始时立即提供项目背景信息\n- ✅ 减少重复解释项目结构的需求\n- ✅ 存储项目特有的开发规范和约定\n- ✅ 记录哪些方法有效、哪些不可取\n- ✅ 可通过 Git 分享给团队成员\n- ✅ 格式经过优化，便于 Claude 快速理解\n\n**注：** 尽管 CLAUDE.md 并非官方功能，但它已成为社区广泛采纳的一种实践。如果项目根目录下存在 CLAUDE.md 文件，Claude Code 会自动读取并解析。\n\n### 4. 工具参考 [官方]\n\n#### Read 工具\n**用途：** 读取并分析文件\n\n```bash\n# 示例\nRead file_path=\"\u002Fsrc\u002Fapp.ts\"\nRead file_path=\"\u002Fdocs\u002Fscreenshot.png\"  # 可以读取图片！\nRead file_path=\"\u002Fdocs\u002Fguide.pdf\"       # 可以读取 PDF！\nRead file_path=\"\u002Fdocs\u002Fguide.pdf\" pages=\"1-5\"  # 读取指定页码的 PDF 内容 [新增 v2.1.30]\n```\n\n**功能：**\n- 可读取任何文本文件（代码、配置、日志等）\n- 支持处理图片（截图、图表、架构图等）\n- 能够解析 PDF 文件，提取文本和图像内容\n- 可解析 Jupyter 笔记本文件（.ipynb）\n- 返回带行号的内容（类似 `cat -n` 格式）\n- 支持通过 offset\u002Flimit 参数读取大文件\n\n**PDF 参数** [新增 v2.1.30]：\n- `pages`：可选参数，用于指定要读取的页码范围（如 `\"1-5\"` 或 `\"1,3,5\"`），以读取特定页面\n- 对于超过 10 页的大 PDF 文件，当被 @ 提及时，仅返回轻量级引用\n- PDF 文件限制：最多 100 页，文件大小不超过 20MB\n\n**特别功能：**\n- **图片：** Claude 可以读取错误截图、UI 设计图、架构示意图等\n- **PDF：** 提取并分析 PDF 内容，适用于文档和需求分析\n- **笔记本：** 完整访问代码单元、Markdown 和输出结果\n\n#### Write 工具\n**用途：** 创建新文件\n\n```bash\nWrite file_path=\"\u002Fsrc\u002FnewFile.ts\"\n      content=\"export const config = {...}\"\n```\n\n**行为：**\n- 创建具有指定内容的新文件\n- 如果文件已存在，则会覆盖原有内容（若需编辑现有文件，请使用 Edit 工具）\n- 每次会话首次使用时需获得权限\n- 如有必要，会自动创建父目录\n\n**最佳实践：** 使用 Edit 工具修改现有文件，而 Write 工具仅用于创建新文件。\n\n#### Edit 工具\n**用途：** 通过精确字符串替换来修改现有文件\n\n```bash\nEdit file_path=\"\u002Fsrc\u002Fapp.ts\"\n     old_string=\"const port = 3000\"\n     new_string=\"const port = process.env.PORT || 3000\"\n```\n\n**重要提示：**\n- 必须完全匹配目标字符串，包括空格和缩进\n- 如果 `old_string` 在文件中不唯一，则操作将失败（此时可扩大上下文范围或使用 `replace_all` 参数）\n- 使用 `replace_all=true` 可替换所有匹配项（适用于重命名场景）\n- 必须先读取文件，才能进行编辑\n\n**常见模式：**\n```bash\n# 1. 读取文件以确认具体内容\nRead file_path=\"\u002Fsrc\u002Fapp.ts\"\n\n# 2. 使用精确字符串匹配进行编辑\nEdit file_path=\"\u002Fsrc\u002Fapp.ts\"\n     old_string=\"function login() {\n  return 'TODO';\n}\"\n     new_string=\"function login() {\n  return authenticateUser();\n}\"\n```\n\n#### Bash 工具\n**用途：** 执行 Shell 命令\n\n```bash\nBash command=\"npm test\"\nBash command=\"git status\"\nBash command=\"find . -name '*.test.ts'\"\n```\n\n**特性：**\n- 可执行任意 Shell 命令\n- 支持后台执行（`run_in_background=true`）\n- 可配置超时时间（默认 2 分钟，最大 10 分钟）\n- Git 操作较为常见（状态、差异、日志、提交、推送）\n\n**安全措施：**\n- 需要权限\n- 可根据设置中的规则模式进行限制\n- 在 macOS\u002FLinux 系统上支持沙盒机制\n\n**常见的 Git 操作模式：**\n```bash\n# 查看当前状态\nBash command=\"git status\"\n\n# 查看更改内容\nBash command=\"git diff\"\n\n# 创建提交\nBash command='git add . && git commit -m \"feat: 添加认证功能\"'\n\n# 查看提交历史\nBash command=\"git log --oneline -10\"\n```\n\n#### Grep 工具\n**用途：** 使用正则表达式搜索文件内容\n\n```bash\n# 查找函数\nGrep pattern=\"function.*auth\" path=\"src\u002F\" output_mode=\"content\"\n\n# 查找带有上下文的 TODO\nGrep pattern=\"TODO\" output_mode=\"content\" -C=3\n\n# 统计出现次数\nGrep pattern=\"import.*from\" output_mode=\"count\"\n\n# 不区分大小写\nGrep pattern=\"error\" -i=true output_mode=\"files_with_matches\"\n```\n\n**参数：**\n- `pattern`：正则表达式模式（ripgrep 语法）\n- `path`：要搜索的目录或文件（默认为当前目录）\n- `output_mode`：\n  - `\"files_with_matches\"`（默认）：仅显示匹配文件的路径\n  - `\"content\"`：显示匹配的行\n  - `\"count\"`：显示每文件的匹配次数\n- `-A`、`-B`、`-C`：上下文行数（分别表示匹配行之后、之前或前后）\n- `-i`：不区分大小写\n- `-n`：显示行号\n- `type`：按文件类型筛选（如 \"js\"、\"py\"、\"rust\" 等）\n- `glob`：按 glob 模式筛选（如 \"*.test.ts\"）\n\n**高效强大：** 内部使用 ripgrep 引擎，在大型代码库中比 Bash 的 grep 命令快得多。\n\n#### Glob 工具\n**用途：** 按模式查找文件\n\n```bash\n# 查找测试文件\nGlob pattern=\"**\u002F*.test.ts\"\n\n# 查找特定扩展名的文件\nGlob pattern=\"src\u002F**\u002F*.{ts,tsx}\"\n\n# 查找配置文件\n通配符模式=\"**\u002Fconfig.{json,yaml,yml}\"\n```\n\n**功能：**\n- 快速模式匹配（适用于任何规模的代码库）\n- 返回按修改时间排序的文件（最近的在前）\n- 支持复杂的 glob 模式（`**` 表示递归，`{}` 表示选项）\n\n#### TodoWrite 工具\n**用途：** 在工作过程中管理任务列表\n\n```bash\nTodoWrite todos=[\n  {\n    \"content\": \"添加认证端点\",\n    \"status\": \"in_progress\",\n    \"activeForm\": \"添加认证端点\"\n  },\n  {\n    \"content\": \"编写集成测试\",\n    \"status\": \"pending\",\n    \"activeForm\": \"编写集成测试\"\n  },\n  {\n    \"content\": \"更新 API 文档\",\n    \"status\": \"pending\",\n    \"activeForm\": \"更新 API 文档\"\n  }\n]\n```\n\n**任务状态：**\n- `\"pending\"` - 尚未开始\n- `\"in_progress\"` - 正在进行中（同一时间只能有一个）\n- `\"completed\"` - 已成功完成\n\n**依赖跟踪** [新功能]：v2.1.16 引入了任务依赖跟踪功能，允许任务定义必须先完成的前置条件。这使得复杂的多步骤工作流能够按照正确的顺序执行。\n\n**最佳实践：**\n- 用于多步骤任务（3 步及以上）\n- 同一时间只保持一个任务为 `in_progress`\n- 完成后立即标记为已完成\n- 使用描述性的 `content`（要做什么）和 `activeForm`（正在做什么）\n\n**适用场景：**\n- ✅ 复杂的多步骤功能\n- ✅ 用户提供多个任务\n- ✅ 需要规划的非 trivial 工作\n- ❌ 单一的简单任务\n- ❌ 简单的操作\n\n#### 任务工具（子代理）\n**用途：** 启动专门处理特定任务的 AI 代理\n\n```bash\n# 探索代码库\nTask subagent_type=\"Explore\"\n     prompt=\"查找所有 API 端点及其认证要求\"\n\n# 通用型代理，用于复杂任务\nTask subagent_type=\"general-purpose\"\n     prompt=\"研究 API 限流的最佳实践，并实现解决方案\"\n```\n\n**可用的子代理类型：**\n- `\"general-purpose\"` - 复杂的多步骤任务、研究、实施\n- `\"Explore\"` - 快速代码库探索（Glob、Grep、Read、Bash）\n\n**适用场景：**\n- 需要网络搜索 + 分析的研究任务\n- 代码库探索（寻找模式、理解架构）\n- 可以独立运行的复杂多步骤操作\n- 在您继续其他任务时进行的后台工作\n\n#### WebFetch 工具\n**用途：** 获取并分析网页内容\n\n```bash\nWebFetch url=\"https:\u002F\u002Fdocs.example.com\u002Fapi\"\n         prompt=\"提取所有端点文档\"\n```\n\n**功能：**\n- 将 HTML 转换为 Markdown 以便分析\n- 可以通过提示提取特定信息\n- 适用于研究文档、文章、参考资料\n\n#### WebSearch 工具\n**用途：** 在网上搜索最新信息\n\n```bash\nWebSearch query=\"React 19 新特性 2024\"\n```\n\n**使用场景：**\n- 研究当前的最佳实践\n- 查找最新的库文档\n- 检查已知问题或解决方案\n- 验证最新框架的功能\n\n**来源：** [CLI 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)、[设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n#### LSP 工具（语言服务器协议）[官方]\n**用途：** 获取代码智能功能，如跳转到定义、查找引用和悬停文档。\n\n```bash\nLSP operation=\"goToDefinition\"\n    filePath=\"src\u002Futils\u002Fauth.ts\"\n    line=42\n    character=15\n```\n\n**可用操作：**\n| 操作 | 描述 |\n|-----------|-------------|\n| `goToDefinition` | 查找符号的定义位置 |\n| `findReferences` | 查找符号的所有引用 |\n| `hover` | 获取符号的文档和类型信息 |\n| `documentSymbol` | 获取文档中的所有符号（函数、类、变量） |\n| `workspaceSymbol` | 在整个工作区中搜索符号 |\n| `goToImplementation` | 查找接口或抽象方法的实现 |\n| `prepareCallHierarchy` | 获取某个位置的调用层次结构 |\n| `incomingCalls` | 查找所有调用该位置函数的方法 |\n| `outgoingCalls` | 查找所有被该位置函数调用的方法 |\n\n**参数：**\n- `operation`（必填）：要执行的 LSP 操作\n- `filePath`（必填）：文件的绝对路径或相对路径\n- `line`（必填）：行号（从 1 开始，与编辑器显示一致）\n- `character`（必填）：字符偏移量（从 1 开始，与编辑器显示一致）\n\n**使用场景：**\n```bash\n# 查找函数的定义位置\n> “跳转到 getUserById 的定义处”\n\n# 查找函数的所有使用处\n> “查找 authenticate 函数的所有引用”\n\n# 获取符号的文档\n> “validateToken 函数是做什么的？”\n\n# 探索代码结构\n> “列出 auth.ts 文件中的所有符号”\n```\n\n**注意：** 必须为文件类型配置 LSP 服务器。如果某种语言没有可用的服务器，则会返回错误。\n\n**来源：** [CLI 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n### 5. 上下文管理 [官方]\n\nClaude Code 通过智能管理来维护对话上下文：\n\n#### 上下文命令\n\n```bash\n\u002Fcompact                   # 减少上下文，移除旧信息\n\u002Fcompact \"keep auth work\"  # 带指令压缩上下文（保留指定内容）\n```\n\n#### 使用时机\n\n**使用 \u002Fcompact 的情况：**\n- 长时间会话且读取了大量文件\n- 出现“上下文过大”错误\n- 完成一项重要任务后希望重新开始\n\n**使用带指令的 \u002Fcompact 的情况：**\n- 上下文变得庞大但仍需保留近期工作\n- 在相关任务之间切换\n- 希望智能清理而不丢失重要上下文\n- 示例：`\u002Fcompact \"keep the authentication implementation context\"`\n\n#### 保留与清除的内容\n\n**保留：**\n- CLAUDE.md 内容（您的项目上下文）\n- 最近的交互和决策\n- 当前任务信息和待办事项\n- 近期仍相关的文件读取\n\n**清除：**\n- 不再需要的旧文件读取\n- 已完成的操作\n- 过时的搜索结果\n- 不再相关的旧上下文\n\n#### 自动上下文管理\n\nClaude Code 可能会在以下情况下自动压缩上下文：\n- 令牌限制即将达到\n- 存在大量旧文件读取\n- 会话持续时间过长\n\n**来源：** [设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n### 6. 工作区管理 [官方]\n\n#### 使用 \u002Fadd-dir 添加目录\n\nClaude Code 可以同时处理多个目录：\n\n```bash\n# 向当前会话添加另一个目录\n\u002Fadd-dir \u002Fpath\u002Fto\u002Fother\u002Fproject\n\n# 跨多个项目工作\n> “更新后端的 User 类型，并将其同步到前端”\n\n# 克劳德现在可以访问这两个目录\n```\n\n**使用场景：**\n- 单体仓库开发（前端 + 后端 + 共享库）\n- 跨项目重构\n- 多个项目中的依赖更新\n- 协调相关仓库之间的变更\n\n**配置：**\n\n你也可以在 `.claude\u002Fsettings.json` 中预先配置额外的目录：\n\n```json\n{\n  \"permissions\": {\n    \"additionalDirectories\": [\n      \"\u002Fpath\u002Fto\u002Ffrontend\",\n      \"\u002Fpath\u002Fto\u002Fbackend\",\n      \"\u002Fpath\u002Fto\u002Fshared-libs\"\n    ]\n  }\n}\n```\n\n#### 状态栏配置与 \u002Fstatusline\n\n自定义状态栏中显示的信息：\n\n```bash\n# 配置状态栏\n\u002Fstatusline\n\n# 选项通常包括：\n# - 当前模型\n# - Token 使用情况\n# - 会话时长\n# - 活跃工具\n# - 后台进程\n```\n\n**好处：**\n- 实时监控 Token 使用情况\n- 跟踪会话时长\n- 查看活跃的后台进程\n- 了解正在使用的工具\n\n**来源:** [CLI 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)\n\n---\n\n## 快速入门指南\n\n### 您的第一个会话\n\n```bash\n# 1. 导航到您的项目\ncd \u002Fpath\u002Fto\u002Fyour\u002Fproject\n\n# 2. 启动 Claude Code\nclaude\n\n# 3. 让 Claude 了解您的项目\n> “阅读代码库并解释项目结构”\n\n# Claude 将会：\n- 查找 README、package.json 或类似的入口文件\n- 阅读相关文件（首次会询问权限）\n- 分析代码结构\n- 提供总结\n\n# 4. 请求分析\n> “检查认证系统是否存在安全问题”\n\n# Claude 将会：\n- 找到与认证相关的文件\n- 分析实现方式\n- 识别潜在漏洞\n- 提出改进建议\n\n# 5. 进行更改\n> “在登录接口上添加限流功能”\n\n# Claude 将会：\n- 规划实现方案\n- 展示将要进行的更改\n- 请求编辑文件的权限\n- 实施更改\n- 可以运行测试来验证\n\n# 6. 创建提交\n> “为这些更改创建一个 Git 提交”\n\n# Claude 将会：\n- 运行 git status 查看更改\n- 审查 git diff\n- 创建描述性的提交信息\n- 提交更改\n```\n\n### 为 Claude Code 设置您的项目\n\n#### 1. 创建 CLAUDE.md [社区]\n\n这提供了在所有会话中持续存在的上下文：\n\n```bash\n# 让 Claude 帮助创建\n> “创建一个 CLAUDE.md 文件，记录该项目的结构、命令和规范”\n\n# 或者手动创建：\n- 使用的语言和框架\n- 重要命令（开发、测试、构建、代码检查）\n- 项目结构概述\n- 编码规范\n- 已知的陷阱或问题\n```\n\n#### 2. 配置权限（可选）[官方]\n\n在您的项目中创建 `.claude\u002Fsettings.json`：\n\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"ask\",\n    \"allow\": {\n      \"Bash\": [\n        \"npm test\",\n        \"npm run*\",\n        \"git status\",\n        \"git diff\",\n        \"git log*\"\n      ],\n      \"Read\": {},\n      \"Grep\": {},\n      \"Glob\": {}\n    },\n    \"deny\": {\n      \"Write\": [\"*.env\", \".env.*\"],\n      \"Edit\": [\"*.env\", \".env.*\", \".git\u002F*\"]\n    }\n  }\n}\n```\n\n此配置：\n- 允许常见的安全命令而无需询问\n- 阻止编辑敏感文件\n- 仍然会为文件修改请求权限\n\n#### 3. 测试设置\n\n```bash\n> “运行测试”\n# 如果已配置，应无需权限提示即可执行\n\n> “有哪些可用的命令？”\n# Claude 将会读取 package.json 并列出脚本\n\n> “CLAUDE.md 里写了什么？”\n# Claude 将会读取并总结您的项目背景\n```\n\n**来源:** [快速入门](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fquickstart)、[设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n---\n\n## 高级功能\n\n### 思考模式 [官方]\n\nClaude Code 支持扩展思考，适用于复杂的推理任务。Opus 4.5 默认启用了思考模式。\n\n**激活方法：**\n\n```bash\n# 使用快捷键切换\nAlt+T（或 macOS 上的 Option+T） # 切换思考模式的开启与关闭\n\n# 或者使用自然语言\n> “思考一下这个问题”\n> “更深入地思考架构问题”\n> “针对这个安全问题进行超深度思考”\n\n# Tab 键（粘性切换）\n按下 Tab 键可在后续提示中保持思考模式的开启或关闭状态\n```\n\n**思考级别：**\n| 触发条件 | 思考预算 | 使用场景 |\n|----------|----------|----------|\n| `think`  | 标准     | 一般推理、代码分析 |\n| `think harder` | 扩展   | 复杂问题、多种解决方案 |\n| `ultrathink` | 最大   | 关键决策、深度架构分析 |\n\n**最佳实践：**\n- 对于复杂问题的调试，使用 `think harder`\n- 对于架构决策或安全审查，使用 `ultrathink`\n- 思考内容可以在 `Ctrl+O` 的转录模式中查看\n- 思考模式具有粘性——除非手动关闭，否则会一直保持开启状态\n\n**来源:** [思考模式](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fthinking-mode)\n\n### 快速模式 [新] [官方]\n\n快速模式是 Claude Opus 4.6 的高速配置，使响应速度提升 **2.5 倍**，但每 token 的成本更高。自 v2.1.36 版本起可用。\n\n**切换快速模式：**\n```bash\n# 使用内置命令切换\n\u002Ffast          # 开启或关闭快速模式\n\n# 或在设置中启用\n\"fastMode\": true   # 在用户设置文件中\n```\n\n**视觉指示器：**\n- 当快速模式激活时，提示旁边会出现 `↯` 图标\n- 在速率限制冷却期间，图标会变为灰色\n\n**定价（每 MTok）：**\n| 模式         | 输入 (\u003C200K) | 输出 | 输入 (>200K) | 输出 |\n|--------------|--------------|------|--------------|------|\n| 标准 Opus 4.6 | $15        | $75  | $15        | $75  |\n| 快速模式     | $30        | $150 | $60        | $225 |\n\n**注意：** 快速模式在 2026 年 2 月 16 日之前享受 50% 折扣。\n\n**要求：**\n- 需要有 Claude 订阅计划（Pro\u002FMax\u002FTeam\u002FEnterprise）或 Claude Console API\n- 需启用额外用量（`\u002Fextra-usage`）\n- 不适用于第三方提供商（Bedrock、Vertex、Azure Foundry）\n- 对于团队\u002F企业版：管理员必须在组织设置中启用\n\n**何时使用：**\n- ✅ 快速迭代代码更改\n- ✅ 实时调试会话\n- ✅ 时间敏感的工作\n- ❌ 长时间的自主任务（成本较高）\n- ❌ 批量处理或 CI\u002FCD 流程\n\n**快速模式与努力等级：**\n| 设置       | 效果 |\n|------------|------|\n| **快速模式** | 质量相同，延迟更低，成本更高 |\n| **较低的努力等级** | 响应更快，但质量可能稍低 |\n\n您可以将两者结合使用，以在简单任务上获得最大速度。\n\n**速率限制：**\n- 与标准 Opus 4.6 的速率限制分开\n- 冷却期间会自动回落到标准模式\n- 冷却结束后重新启用\n\n**来源:** [快速模式](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Ffast-mode)\n\n### 计划模式 [官方]\n\n计划模式通过选择合适的模型，为复杂任务提供结构化的规划。\n\n```bash\n# 进入计划模式\n\u002Fplan\n\n# 或者 Claude 可能会在遇到复杂任务时建议进入计划模式\n> “实现一个完整的认证系统”\n\n# 克劳德：“这是一项复杂的任务。您希望我先制定一个计划吗？”\n```\n\n**计划模式功能：**\n- **Opus规划，Sonnet执行** - 使用更强的模型进行规划，更快的模型进行实施\n- **SonnetPlan模式** - Sonnet规划，Haiku执行（经济高效）\n- **Shift+Tab** - 在计划模式下自动接受编辑\n- **计划持久化** - 计划在 `\u002Fclear` 后仍会保留\n\n**计划模式工作流程：**\n1. 克劳德分析任务并创建结构化计划\n2. 您审查并批准或修改计划\n3. 克劳德逐步执行计划\n4. 进度通过TodoWrite进行跟踪\n\n**来源:** [计划模式](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fplan-mode)\n\n### 后台任务与代理 [官方]\n\n在继续工作的同时，在后台运行命令和代理。\n\n**快捷键：**\n```bash\nCtrl+B  # 将当前命令或代理置于后台（统一快捷键）\n```\n\n**后台命令：**\n```bash\n# 在后台启动命令\n> “在后台运行开发服务器”\n> “在后台以监听模式启动测试”\n\n# 或者在命令前加上 &\n> “& npm run dev”\n\n# 查看后台任务\n\u002Ftasks\n\u002Fbashes\n\n# 杀死某个后台任务\n\u002Fkill \u003C任务编号>\n```\n\n**后台代理：**\n```bash\n# 在后台启动代理\n> “让Explore代理在后台分析代码库架构”\n\n# 代理异步运行，并在完成时通知您\n# 当后台代理完成时，您会收到唤醒消息\n```\n\n**特性：**\n- 实时输出流到状态栏\n- 任务完成时的唤醒通知\n- 多个并发后台进程\n- 大量输出可持久化到文件中\n\n**来源:** [后台任务](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fbackground-tasks)\n\n### 自动记忆 [新功能]\n\nClaude Code 现在会在工作时自动记录和回忆记忆（v2.1.32及以上版本）。\n\n**工作原理：**\n- 克劳德会自动记住重要的上下文、决策和模式\n- 记忆会跨会话保存，并为未来的工作提供参考\n- 无需手动干预\n\n**代理的记忆范围：**\n```markdown\n---\nname: my-agent\nmemory: project  # 选项：user, project, local\n---\n```\n\n| 范围 | 存储位置 | 是否共享 |\n|-------|---------|--------|\n| `user` | `~\u002F.claude\u002F` | 所有项目 |\n| `project` | `.claude\u002F` | 团队通过git共享 |\n| `local` | `.claude\u002F*.local.*` | 否（被gitignore忽略） |\n\n**禁用自动记忆：**\n```bash\nexport CLAUDE_CODE_DISABLE_AUTO_MEMORY=1\n```\n\n### 键盘快捷键 [官方]\n\n**导航与编辑：**\n| 快捷键 | 动作 |\n|----------|--------|\n| `Ctrl+R` | 搜索命令历史 |\n| `Ctrl+O` | 查看对话记录（显示思考块） |\n| `Ctrl+G` | 在系统文本编辑器中编辑提示 |\n| `Ctrl+Y` | 类似Readline的粘贴（yank） |\n| `Alt+Y` | yank-pop（循环剪切板环） |\n| `Ctrl+B` | 将当前命令\u002F代理置于后台 |\n| `Ctrl+Z` | 暂停\u002F撤销 |\n\n**模型与模式切换：**\n| 快捷键 | 动作 |\n|----------|--------|\n| `Alt+P`（Win\u002FLinux）\u002F `Option+P`（macOS） | 在输入时切换模型 |\n| `Alt+T`（Win\u002FLinux）\u002F `Option+T`（macOS） | 切换思考模式 |\n| `Tab` | 切换思考模式（固定）\u002F接受建议 |\n| `Shift+Tab` | 自动接受编辑（计划模式）\u002F切换模式（Windows） |\n\n**输入与提交：**\n| 快捷键 | 动作 |\n|----------|--------|\n| `Enter` | 提交提示 \u002F 立即接受建议 |\n| `Shift+Enter` | 新行（适用于iTerm2、WezTerm、Ghostty、Kitty） |\n| `Tab` | 编辑\u002F接受提示建议 |\n| `Ctrl+T` | 在 `\u002Ftheme` 中切换语法高亮 |\n\n**图片与文件处理：**\n| 快捷键 | 动作 |\n|----------|--------|\n| `Cmd+V`（macOS）\u002F `Alt+V`（Windows） | 从剪切板粘贴图片 |\n| `Cmd+N` \u002F `Ctrl+N` | 新对话（VSCode） |\n\n**Vim绑定（若启用）：**\n| 快捷键 | 动作 |\n|----------|--------|\n| `;` 和 `,` | 重复上次动作 |\n| `y` | 复制操作符 |\n| `p` \u002F `P` | 粘贴 |\n| `Alt+B` \u002F `Alt+F` | 单词导航 |\n\n**登录与认证：**\n| 快捷键 | 动作 |\n|----------|--------|\n| `c` | 登录时复制OAuth链接 |\n\n**Bash模式自动补全** [新功能 v2.1.14]：\n| 快捷键 | 动作 |\n|----------|--------|\n| `!` + `Tab` | 基于历史的自动补全 - 完成历史中的部分命令 |\n\n### 提示建议 [官方]\n\nClaude Code 会根据上下文提供建议提示（默认已启用）。\n\n```bash\n# 克劳德会给出上下文相关的提示\n> _  # 光标闪烁\n# 出现建议：“回顾我们所做的更改”\n\n# 按Tab键编辑建议\nTab → 编辑建议内容\n\n# 按Enter键立即提交\nEnter → 按原样提交建议\n```\n\n**配置：**\n```bash\n# 在\u002Fconfig中切换\n\u002Fconfig\n# 搜索“提示建议”\n# 切换开启\u002F关闭\n```\n\n### 环境变量 [官方]\n\n**核心配置：**\n| 变量 | 描述 |\n|----------|-------------|\n| `ANTHROPIC_API_KEY` | 你的 API 密钥 |\n| `CLAUDE_CODE_SHELL` | 覆盖 shell 检测 |\n| `CLAUDE_CODE_TMPDIR` | 自定义临时目录 |\n| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | 禁用后台任务系统 |\n| `CLAUDE_CODE_ENABLE_TASKS` | 设置为 `false` 以使用旧版任务系统 [新增 v2.1.19] |\n\n**显示与 UI：**\n| 变量 | 描述 |\n|----------|-------------|\n| `CLAUDE_CODE_HIDE_ACCOUNT_INFO` | 在 UI 中隐藏账户信息 |\n\n**Bash 与命令：**\n| 变量 | 描述 |\n|----------|-------------|\n| `BASH_DEFAULT_TIMEOUT_MS` | 默认的 bash 命令超时时间 |\n| `BASH_MAX_TIMEOUT_MS` | 允许的最大超时时间 |\n| `CLAUDE_BASH_NO_LOGIN` | 不使用登录 shell |\n| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | 保持工作目录 |\n| `CLAUDE_CODE_SHELL_PREFIX` | Shell 命令前缀 |\n\n**模型配置：**\n| 变量 | 描述 |\n|----------|-------------|\n| `ANTHROPIC_DEFAULT_SONNET_MODEL` | 覆盖默认的 Sonnet 模型 |\n| `ANTHROPIC_DEFAULT_OPUS_MODEL` | 覆盖默认的 Opus 模型 |\n| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | 覆盖默认的 Haiku 模型 |\n| `ANTHROPIC_LOG` | 启用调试日志 |\n\n**MCP 配置：**\n| 变量 | 描述 |\n|----------|-------------|\n| `MCP_TIMEOUT` | MCP 连接超时时间 |\n| `MCP_TOOL_TIMEOUT` | 单个工具的超时时间 |\n\n**文件与上下文：**\n| 变量 | 描述 |\n|----------|-------------|\n| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | 文件读取的最大 token 数 |\n| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | 设置为 `1` 以从 `--add-dir` 目录加载 CLAUDE.md [新增] |\n| `CLAUDE_PROJECT_DIR` | 覆盖项目目录 |\n| `CLAUDE_PLUGIN_ROOT` | 插件根目录替换 |\n| `CLAUDE_CONFIG_DIR` | 自定义配置目录 |\n| `XDG_CONFIG_HOME` | XDG 配置基础路径 |\n\n**网络与代理：**\n| 变量 | 描述 |\n|----------|-------------|\n| `NODE_EXTRA_CA_CERTS` | 自定义 CA 证书 |\n| `NO_PROXY` | 代理绕过列表 |\n| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | 代理 DNS 解析 |\n\n**自动更新与插件：**\n| 变量 | 描述 |\n|----------|-------------|\n| `DISABLE_AUTOUPDATER` | 禁用自动更新 |\n| `FORCE_AUTOUPDATE_PLUGINS` | 强制更新插件 |\n| `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY` | 停止后的退出延迟 |\n\n**监控与遥测：**\n| 变量 | 描述 |\n|----------|-------------|\n| `CLAUDE_CODE_ENABLE_TELEMETRY` | 启用 OpenTelemetry 数据采集 (`1`) |\n| `OTEL_METRICS_EXPORTER` | OTel 指标导出器（例如 `otlp`） |\n| `DISABLE_TELEMETRY` | 退出 Statsig 遥测 (`1`) |\n| `DISABLE_ERROR_REPORTING` | 退出 Sentry 错误报告 (`1`) |\n| `DISABLE_COST_WARNINGS` | 禁用成本警告消息 (`1`) |\n\n**高级设置：**\n| 变量 | 描述 |\n|----------|-------------|\n| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | 禁用 anthropic-beta 头部（网关用户的 workaround） |\n| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | 启用代理团队功能 (`1`) [新增] |\n| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | 禁用自动记忆记录 (`1`) [新增] |\n| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | 禁用后台任务系统 (`1`) |\n| `DISABLE_INTERLEAVED_THINKING` | 禁用交错思考 |\n| `USE_BUILTIN_RIPGREP` | 使用内置 ripgrep |\n| `CLOUD_ML_REGION` | Vertex 的云 ML 区域 |\n| `AWS_BEARER_TOKEN_BEDROCK` | AWS bearer token |\n| `MAX_THINKING_TOKENS` | 扩展思考预算（默认：31,999） |\n| `MAX_MCP_OUTPUT_TOKENS` | 最大 MCP 工具响应 token 数（默认：25,000） |\n| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | 最大输出 token 数（默认：32,000，最大：64,000） |\n| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | 禁用自动更新、错误报告和遥测 |\n\n### 新设置 [官方]\n\n近期新增的设置（可在 `\u002Fconfig` 或 `settings.json` 中配置）：\n\n```json\n{\n  \u002F\u002F 回应语言\n  \"language\": \"en\",  \u002F\u002F Claude 的回应语言\n\n  \u002F\u002F Git 集成\n  \"attribution\": true,  \u002F\u002F 在提交署名中添加模型名称\n  \"respectGitignore\": true,  \u002F\u002F 搜索时尊重 .gitignore\n\n  \u002F\u002F UI 偏好\n  \"showTurnDuration\": true,  \u002F\u002F 显示回合持续时间消息\n  \"fileSuggestion\": \"custom-cmd\",  \u002F\u002F 自定义 @ 文件搜索命令\n  \"spinnerVerbs\": [\"analyzing\", \"thinking\", \"processing\"],  \u002F\u002F 自定义旋转动画文案\n  \"prefersReducedMotion\": false,  \u002F\u002F 减少 UI 动画以提升可访问性 [新增 v2.1.30]\n\n  \u002F\u002F 会话行为\n  \"companyAnnouncements\": true,  \u002F\u002F 显示公司公告\n\n  \u002F\u002F 计划模式\n  \"plansDirectory\": \".claude\u002Fplans\"  \u002F\u002F 自定义计划文件目录\n}\n```\n\n**技能变量替换：** [新增]\n```markdown\n# 在技能文件中，使用 ${CLAUDE_SESSION_ID} 进行会话特定的操作\n会话 ID：${CLAUDE_SESSION_ID}\n```\n\n**项目规则：**\n```bash\n# 新增：.claude\u002Frules\u002F 目录用于项目特定规则\n.claude\u002Frules\u002F\n├── coding-style.md      # 编码规范\n├── testing.md           # 测试要求\n└── security.md          # 安全指南\n```\n\n**通配符权限：**\n```json\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": [\"npm *\", \"git *\"],  \u002F\u002F 通配符模式\n      \"mcp__myserver__*\": {}       \u002F\u002F MCP 工具通配符\n    }\n  }\n}\n```\n\n---\n\n## 技能系统\n\n**技能是统一的功能模块，扩展了 Claude Code 的能力——既可以由 Claude 自动激活，也可以通过 `\u002F技能名` 手动调用。**\n\n> **注意：** 自定义斜杠命令（`.claude\u002Fcommands\u002F` 文件）已于 v2.1.3 合并到技能中。你现有的命令文件仍可继续使用。建议新工作采用技能，因为它支持附加功能，如支持文件、调用控制和子代理执行。请参阅 [命令迁移至技能](#migration-commands-to-skills)。\n\nClaude Code 的技能遵循 [Agent Skills](https:\u002F\u002Fagentskills.io) 开放标准，该标准适用于多种 AI 工具。Claude Code 在此基础上增加了调用控制、子代理执行和动态上下文注入等功能。\n\n### 什么是技能？[官方]\n\n技能是以 `SKILL.md` 文件形式封装的指令，用于扩展 Claude Code 的功能。Claude 会在相关请求时加载这些技能，或者你可以直接调用它们：\n\n```\n# Claude 根据你的请求自动激活技能\n你： “检查这段代码是否存在安全问题”\nClaude： [自动加载安全审查技能]\n\n# 或者你直接调用技能\n你： \u002Fsecurity-reviewer src\u002Fauth.ts\nClaude： [加载并执行安全审查技能]\n```\n\n**两种类型的技能内容：**\n\n- **参考内容** — Claude 应用于当前工作的知识（规范、模式、风格指南）。在对话上下文中内联运行。\n- **任务内容** — 针对特定操作的分步说明（部署、提交、代码生成）。通常通过 `\u002F技能名` 手动调用。\n\n### 技能的存储位置 [官方]\n\n技能的存储位置决定了谁可以使用它：\n\n| 位置         | 路径                                      | 适用范围                     |\n|--------------|-------------------------------------------|------------------------------|\n| **企业级**   | [托管设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fpermissions#managed-settings) | 组织内的所有用户             |\n| **个人级**   | `~\u002F.claude\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md`  | 您的所有项目                 |\n| **项目级**   | `.claude\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md`    | 仅限当前项目                 |\n| **插件级**   | `\u003Cplugin>\u002Fskills\u002F\u003Cskill-name>\u002FSKILL.md`   | 插件启用的位置               |\n\n当多个技能具有相同名称时，优先级较高的位置会生效：**企业级 > 个人级 > 项目级**。插件技能使用 `plugin-name:skill-name` 命名空间，因此不会发生冲突。\n\n**旧版兼容性：** `.claude\u002Fcommands\u002F` 中的文件仍然有效，并支持相同的 frontmatter。如果某个技能和命令同名，则技能优先。\n\n**自动检测嵌套目录：** 当您在子目录中工作时，Claude Code 会从嵌套的 `.claude\u002Fskills\u002F` 目录中发现技能。例如，在 `packages\u002Ffrontend\u002F` 中编辑文件时，也会加载 `packages\u002Ffrontend\u002F.claude\u002Fskills\u002F` 中的技能。这支持多仓库（monorepo）结构，其中每个包都有自己的技能。\n\n**实时更改检测：** 通过 `--add-dir` 添加的目录中的技能会自动加载，并被实时更改检测机制捕获——您可以在会话期间直接编辑这些技能，无需重启。\n\n### 技能目录结构 [官方]\n\n每个技能都是一个包含 `SKILL.md` 作为入口文件的目录：\n\n```\nmy-skill\u002F\n├── SKILL.md           # 主要说明文档（必填）\n├── template.md        # Claude 可填充的模板（可选）\n├── examples\u002F\n│   └── sample.md      # 示例输出（可选）\n└── scripts\u002F\n    └── validate.sh    # Claude 可执行的脚本（可选）\n```\n\n在 `SKILL.md` 中引用辅助文件，以便 Claude 知道每个文件的内容：\n\n```markdown\n## 附加资源\n- 完整的 API 详情，请参阅 [reference.md](reference.md)\n- 使用示例，请参阅 [examples.md](examples.md)\n```\n\n> **提示：** 将 `SKILL.md` 保持在 500 行以内。将详细参考材料移至单独的文件。\n\n### 创建技能 [官方]\n\n**步骤 1：** 创建技能目录：\n```bash\n# 个人技能（在所有项目中可用）\nmkdir -p ~\u002F.claude\u002Fskills\u002Fexplain-code\n\n# 项目技能（通过 git 与团队共享）\nmkdir -p .claude\u002Fskills\u002Fexplain-code\n```\n\n**步骤 2：** 编写带有 frontmatter 和说明的 `SKILL.md`：\n```yaml\n---\nname: explain-code\ndescription: 用可视化图表和类比解释代码。适用于解释代码如何运行、讲解代码库，或当用户询问“这是如何工作的？”时。\n---\n\n解释代码时，务必包括以下内容：\n\n1. **从类比开始**：将代码与日常生活中的事物进行比较\n2. **绘制图表**：使用 ASCII 艺术展示流程、结构或关系\n3. **逐步解释代码**：逐行说明代码的执行过程\n4. **指出常见陷阱**：常见的错误或误解是什么？\n\n保持解释的对话式风格。对于复杂概念，可以使用多种类比。\n```\n\n**步骤 3：** 测试技能：\n```bash\n# 让 Claude 自动调用\n> “这段代码是如何工作的？”\n\n# 或直接调用\n> \u002Fexplain-code src\u002Fauth\u002Flogin.ts\n```\n\n### Frontmatter 参考 [官方]\n\n通过在 `SKILL.md` 文件顶部的 `---` 标记之间的 YAML frontmatter 配置技能行为。所有字段均为可选；仅建议填写 `description`。\n\n| 字段                | 必填 | 描述                                                         |\n|---------------------|------|--------------------------------------------------------------|\n| `name`              | 否   | 显示名称。若省略，则使用目录名称。小写字母、数字和连字符（最多 64 个字符）。 |\n| `description`       | 推荐 | 技能的功能及适用场景。Claude 会根据此描述决定何时加载该技能。 |\n| `argument-hint`     | 否   | 自动补全时显示的提示（如 `[issue-number]` 或 `[filename] [format]`）。 |\n| `disable-model-invocation` | 否   | 设置为 `true` → 只有用户可以通过 `\u002Fname` 调用。默认值：`false`。 |\n| `user-invocable`    | 否   | 设置为 `false` → 不显示在 `\u002F` 菜单中，只有 Claude 可以调用。默认值：`true`。 |\n| `allowed-tools`     | 否   | 在技能激活时，Claude 可以使用的工具，无需征得许可。 |\n| `model`             | 否   | 技能激活时使用的模型。 |\n| `context`           | 否   | 设置为 `fork` 以在分叉的子代理上下文中运行。 |\n| `agent`             | 否   | 当设置 `context: fork` 时，应使用哪种子代理类型。 |\n| `hooks`             | 否   | 作用于该技能生命周期的钩子。请参阅 [Hooks](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks#hooks-in-skills-and-agents)。 |\n\n### 控制技能调用 [官方]\n\n默认情况下，您和 Claude 都可以调用任何技能。有两个 frontmatter 字段可以限制这一行为：\n\n- **`disable-model-invocation: true`** — 只有您可以调用。适用于具有副作用的工作流（如 `\u002Fdeploy`、`\u002Fcommit`）。\n- **`user-invocable: false`** —  only Claude can invoke. Use for background knowledge that isn't actionable as a command.\n\n```yaml\n# 仅供用户调用的技能（Claude 不会自动触发）\n---\nname: deploy\ndescription: 将应用程序部署到生产环境\ndisable-model-invocation: true\n---\n\n# 仅供模型调用的技能（隐藏在 \u002F 菜单之外）\n---\nname: legacy-system-context\ndescription: 关于遗留系统的背景知识\nuser-invocable: false\n---\n```\n\n**调用与上下文加载行为：**\n\n| Frontmatter                          | 您可以调用 | Claude 可以调用 | 何时加载到上下文中          |\n|--------------------------------------|------------|-----------------|-----------------------------|\n| （默认）                             | 是         | 是              | 描述始终在上下文中；完整技能在调用时加载 |\n| `disable-model-invocation: true`     | 是         | 否              | 描述不在上下文中；完整技能在您调用时加载 |\n| `user-invocable: false`              | 否         | 是              | 描述始终在上下文中；完整技能在调用时加载 |\n\n**通过 `\u002Fpermissions` 限制 Claude 的访问权限：**\n\n```bash\n# 仅允许特定技能\nSkill(commit)\nSkill(review-pr *)\n\n# 拒绝特定技能\nSkill(deploy *)\n\n# 禁用所有技能\nSkill    # 添加到拒绝规则中\n```\n\n权限语法：`Skill(name)` 用于精确匹配，`Skill(name *)` 用于前缀匹配，后跟任意参数。\n\n### 传递参数 [官方]\n\n技能通过占位符替换接受参数：\n\n| 变量            | 描述                                         |\n|-----------------|----------------------------------------------|\n| `$ARGUMENTS`    | 调用技能时传递的所有参数                   |\n| `$ARGUMENTS[N]` | 按照 0 开始的索引获取特定参数（如 `$ARGUMENTS[0]`） |\n| `$N`            | `$ARGUMENTS[N]` 的简写形式（如 `$0`、`$1`） |\n| `${CLAUDE_SESSION_ID}` | 当前会话 ID（可用于日志记录）             |\n\n**示例：**\n```yaml\n---\nname: fix-issue\ndescription: 修复 GitHub 问题\ndisable-model-invocation: true\n---\n\n按照我们的编码标准修复 GitHub 问题 $ARGUMENTS。\n\n1. 阅读问题描述\n2. 实施修复\n3. 编写测试\n4. 提交更改\n```\n\n```bash\n\u002Ffix-issue 123\n# Claude 接收到：“按照我们的编码标准修复 GitHub 问题 123……”\n```\n\n**索引参数：**\n```yaml\n---\nname: compare-files\ndescription: 比较两个文件\n---\n\n# 比较：$ARGUMENTS[0] 与 $ARGUMENTS[1]\n\n# 缩写：$0 与 $1\n\n比较 $0 和 $1 的差异。\n```\n\n```bash\n\u002Fcompare-files \"src\u002Fv1\u002Fapi.ts\" \"src\u002Fv2\u002Fapi.ts\"\n# $0 = \"src\u002Fv1\u002Fapi.ts\", $1 = \"src\u002Fv2\u002Fapi.ts\"\n```\n\n如果技能内容中不存在 `$ARGUMENTS`，参数将以 `ARGUMENTS: \u003Cvalue>` 的形式追加。\n\n### 高级模式 [官方]\n\n#### 动态上下文注入\n\n`` !`command` `` 语法会在技能内容发送给 Claude 之前运行 Shell 命令。命令的输出会替换占位符：\n\n```yaml\n---\nname: pr-summary\ndescription: 总结拉取请求中的更改\ncontext: fork\nagent: Explore\nallowed-tools: Bash(gh *)\n---\n\n## 拉取请求上下文\n- PR 差异：!`gh pr diff`\n- PR 评论：!`gh pr view --comments`\n- 更改文件：!`gh pr diff --name-only`\n\n## 你的任务\n总结这个拉取请求……\n```\n\n每个 `` !`command` `` 都会立即执行（在 Claude 看到任何内容之前）。Claude 只能看到包含实际数据的最终结果。\n\n#### 在子代理中运行\n\n添加 `context: fork` 可以让技能独立运行。技能内容会成为驱动子代理的提示（无法访问对话历史）：\n\n```yaml\n---\nname: deep-research\ndescription: 深入研究某个主题\ncontext: fork\nagent: Explore\n---\n\n深入研究 $ARGUMENTS：\n\n1. 使用 Glob 和 Grep 查找相关文件\n2. 阅读并分析代码\n3. 总结发现，并附上具体的文件引用\n```\n\n`agent` 字段指定要使用的子代理。选项包括内置代理（`Explore`、`Plan`、通用型）或来自 `.claude\u002Fagents\u002F` 的自定义子代理。默认为通用型。\n\n> **警告：** `context: fork` 只适用于具有明确指令的技能。如果没有任务指引的技能将不会返回有意义的输出。\n\n#### 扩展思考\n\n要在技能中启用扩展思考功能，在技能内容中的任意位置加入 `ultrathink` 一词：\n\n```yaml\n---\nname: architecture-review\ndescription: 深度架构分析\n---\n\n使用 ultrathink 对架构进行深度分析。\n\n审查整体结构，识别模式，并提出改进建议。\n```\n\n### 实用示例\n\n**示例：代码审查技能**\n\n`.claude\u002Fskills\u002Fcode-reviewer\u002FSKILL.md`:\n```yaml\n---\nname: code-reviewer\ndescription: 审查代码中的安全漏洞、Bug、性能问题以及代码风格问题。当用户要求审查、审计或检查代码质量时使用此技能。\nallowed-tools: [Read, Grep, Glob]\n---\n\n# 代码审查技能\n\n## 激活时机\n当用户要求以下内容时使用此技能：\n- 审查代码中的问题\n- 进行安全审计或查找漏洞\n- 检查代码质量或最佳实践\n\n## 审查流程\n\n### 1. 范围检测\n- 使用 Glob 确定需要审查的文件\n- 优先考虑最近修改的文件\n- 如果提到特定区域，则重点关注该区域\n\n### 2. 分层分析\n- **安全**：SQL 注入、XSS、认证问题、敏感信息泄露\n- **Bug**：逻辑错误、空值检查、错误处理\n- **性能**：N+1 查询、不必要的循环、内存泄漏\n- **风格**：命名规范、代码组织、可读性\n\n### 3. 报告\n提供按严重程度分类的结构化反馈：\n- **严重\u002F高危**：安全问题\n- **中等**：性能问题\n- **低危**：代码风格和最佳实践\n\n每个问题都应包含文件路径、描述及修复建议。\n```\n\n**示例：测试生成技能**\n\n`.claude\u002Fskills\u002Ftest-generator\u002FSKILL.md`:\n```yaml\n---\nname: test-generator\ndescription: 生成全面的单元测试和集成测试。当用户要求编写测试、增加测试覆盖率或创建测试用例时使用此技能。\nallowed-tools: [Read, Write, Grep, Glob, Bash]\n---\n\n# 测试生成技能\n\n## 激活时机\n当用户提出以下请求时使用此技能：\n- “为……编写测试”\n- “增加测试覆盖率”\n- “生成测试用例”\n\n## 测试生成流程\n\n### 1. 分析目标代码\n- 阅读待测试的文件或函数\n- 确定输入、输出及副作用\n- 检查现有的测试模式\n\n### 2. 生成全面测试\n覆盖所有场景：\n- 正常流程（预期使用情况）\n- 错误情况（无效输入）\n- 边界情况（空值、null、边界值）\n- 副作用（数据库操作、API 调用）\n\n### 3. 遵循项目规范\n- 查看 CLAUDE.md 中的测试约定\n- 匹配现有测试文件结构\n- 使用项目的测试框架\n```\n\n**示例：安全审查技能**\n\n`.claude\u002Fskills\u002Fsecurity-review\u002FSKILL.md`:\n```yaml\n---\nname: security-review\ndescription: 对代码库进行全面的安全审计。当被要求审查安全性、审计漏洞或检查是否存在利用风险时使用此技能。\nallowed-tools: [Read, Grep, Glob]\ndisable-model-invocation: true\n---\n\n# 安全审查：$ARGUMENTS\n\n针对：$ARGUMENTS 进行彻底的安全审计\n\n## 审查清单\n\n### 1. 认证与授权\n- 检查弱密码策略\n- 验证 JWT 令牌验证机制\n- 审查会话管理\n- 检查访问控制是否失效\n\n### 2. 输入验证\n- SQL 注入漏洞\n- XSS（跨站脚本攻击）风险\n- 命令注入的可能性\n- 路径遍历漏洞\n\n### 3. 数据保护\n- 敏感数据暴露\n- 静态及传输中的加密\n- 代码中是否存在 API 密钥和机密信息\n- 数据库凭证的安全性\n\n### 4. 依赖项\n- 包中已知的漏洞\n- 过时的依赖包\n- 许可证合规问题\n\n### 5. 配置\n- 安全头设置（CSP、HSTS 等）\n- CORS 配置\n- 是否有错误信息泄露\n- 生产环境中是否开启了调试模式\n\n**输出格式** - 提供详细的报告，分为以下几个部分：\n- 严重问题（需立即修复）\n- 高优先级\n- 中优先级\n- 低优先级 \u002F 建议\n- 安全优势\n- 行动计划（按优先级排列的修复清单）\n```\n\n**使用方法：**\n```bash\n\u002Fsecurity-review \"authentication and API endpoints\"\n```\n\n**示例：API 文档生成技能**\n\n`.claude\u002Fskills\u002Fapi-docs\u002FSKILL.md`:\n```yaml\n---\nname: api-docs\ndescription: 根据代码生成全面的 API 文档。当被要求记录 API、创建 API 文档或生成 OpenAPI 规范时使用此技能。\nallowed-tools: [Read, Write, Grep, Glob]\ndisable-model-invocation: true\n---\n\n# 生成 API 文档\n\n分析代码库，为：$ARGUMENTS 生成全面的 API 文档\n\n## 流程\n\n### 1. 发现\n- 找到所有 API 路由\u002F端点\n- 确定请求\u002F响应类型\n- 记录认证要求\n- 文档化查询参数\n\n### 2. 文档化\n对于每个端点，记录：\n- 方法和路径\n- 描述\n- 认证要求\n- 请求体\u002F参数\n- 响应码和响应内容\n- 示例请求\n\n### 3. 输出\n- 创建 `\u002Fdocs\u002FAPI.md` 包含完整文档\n- 如适用，创建 `\u002Fopenapi.yaml` 包含 OpenAPI 规范\n```\n\n**使用方法：**\n```bash\n\u002Fapi-docs \"all endpoints\"\n\u002Fapi-docs \"authentication routes\"\n```\n\n### 文件引用与 @ 语法 [官方]\n\n使用 `@` 前缀快速引用文件：\n\n```bash\n# 引用单个文件\n\u002Freview-code @src\u002Fauth.ts\n\n# 引用多个文件\n\u002Freview-code @src\u002Fauth.ts @src\u002Fapi.ts @tests\u002Fauth.test.ts\n\n# 也可用于普通提示\n> “审查 @src\u002Fservices\u002Fpayment.ts 中的安全问题”\n\n# 引用包含技能参数的文件\n\u002Fanalyze-file @src\u002Fcomponents\u002FUserProfile.tsx\n```\n\n**@ 引用的工作原理：**\n- `@filename` 会自动展开以包含文件内容\n- 支持绝对路径和相对路径\n- 可以在一个命令中引用多个文件\n- 文件会被自动读取并纳入上下文中\n- 减少了显式指定“先读取文件X”的需求\n\n**使用场景：**\n```bash\n# 带上下文的代码审查\n> \"比较 @src\u002Fapi\u002Fv1.ts 和 @src\u002Fapi\u002Fv2.ts，并列出差异\"\n\n# 跨文件重构\n> \"使 @src\u002Fmodels\u002FUser.ts 与 @src\u002Ftypes\u002Fuser.d.ts 保持一致\"\n\n# Bug调查\n> \"此错误发生在 @src\u002Fservices\u002Fauth.ts 中，请查看 @logs\u002Ferror.log 寻找线索\"\n\n# 测试生成\n> \"为 @src\u002Futils\u002Fvalidator.ts 生成测试\"\n```\n\n**最佳实践：**\n- 当你知道确切的文件路径时使用 @ 引用\n- 结合技能以实现可重用的工作流\n- 非常适合对特定文件进行聚焦分析\n- 相比读取整个目录，能减少令牌使用量\n\n### MCP集成 [官方]\n\nMCP服务器可以暴露提示，这些提示会自动成为可调用的技能：\n\n```json\n{\n  \"prompts\": [\n    {\n      \"name\": \"search-docs\",\n      \"description\": \"搜索内部文档\",\n      \"arguments\": [{\"name\": \"query\", \"description\": \"搜索查询\"}]\n    }\n  ]\n}\n```\n\n这将在Claude Code中作为 `\u002Fsearch-docs` 可用。\n\n```bash\n# 添加MCP服务器\nclaude mcp add github -- gh-mcp\n\n# MCP提示会变成技能：\n\u002Fgithub-pr-review      # 审查当前PR\n\u002Fgithub-issues         # 列出未解决问题\n\u002Fgithub-create-pr      # 从当前分支创建PR\n```\n\n### 技能最佳实践 [官方]\n\n#### 1. 编写清晰、具体的描述\n\n`description`字段至关重要——它帮助Claude决定何时激活技能：\n\n**好的：**\n```yaml\ndescription: \"根据代码注释生成API文档。当用户请求记录API、创建API文档、更新端点文档或生成OpenAPI规范时使用。\"\n```\n\n**坏的：**\n```yaml\ndescription: \"文档生成器\"  # 太模糊\n```\n\n#### 2. 使用自然触发词\n\n包含用户自然会说的术语：\n\n```yaml\n# 用于安全审查技能\ndescription: \"审查代码安全性。当被要求：审查安全、审计代码、查找漏洞、检查是否存在利用、分析风险时使用。\"\n\n# 用于性能优化技能\ndescription: \"优化代码性能。当被要求：提升性能、优化速度、减少内存使用、加快速度、对代码进行性能分析时使用。\"\n```\n\n#### 3. 适当限制工具\n\n```yaml\n# 仅限分析（不能修改代码）\nallowed-tools: [Read, Grep, Glob]\n\n# 可以创建\u002F修改代码\nallowed-tools: [Read, Write, Edit, Bash]\n\n# 研究与实施\nallowed-tools: [Read, Write, Edit, WebFetch, WebSearch]\n```\n\n#### 4. 保持技能专注\n\n**好的（专注）：**\n- `sql-optimizer` — 仅优化SQL查询\n- `api-docs-generator` — 生成API文档\n- `security-scanner` — 查找安全问题\n\n**坏的（过于宽泛）：**\n- `database-everything` — 太模糊\n- `code-helper` — 帮助什么？\n\n#### 5. 提供清晰的说明\n\n按照以下结构编写SKILL.md：\n1. **何时激活** — 清晰的触发条件\n2. **流程** — 分步骤的操作指南\n3. **输出格式** — 如何呈现结果\n4. **示例** — 展示预期行为\n\n#### 6. 注意上下文预算\n\n技能描述会被加载到上下文中，以便Claude知道有哪些可用技能。如果有太多技能，可能会超出字符预算（上下文窗口的2%，默认为16,000字符）。运行 `\u002Fcontext` 来检查是否有被排除技能的警告。\n\n可以通过设置环境变量 `SLASH_COMMAND_TOOL_CHAR_BUDGET` 来覆盖此限制。\n\n### 技能故障排除 [官方]\n\n**技能未触发：**\n1. 检查描述是否包含用户自然会说的关键词\n2. 确认在输入“有哪些可用技能？”时技能是否出现\n3. 尝试改写请求以匹配描述\n4. 直接使用 `\u002F技能名` 调用，确认其是否正常工作\n\n**技能触发过于频繁：**\n1. 使描述更加具体\n2. 添加 `disable-model-invocation: true` 以实现仅手动调用\n\n**Claude看不到所有技能：**\n- 如果技能描述过多，可能会超出字符预算\n- 运行 `\u002Fcontext` 检查是否有被排除技能的警告\n- 设置 `SLASH_COMMAND_TOOL_CHAR_BUDGET` 为更高的值\n\n### 迁移：命令到技能\n\n自定义斜杠命令（`.claude\u002Fcommands\u002F`文件）已被合并到技能系统中。**您现有的命令文件仍可继续使用且无需更改。** 对于新工作，建议使用技能，因为它们支持：\n- **支持文件** — 可将模板、脚本和参考文档与您的技能打包在一起\n- **调用控制** — 可选择由您、Claude或两者共同调用\n- **子代理执行** — 在隔离的分叉上下文中运行技能\n- **嵌套发现** — 自动从子目录加载（支持monorepo）\n\n**迁移路径：**\n```bash\n# 旧结构（仍然有效）\n.claude\u002Fcommands\u002Freview.md\n\n# 新结构（推荐）\n.claude\u002Fskills\u002Freview\u002FSKILL.md\n```\n\n两者都会创建 `\u002Freview` 并以相同的方式工作。如果两者同时存在，则技能优先。\n\n**来源：** [Agent Skills](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fskills)\n\n---\n\n## 内置命令\n\n**内置命令是用于管理Claude Code会话的原生CLI命令。** 它们被硬编码到Claude Code中，而不是技能——您无法自定义或覆盖它们。\n\n> **注意：** 对于自定义工作流命令，请使用[技能](#skills-system)代替。像 `\u002Fhelp` 和 `\u002Fcompact` 这样的内置命令无法通过技能工具使用。\n\n### 命令参考 [官方]\n\n```bash\n# 会话管理\n\u002Fhelp              # 显示所有可用命令\n\u002Fexit              # 结束当前会话\n\u002Fclear             # 清除对话历史\n\u002Fcompact [instr]   # 整理上下文（可选指定关注的内容）\n\u002Frewind            # 撤销对话中的代码更改\n\n# 会话与历史\n\u002Frename \u003Cname>     # 为当前会话命名\n\u002Fresume [name|id]  # 根据名称或ID恢复之前的会话\n\u002Fexport            # 将对话导出为文件\n\u002Fcopy              # 将最后一条回复复制到剪贴板 [新功能]\n\n# 使用情况与统计\n\u002Fusage             # 查看套餐限额及使用情况 [新功能]\n\u002Fstats             # 使用统计与参与度指标（支持7天\u002F30天\u002F全部时间） [新功能]\n\u002Fextra-usage       # 为Max套餐订阅者启用额外使用额度 [新功能]\n\u002Ffast              # 切换快速模式（使用更快的模型，需先启用\u002Fextra-usage） [新功能]\n\n# 后台进程管理\n\u002Fbashes            # 列出所有后台进程\n\u002Ftasks             # 列出所有后台任务（代理、Shell等）\n\u002Fkill \u003Cid>         # 停止某个后台进程\n\n# 发现与调试\n\u002Fbug               # 报告错误（将对话发送至 Anthropic）\n\u002Fcommands          # 列出所有技能和命令\n\u002Fdebug             # 诊断会话问题 [新功能 v2.1.30]\n\u002Fhooks             # 显示已配置的钩子\n\u002Fskills            # 列出可用的技能\n\u002Fplugin            # 插件管理界面\n\u002Fcontext           # 以彩色网格形式查看当前上下文使用情况\n\u002Fcost              # 显示 token 使用统计信息\n\u002Fdoctor            # 运行诊断程序（显示带有自动更新频道的更新部分）\n\n# 配置\n\u002Fconfig            # 常规设置（可键入搜索和筛选）\n\u002Fpermissions       # 管理工具权限（支持搜索）\n\u002Fprivacy-settings  # 查看并更新隐私设置\n\u002Fstatus            # 显示会话状态（状态选项卡）\n\u002Fstatusline        # 配置状态栏显示\n\u002Fmodel             # 切换模型\n\u002Foutput-style      # 直接或通过选择菜单设置输出样式\n\u002Ftheme             # 主题选择器（Ctrl+T 切换语法高亮）\n\u002Fterminal-setup    # 配置终端（Kitty、Alacritty、Zed、Warp）\n\u002Fvim               # 进入 vim 模式，可在插入模式和命令模式之间切换\n\u002Fsandbox           # 启用沙盒化的 bash，具备文件系统和网络隔离\n\n# 工作区管理\n\u002Fadd-dir \u003Cpath>    # 向工作区添加额外目录\n\u002Fagents            # 管理自定义 AI 子代理\n\u002Finit              # 使用 CLAUDE.md 指南初始化项目\n\u002Fmemory            # 编辑 CLAUDE.md 内存文件\n\u002Finstall-github-app # 为仓库设置 Claude GitHub Actions\n\u002Fpr-comments       # 查看拉取请求评论\n\u002Freview            # 请求代码审查\n\u002Fsecurity-review   # 完成待处理更改的安全审查\n\u002Ftodos             # 列出当前待办事项\n\n# MCP 服务器管理\n\u002Fmcp               # MCP 服务器管理和 OAuth 认证\n\u002Fmcp enable \u003Csrv>  # 启用一个 MCP 服务器\n\u002Fmcp disable \u003Csrv> # 禁用一个 MCP 服务器\n\n# 远程会话（claude.ai 订阅用户）\n\u002Fteleport          # 通过会话 ID 从 claude.ai 恢复远程会话\n\u002Fremote-env        # 配置远程会话环境\n\n# 账户与更新\n\u002Flogin             # 切换 Anthropic 账户\n\u002Flogout            # 退出 Anthropic 账户\n\u002Frelease-notes     # 查看发布说明\n\n# 计划模式\n\u002Fplan              # 进入计划模式，进行结构化规划\n```\n\n**来源:** [CLI 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference)、[交互模式](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Finteractive-mode#built-in-commands)\n\n---\n\n## 钩子系统\n\n**钩子是自动化脚本，在 Claude Code 工作流中的特定点执行。**\n\n### 什么是钩子？[官方]\n\n钩子允许你 **拦截并控制** Claude 的行为：\n\n```bash\n# 钩子可以实现的功能示例：\n- 阻止编辑敏感文件（如 .env）\n- 在会话开始时注入上下文\n- 在文件编辑前运行代码检查\n- 验证 Git 提交\n- 审计所有执行的命令\n- 添加自定义安全检查\n```\n\n**两种类型：**\n1. **Bash 命令钩子** (`type: \"command\"`) - 执行 Shell 脚本\n2. **基于提示的钩子** (`type: \"prompt\"`) - 使用 LLM 进行上下文感知决策\n\n### 钩子配置 [官方]\n\n钩子在 `.claude\u002Fsettings.json` 或 `~\u002F.claude\u002Fsettings.json` 中配置：\n\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"ToolPattern\",\n        \"hooks\": [\n          {\"type\": \"command\", \"command\": \"script\"}\n        ]\n      }\n    ]\n  }\n}\n```\n\n### 钩子事件 [官方]\n\n| 事件 | 触发时机 | 是否可阻止 |\n|-------|---------------|-----------|\n| **Setup** | 通过 `--init`、`--init-only` 或 `--maintenance` 标志 | 否 |\n| **SessionStart** | 会话开始或恢复 | 否 |\n| **SessionEnd** | 会话结束 | 否 |\n| **UserPromptSubmit** | 用户提交提示 | 是 |\n| **PreToolUse** | 工具执行前 | 是 |\n| **PostToolUse** | 工具成功后 | 否 |\n| **PostToolUseFailure** | 工具失败后 | 否 |\n| **PermissionRequest** | 权限对话框出现时 | 是 |\n| **SubagentStart** | 派生子代理时 | 否 |\n| **SubagentStop** | 子代理结束时 | 是 |\n| **Stop** | Claude 完成响应时 | 是 |\n| **Notification** | Claude 发送通知时 | 否 |\n| **PreCompact** | 上下文压缩前 | 否 |\n| **TeammateIdle** | 代理团队成员即将空闲时 [新] | 是 |\n| **TaskCompleted** | 任务即将标记为完成时 [新] | 是 |\n\n### 示例：保护敏感文件 [官方]\n\n`.claude\u002Fsettings.json`:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'FILE=$(echo \\\"$HOOK_INPUT\\\" | jq -r \\\".tool_input.file_path \u002F\u002F empty\\\"); if [[ \\\"$FILE\\\" == *\\\".env\\\"* ]] || [[ \\\"$FILE\\\" == \\\".git\u002F\\\"* ]]; then echo \\\"Cannot modify sensitive files\\\" >&2; exit 2; fi'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**工作原理：**\n- 在任何 Edit 或 Write 工具执行前运行\n- 检查文件路径是否包含 \".env\" 或 \".git\u002F\"\n- 以退出码 2 阻止操作\n- Claude 收到错误消息，不会编辑该文件\n\n### 示例：会话上下文注入 [官方]\n\n```json\n{\n  \"hooks\": {\n    \"SessionStart\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"cat .claude\u002Fsession-context.txt\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**创建内容：** `.claude\u002Fsession-context.txt`\n```\n今日重点：进行身份验证重构\n近期背景：已从会话迁移到 JWT\n当前分支：feature\u002Fjwt-auth\n重要提醒：请勿修改 \u002Fold-auth 中的旧版认证代码\n```\n\n此上下文会在每次会话开始时被注入。\n\n### 示例：智能决策钩子 [官方]\n\n```json\n{\n  \"hooks\": {\n    \"Stop\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"prompt\",\n            \"prompt\": \"评估当前任务是否已完成。参数：$ARGUMENTS。检查所有子任务是否完成、测试是否通过以及文档是否更新。请回复 {\\\"decision\\\": \\\"stop\\\" 或 \\\"continue\\\", \\\"reason\\\": \\\"解释\\\"}\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n使用 LLM（Haiku）智能判断 Claude 是否应停止工作。\n\n### 钩子输入\u002F输出 [官方]\n\n**输入（通过 stdin 以 JSON 格式传递）：**\n```json\n{\n  \"sessionId\": \"abc123\",\n  \"tool_name\": \"Edit\",\n  \"tool_input\": {\n    \"file_path\": \"\u002Fsrc\u002Fapp.ts\",\n    \"old_string\": \"...\",\n    \"new_string\": \"...\"\n  },\n  \"project_dir\": \"\u002Fhome\u002Fuser\u002Fproject\"\n}\n```\n\n**输出（退出码）：**\n- `0` - 成功，继续\n- `2` - 阻止操作\n- 其他 - 非阻断性错误（记录日志）\n\n**JSON 输出（可选）：**\n```json\n{\n  \"decision\": \"stop\",\n  \"reason\": \"所有任务已完成\",\n  \"continue\": false\n}\n```\n\n### 安全最佳实践 [官方]\n\n⚠️ **重要提示：** “使用钩子时，您需对所配置的命令承担全部责任，这些命令可能会修改或删除您用户有权访问的文件。”\n\n**最佳实践：**\n```bash\n# 1. 始终对变量加引号\nFILE=\"$HOOK_INPUT\"  # 正确\nFILE=$HOOK_INPUT    # 错误 - 包含空格时可能出错\n\n# 2. 验证路径\nif [[ \"$FILE\" == ..\u002F* ]]; then\n  echo \"路径遍历尝试\" >&2\n  exit 2\nfi\n\n# 3. 使用绝对路径\ncd \"$CLAUDE_PROJECT_DIR\" || exit 1\n\n# 4. 对输入进行清理\njq -r '.tool_input.file_path' \u003C\u003C\u003C \"$HOOK_INPUT\"  # 好\neval \"$SOME_VAR\"  # 不好 - 存在代码注入风险\n\n# 5. 阻止敏感操作\ncase \"$FILE\" in\n  *.env|.git\u002F*|.ssh\u002F*)\n    echo \"已阻止：敏感文件\" >&2\n    exit 2\n    ;;\nesac\n```\n\n### 调试钩子 [官方]\n\n```bash\n# 以调试模式运行 Claude\nclaude --debug\n\n# 检查钩子配置\n> \u002Fhooks\n\n# 手动测试钩子命令\necho '{\"tool_name\":\"Edit\",\"tool_input\":{\"file_path\":\".env\"}}' | bash your-hook-script.sh\n\n# 查看日志\ntail -f ~\u002F.claude\u002Flogs\u002Fclaude.log\n```\n\n### 钩子配方库 [官方 + 社区]\n\n**全面的生产就绪型钩子模式集合，满足常见的自动化需求。**\n\n#### 1. 保存时自动格式化代码 [社区]\n\n使用适合语言的格式化工具，在 Claude 编辑文件后自动格式化代码。\n\n**配置（`.claude\u002Fsettings.json`）：**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|MultiEdit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fformat-code.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**脚本（`~\u002F.claude\u002Fhooks\u002Fformat-code.sh`）：**\n```bash\n#!\u002Fbin\u002Fbash\n# 从 JSON 输入中提取文件路径\nFILE=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.file_path \u002F\u002F empty')\n\n[[ -z \"$FILE\" ]] && exit 0\n\n# 根据文件扩展名进行格式化\ncase \"$FILE\" in\n  *.ts|*.tsx|*.js|*.jsx)\n    # 先尝试 Biome，若失败则使用 Prettier\n    if command -v biome &> \u002Fdev\u002Fnull; then\n      biome format --write \"$FILE\" &> \u002Fdev\u002Fnull || true\n    elif command -v prettier &> \u002Fdev\u002Fnull; then\n      prettier --write \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    ;;\n  *.py)\n    # Python：Ruff\n    if command -v ruff &> \u002Fdev\u002Fnull; then\n      ruff format \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    ;;\n  *.go)\n    # Go：goimports + gofmt\n    if command -v goimports &> \u002Fdev\u002Fnull; then\n      goimports -w \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    go fmt \"$FILE\" &> \u002Fdev\u002Fnull || true\n    ;;\n  *.md)\n    # Markdown：Prettier\n    if command -v prettier &> \u002Fdev\u002Fnull; then\n      prettier --write \"$FILE\" &> \u002Fdev\u002Fnull || true\n    fi\n    ;;\nesac\n```\n\n**赋予可执行权限：** `chmod +x ~\u002F.claude\u002Fhooks\u002Fformat-code.sh`\n\n---\n\n#### 2. 编辑时自动修复 ESLint [社区]\n\n自动对 JavaScript\u002FTypeScript 文件运行带有 `--fix` 选项的 ESLint。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|MultiEdit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'FILE=$(echo \\\"$HOOK_INPUT\\\" | jq -r \\\".tool_input.file_path \u002F\u002F empty\\\"); if [[ \\\"$FILE\\\" =~ \\\\.(ts|tsx|js|jsx)$ ]] && command -v eslint &>\u002Fdev\u002Fnull; then eslint --fix \\\"$FILE\\\" &>\u002Fdev\u002Fnull || true; fi'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n---\n\n#### 3. 阻止读取 .gitignore 匹配的文件 [社区]\n\n防止 Claude 读取与 `.claudeignore` 模式匹配的文件。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Read\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"claude-ignore\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**安装：** `npm install -g claude-ignore && claude-ignore init`\n\n---\n\n#### 4. 提交前运行测试 [社区]\n\n在允许 Git 提交之前，验证测试是否通过。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fpre-commit-test.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**脚本（`~\u002F.claude\u002Fhooks\u002Fpre-commit-test.sh`）：**\n```bash\n#!\u002Fbin\u002Fbash\nCOMMAND=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.command \u002F\u002F empty')\n\n# 只拦截 git commit 命令\nif [[ \"$COMMAND\" == git*commit* ]]; then\n  echo \"正在提交前运行测试...\" >&2\n\n  # 运行测试\n  if npm test &>\u002Fdev\u002Fnull; then\n    echo \"✅ 测试通过\" >&2\n    exit 0\n  else\n    echo \"❌ 测试失败 - 阻止提交\" >&2\n    exit 2\n  fi\nfi\n\nexit 0\n```\n\n---\n\n#### 5. 审计日志钩子 [社区]\n\n记录所有工具使用情况，用于安全审计。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'echo \\\"$(date -Iseconds) $TOOL_NAME: $(echo \\\\\\\"$HOOK_INPUT\\\\\\\" | jq -c .)\\\" >> ~\u002F.claude\u002Faudit.log'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n---\n\n#### 6. Token 使用量跟踪器 [社区]\n\n监控并记录每个会话的 Token 使用情况。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"SessionEnd\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Flog-session.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**脚本：**\n```bash\n#!\u002Fbin\u002Fbash\nSESSION_ID=$(echo \"$HOOK_INPUT\" | jq -r '.session_id \u002F\u002F \"unknown\"')\nTRANSCRIPT=$(echo \"$HOOK_INPUT\" | jq -r '.transcript_path \u002F\u002F empty')\n\nif [[ -f \"$TRANSCRIPT\" ]]; then\n  TOKENS=$(jq '[.[] | select(.role==\"assistant\") | .usage.total_tokens] | add' \"$TRANSCRIPT\" 2>\u002Fdev\u002Fnull || echo 0)\n  echo \"$(date -Iseconds) 会话 $SESSION_ID: $TOKENS tokens\" >> ~\u002F.claude\u002Ftoken-usage.log\nfi\n```\n\n---\n\n#### 7. 提交信息验证 [社区]\n\n强制遵守规范化的提交信息格式。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fvalidate-commit.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**脚本：**\n```bash\n#!\u002Fbin\u002Fbash\nCOMMAND=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.command \u002F\u002F empty')\n\nif [[ \"$COMMAND\" == git*commit*-m* ]]; then\n  MSG=$(echo \"$COMMAND\" | sed -n 's\u002F.*-m[[:space:]]*[\"'\"'\"']\\([^\"'\"'\"']*\\)[\"'\"'\"'].*\u002F\\1\u002Fp')\n\n  # 检查规范化的提交格式：type(scope): message\n  if [[ ! \"$MSG\" =~ ^(feat|fix|docs|style|refactor|test|chore)(\\(.+\\))?: ]]; then\n    echo \"❌ 提交信息必须遵循格式：type(scope): message\" >&2\n    echo \"有效类型：feat, fix, docs, style, refactor, test, chore\" >&2\n    exit 2\n  fi\nfi\n\nexit 0\n```\n\n---\n\n#### 8. 安全密钥扫描器 [社区]\n\n防止提交包含潜在密钥的文件。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fdetect-secrets.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**脚本：**\n```bash\n#!\u002Fbin\u002Fbash\nFILE=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.file_path \u002F\u002F empty')\nNEW_CONTENT=$(echo \"$HOOK_INPUT\" | jq -r '.tool_input.new_string \u002F\u002F .tool_input.content \u002F\u002F empty')\n\n# 检查常见的密钥模式\nif echo \"$NEW_CONTENT\" | grep -iE '(api[_-]?key|password|secret|token|auth)[\"\\s:=]+\\S{16,}' &>\u002Fdev\u002Fnull; then\n  echo \"⚠️  在 $FILE 中检测到潜在的敏感信息\" >&2\n  echo \"请审查并改用环境变量\" >&2\n  exit 2\nfi\n\nexit 0\n```\n\n---\n\n#### 9. 自动更新文档 [社区]\n\n当代码发生变更时，自动更新 README 文件。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"matcher\": \"Edit|MultiEdit|Write\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'echo \\\"📝 考虑为最近的更改更新文档\\\" >&2'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n---\n\n#### 10. 性能 profiling [社区]\n\n跟踪工具操作的执行时间。\n\n**配置：**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'echo \\\"$HOOK_INPUT\\\" > \u002Ftmp\u002Fclaude-pre-$$.json; date +%s%N > \u002Ftmp\u002Fclaude-time-$$.txt'\"\n          }\n        ]\n      }\n    ],\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash ~\u002F.claude\u002Fhooks\u002Fprofile-tool.sh\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**脚本：**\n```bash\n#!\u002Fbin\u002Fbash\nSTART=$(cat \u002Ftmp\u002Fclaude-time-$$.txt 2>\u002Fdev\u002Fnull || echo 0)\nEND=$(date +%s%N)\nDURATION=$(( (END - START) \u002F 1000000 ))  # 毫秒\nTOOL=$(echo \"$HOOK_INPUT\" | jq -r '.tool_name \u002F\u002F \"unknown\"')\n\necho \"$(date -Iseconds) $TOOL: ${DURATION}ms\" >> ~\u002F.claude\u002Fperformance.log\n\nrm -f \u002Ftmp\u002Fclaude-pre-$$.json \u002Ftmp\u002Fclaude-time-$$.txt\n```\n\n---\n\n**来源：** [Hooks 参考](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks), [Hooks 指南](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks-guide), 社区 GitHub 仓库\n\n---\n\n## MCP 集成\n\n**模型上下文协议（MCP）将 Claude Code 连接到外部数据源和工具。**\n\n### 什么是 MCP？[官方]\n\nMCP 允许 Claude Code：\n- 访问外部数据（Google Drive、Slack、Jira、Notion 等）\n- 使用专用工具（数据库、API、服务）\n- 与企业系统集成\n- 扩展本地文件系统之外的功能\n\n**常见用例：**\n- 读取\u002F写入 Google Drive 文档\n- 搜索 Slack 对话\n- 直接查询数据库\n- 从内部 API 获取数据\n- 访问设计文件（Figma）\n- 管理项目任务（Jira、Linear）\n\n### MCP 服务器安装 [官方]\n\n可以通过 CLI 或配置文件添加 MCP 服务器：\n\n**CLI 安装（推荐）：**\n```bash\n# 远程 HTTP 服务器（推荐用于托管服务）\nclaude mcp add --transport http notion https:\u002F\u002Fmcp.notion.com\u002Fmcp\nclaude mcp add --transport http github https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\n\n# 带身份验证头\nclaude mcp add --transport http secure-api https:\u002F\u002Fapi.example.com\u002Fmcp \\\n  --header \"Authorization: Bearer your-token\"\n\n# 本地 Stdio 服务器（用于本地包）\nclaude mcp add --transport stdio airtable -- npx -y airtable-mcp-server\nclaude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol\u002Fserver-postgres \"$DATABASE_URL\"\n\n# 带环境变量\nclaude mcp add --transport stdio --env AIRTABLE_API_KEY=your_key airtable -- npx -y airtable-mcp-server\n\n# Windows（需要 cmd \u002Fc 包装）\nclaude mcp add --transport stdio myserver -- cmd \u002Fc npx -y @some\u002Fpackage\n```\n\n**MCP 服务器管理：**\n```bash\nclaude mcp list              # 列出所有已配置的服务器\nclaude mcp get github        # 获取特定服务器的详细信息\nclaude mcp remove github     # 移除一个服务器\n\u002Fmcp                         # 在 Claude Code 中进行交互式管理\n```\n\n**安装范围：**\n```bash\n# 本地范围（默认）——存储在 ~\u002F.claude.json 的项目路径下\nclaude mcp add --transport http stripe https:\u002F\u002Fmcp.stripe.com\n\n# 项目范围——存储在 .mcp.json 中（可通过 git 共享）\nclaude mcp add --scope project --transport http paypal https:\u002F\u002Fmcp.paypal.com\u002Fmcp\n\n# 用户范围——存储在 ~\u002F.claude.json 中（可在所有项目中使用）\nclaude mcp add --scope user --transport http hubspot https:\u002F\u002Fmcp.hubspot.com\n```\n\n**配置文件（`.mcp.json`）：**\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"type\": \"http\",\n      \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\"\n    },\n    \"postgres\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-postgres\", \"${DATABASE_URL}\"],\n      \"env\": {\n        \"DB_URL\": \"${DB_URL}\",\n        \"API_KEY\": \"${API_KEY:-default-value}\"\n      }\n    },\n    \"slack\": {\n      \"type\": \"stdio\",\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-slack\"],\n      \"env\": {\n        \"SLACK_BOT_TOKEN\": \"${SLACK_BOT_TOKEN}\",\n        \"SLACK_TEAM_ID\": \"${SLACK_TEAM_ID}\"\n      }\n    }\n  }\n}\n```\n\n### OAuth 身份验证 [官方]\n\n许多 MCP 服务器支持 OAuth 进行安全身份验证：\n\n```bash\n# 添加需要 OAuth 的服务器\nclaude mcp add --transport http sentry https:\u002F\u002Fmcp.sentry.dev\u002Fmcp\n\n# 在 Claude Code 中通过浏览器进行身份验证\n\u002Fmcp\n# 按照浏览器步骤完成 OAuth 登录\n```\n\n**手动 OAuth 配置：**\n```json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"type\": \"http\",\n      \"url\": \"https:\u002F\u002Fapi.githubcopilot.com\u002Fmcp\u002F\",\n      \"oauth\": {\n        \"provider\": \"github\",\n        \"scopes\": [\"repo\", \"read:user\"]\n      }\n    }\n  }\n}\n```\n\nClaude Code 会在首次使用时打开浏览器以完成 OAuth 流程。\n\n### 使用 MCP 工具 [官方]\n\n一旦配置完毕，MCP 工具会以 `mcp__\u003Cserver>__\u003Ctool>` 的模式出现：\n\n```bash\n# 示例：Google Drive 搜索\n> “在我们的 Google Drive 中搜索 Q4 计划文档”\n\n# Claude 使用：mcp__google-drive__search_files\n\n# 示例：数据库查询\n> “显示上周创建的所有用户”\n\n# Claude 使用：mcp__postgres__query 并执行 SQL 查询\n\n# 示例：Slack 搜索\n> “查找关于 API 重新设计的对话”\n\n# Claude 使用：mcp__slack__search_messages\n```\n\n### Hooks 中的 MCP [官方]\n\n可以在 hooks 中引用 MCP 工具：\n\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"mcp__postgres__query\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo '数据库查询需要审核' && read -p '批准吗？(y\u002Fn) ' -n 1 -r && [[ $REPLY =~ ^[Yy]$ ]]\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### 流行的 MCP 服务器 [社区]\n\n```bash\n# 官方服务器\n@modelcontextprotocol\u002Fserver-google-drive      # Google Drive 访问\n@modelcontextprotocol\u002Fserver-slack             # Slack 集成\n@modelcontextprotocol\u002Fserver-github            # GitHub API\n@modelcontextprotocol\u002Fserver-postgres          # PostgreSQL 数据库\n@modelcontextprotocol\u002Fserver-sqlite            # SQLite 数据库\n@modelcontextprotocol\u002Fserver-filesystem        # 扩展文件访问\n\n# 社区服务器\n# 可以在 GitHub 上查看社区构建的 MCP 服务器\n```\n\n### MCP 配置管理 [官方]\n\n```bash\n# 自动启用所有项目中的 MCP 服务器\n{\n  \"enableAllProjectMcpServers\": true\n}\n\n# 将特定服务器加入白名单\n{\n  \"enabledMcpjsonServers\": [\"google-drive\", \"postgres\"]\n}\n\n# 将服务器加入黑名单\n{\n  \"disabledMcpjsonServers\": [\"risky-server\"]\n}\n\n# 企业版：仅限受管服务器\n{\n  \"useEnterpriseMcpConfigOnly\": true,\n  \"allowedMcpServers\": [\"approved-server-1\", \"approved-server-2\"]\n}\n```\n\n### MCP 工具搜索 [新功能]\n\n当 MCP 工具定义超出上下文窗口的阈值时，它们会通过 MCPSearch 工具自动延迟执行：\n\n```bash\n# 配置工具搜索阈值（占上下文窗口的百分比）\nENABLE_TOOL_SEARCH=auto:5 claude    # 在达到 5% 时激活\nENABLE_TOOL_SEARCH=auto:10 claude   # 在达到 10% 时激活（默认）\nENABLE_TOOL_SEARCH=true claude      # 始终启用\nENABLE_TOOL_SEARCH=false claude     # 始终禁用\n\n# 或者在 settings.json 中配置\n{\n  \"permissions\": {\n    \"deny\": [\"MCPSearch\"]  # 禁用 MCP 工具搜索\n  }\n}\n```\n\n**来源:** [MCP 文档](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fmcp), [设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)\n\n### MCP 设置示例 [官方]\n\n**适用于热门 MCP 服务器的快速入门配置。**\n\n#### GitHub 集成\n\n```bash\n# 安装\nclaude mcp add --transport stdio github -- npx -y @modelcontextprotocol\u002Fserver-github\n\n# 或通过 .mcp.json\n{\n  \"mcpServers\": {\n    \"github\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-github\"],\n      \"env\": {\n        \"GITHUB_PERSONAL_ACCESS_TOKEN\": \"${GITHUB_TOKEN}\"\n      }\n    }\n  }\n}\n```\n\n**常用操作:** 创建问题、管理 PR、搜索代码、审查仓库。\n\n#### Slack 集成\n\n```bash\n# 安装\nclaude mcp add --transport stdio slack -- npx -y @modelcontextprotocol\u002Fserver-slack\n\n# 配置\n{\n  \"mcpServers\": {\n    \"slack\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-slack\"],\n      \"env\": {\n        \"SLACK_BOT_TOKEN\": \"${SLACK_BOT_TOKEN}\",\n        \"SLACK_TEAM_ID\": \"T01234567\"\n      }\n    }\n  }\n}\n```\n\n**用法:** `> \"在 Slack 中搜索关于 API 重新设计的对话\"`\n\n#### Google Drive 集成\n\n```bash\n# 使用 OAuth 安装\nclaude mcp add --transport http gdrive https:\u002F\u002Fmcp.google.com\u002Fdrive\n\n# 或使用 stdio 并提供凭据\n{\n  \"mcpServers\": {\n    \"gdrive\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@modelcontextprotocol\u002Fserver-gdrive\"],\n      \"env\": {\n        \"GDRIVE_CREDENTIALS_PATH\": \"${HOME}\u002F.gdrive-credentials.json\"\n      }\n    }\n  }\n}\n```\n\n**认证:** 在 Claude Code 中运行 `\u002Fmcp` 并按照 OAuth 流程操作。\n\n#### PostgreSQL 数据库\n\n```bash\n# 安装\nclaude mcp add --transport stdio postgres -- npx -y @modelcontextprotocol\u002Fserver-postgres postgresql:\u002F\u002Fuser:pass@localhost\u002Fdb\n\n# 配置\n{\n  \"mcpServers\": {\n    \"postgres\": {\n      \"command\": \"npx\",\n      \"args\": [\n        \"-y\",\n        \"@modelcontextprotocol\u002Fserver-postgres\",\n        \"${DATABASE_URL}\"\n      ]\n    }\n  }\n}\n```\n\n**用法:** `> \"显示过去一周内数据库中创建的所有用户\"`\n\n#### Notion 集成\n\n```bash\n# 安装\nclaude mcp add --transport http notion https:\u002F\u002Fmcp.notion.com\u002Fmcp\n\n# 需要 Notion OAuth - 通过 \u002Fmcp 命令进行认证\n```\n\n**常用操作:** 查询数据库、创建页面、搜索工作区。\n\n#### Stripe 支付集成\n\n```bash\n# 配置\n{\n  \"mcpServers\": {\n    \"stripe\": {\n      \"command\": \"npx\",\n      \"args\": [\"-y\", \"@stripe\u002Fmcp-server\"],\n      \"env\": {\n        \"STRIPE_API_KEY\": \"${STRIPE_API_KEY}\"\n      }\n    }\n  }\n}\n```\n\n**用法:** `> \"列出最近的 Stripe 交易并汇总收入\"`\n\n### MCP 故障排除 [社区]\n\n**来自 GitHub 问题和实际使用中的常见问题及解决方案。**\n\n#### 问题: MCP 服务器未显示在列表中\n\n```bash\n# 问题\nclaude mcp list\n# 输出: \"未配置任何 MCP 服务器\"\n\n# 解决方案\n1. 检查文件位置:\n   - 用户范围: ~\u002F.claude\u002Fsettings.json\n   - 项目范围: .mcp.json（位于项目根目录）\n\n2. 验证 JSON 语法:\n   cat .mcp.json | jq .\n\n3. 检查作用域设置:\n   claude mcp add --scope project \u003Cname> ...\n\n4. 在更改配置后重启 Claude Code\n```\n\n#### 问题: 工具虽已“连接”但仍不可用\n\n```bash\n# 问题\n\u002Fmcp 显示“✓ 已连接”，但工具未出现\n\n# 解决方案\n1. 检查工具输出大小（最大 25,000 个 token）:\n   export MAX_MCP_OUTPUT_TOKENS=50000\n\n2. 验证服务器是否已启动:\n   ps aux | grep mcp\n\n3. 检查调试日志:\n   claude --debug\n   tail -f ~\u002F.claude\u002Flogs\u002Fclaude.log\n\n4. 重置项目批准:\n   claude mcp reset-project-choices\n```\n\n#### 问题: OAuth 认证失败\n\n```bash\n# 问题\n浏览器打开后，OAuth 却失败或无法完成\n\n# 解决方案\n1. 使用 \u002Fmcp 命令（而非直接 URL）\n\n2. 检查网络\u002F代理设置:\n   # 尝试关闭 VPN\u002FCloudflare Warp\n\n3. 清除 OAuth 缓存:\n   rm -rf ~\u002F.claude\u002Foauth-cache\n\n4. 验证提供商设置中的重定向 URI\n```\n\n#### 问题: Windows 上出现“连接已关闭”错误\n\n```bash\n# 问题\nMCP 服务器在 Windows 上立即关闭\n\n# 解决方案 - 使用 cmd \u002Fc 包装器:\nclaude mcp add --transport stdio myserver -- cmd \u002Fc npx -y package-name\n\n# 在 .mcp.json 中:\n{\n  \"mcpServers\": {\n    \"myserver\": {\n      \"command\": \"cmd\",\n      \"args\": [\"\u002Fc\", \"npx\", \"-y\", \"package-name\"]\n    }\n  }\n}\n```\n\n#### 问题: 环境变量未展开\n\n```bash\n# 问题\n${VAR} 直接显示为文字，而非展开\n\n# 解决方案\n1. 检查 .env 文件是否存在并已加载\n\n2. 使用默认语法:\n   \"${API_KEY:-default_value}\"\n\n3. 在运行前先在 shell 中设置:\n   export API_KEY=xxx && claude\n\n4. 对于敏感值，可使用 settings.local.json\n```\n\n#### 问题: MCP 服务器进程崩溃\n\n```bash\n# 调试步骤:\n1. 直接测试服务器:\n   npx @modelcontextprotocol\u002Fserver-github\n\n2. 检查 stdout\u002Fstderr:\n   claude --debug | grep mcp\n\n3. 验证依赖项是否已安装:\n   npm list -g | grep mcp\n\n4. 检查内存\u002F资源限制:\n   ulimit -a\n```\n\n---\n\n## 子代理\n\n**子代理是为特定任务配置的专业 AI 助手。**\n\n### 什么是子代理？[官方]\n\n子代理是针对特定工作流优化的 Claude 实例：\n\n```bash\n# 内置子代理\n- 通用型: 复杂的多步任务\n- 探索型: 快速探索代码库\n\n# 自定义子代理\n- 您可以使用自定义提示和工具创建自己的子代理\n```\n\n### 使用子代理 [官方]\n\n通过 `Task` 工具启动：\n\n```bash\n# 探索代码库\n> \"查找代码库中的所有数据库查询\"\n\n# Claude 使用:\nTask subagent_type=\"Explore\"\n     prompt=\"查找所有数据库查询，并列出包含 SQL、Prisma 或 ORM 代码的文件\"\n\n# 通用研究\n> \"研究 API 速率限制的最佳实践，并提出实施建议\"\n\n# Claude 使用:\nTask subagent_type=\"general-purpose\"\n     prompt=\"研究 API 速率限制的方法，比较各种方案，并为 Express.js 提出实施建议\"\n```\n\n### 创建自定义子代理 [官方]\n\n子代理被定义为位于 `.claude\u002Fagents\u002F` 或 `~\u002F.claude\u002Fagents\u002F` 中的 Markdown 文件：\n\n**示例：调试助手**\n\n`.claude\u002Fagents\u002Fdebugger.md`:\n```markdown\n---\nname: debugger\ndescription: 用于生产环境问题的专用调试代理\nmodel: claude-sonnet-4\nallowedTools: [Read, Grep, Glob, Bash]\n---\n\n# 调试助手\n\n你是一名专门的调试代理。你的职责是系统地调查并找出问题的根本原因。\n\n## 调试流程\n\n### 1. 收集上下文\n- 阅读错误信息和堆栈跟踪\n- 检查最近的代码变更（git log）\n- 审核相关的日志文件\n- 理解预期行为与实际行为之间的差异\n\n### 2. 提出假设\n- 列出可能的原因\n- 按可能性排序\n- 首先考虑最近的变更\n\n### 3. 系统性调查\n- 有条不紊地测试每个假设\n- 使用 Grep 查找相关代码\n- 阅读实现细节\n- 检查其他地方是否存在类似模式\n\n### 4. 根因分析\n- 确定确切的原因\n- 解释其发生的原因\n- 追踪执行路径\n\n### 5. 提出解决方案\n- 建议具体的修复方案\n- 说明各种方案的权衡\n- 提供代码示例\n- 推荐防止问题再次发生的测试方法\n\n## 限制条件\n- 不得修改代码（仅限只读分析）\n- 必须提供详细的解释\n- 必须引用具体的文件和行号\n- 必须考虑边界情况\n```\n\n**示例：代码审查代理**\n\n`.claude\u002Fagents\u002Freviewer.md`:\n```markdown\n---\nname: reviewer\ndescription: 专注于代码质量和最佳实践的代码审查专家\nmodel: claude-sonnet-4\nallowedTools: [Read, Grep, Glob]\n---\n\n# 代码审查员\n\n你是一位资深的代码审查员。请提供建设性的、可操作的反馈。\n\n## 审查标准\n\n### 代码质量\n- 可读性和可维护性\n- 命名规范\n- 代码组织\n- 遵循 DRY 原则\n\n### 正确性\n- 逻辑错误\n- 边界情况处理\n- 错误处理\n- 空值\u002F未定义检查\n\n### 性能\n- 算法效率\n- 不必要的计算\n- 内存使用\n- 数据库查询优化\n\n### 安全性\n- 输入验证\n- SQL 注入风险\n- XSS 漏洞\n- 身份验证\u002F授权\n\n### 测试\n- 测试覆盖率\n- 测试质量\n- 是否覆盖了边界情况\n\n## 输出格式\n提供结构化的反馈：\n- **优点**：做得好的地方\n- **问题**：发现的问题（附带严重程度）\n- **建议**：改进建议\n- **示例**：修复代码片段\n```\n\n### 子代理特性 [官方]\n\n#### 模型选择\n\n可以为每个代理选择不同的模型：\n\n```markdown\n---\nname: fast-explorer\nmodel: claude-haiku-4  # 快速且经济高效\n---\n```\n\n```markdown\n---\nname: deep-analyzer\nmodel: claude-opus-4  # 功能最强大\n---\n```\n\n#### 工具限制\n\n可以通过限制工具来实现专注运行：\n\n```markdown\n---\nname: readonly-analyzer\nallowedTools: [Read, Grep, Glob]  # 仅限分析\n---\n```\n\n```markdown\n---\nname: implementation-agent\nallowedTools: [Read, Write, Edit, Bash]  # 可以修改代码\n---\n```\n\n### 子代理模式 [社区]\n\n#### 并行分析\n\n```bash\n> “让多个代理分别分析不同方面”\n\n# 同时启动多个代理：\n- 安全审查代理\n- 性能分析代理\n- 代码风格代理\n- 测试覆盖率代理\n\n# 汇总结果\n```\n\n#### 顺序流水线\n\n```bash\n> “研究 → 设计 → 实现认证功能”\n\n# 依次运行的子代理：\n1. 研究代理：寻找最佳实践\n2. 设计代理：创建架构\n3. 实现代理：编写代码\n4. 审查代理：验证实现效果\n```\n\n#### 专业化团队\n\n```json\n{\n  \"frontend-agent\": \"React\u002FUI 专家\",\n  \"backend-agent\": \"API\u002F数据库专家\",\n  \"devops-agent\": \"部署\u002F基础设施专家\"\n}\n```\n\n**来源：** [子代理](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsub-agents)\n\n---\n\n## 代理团队\n\n**代理团队使多个 Claude Code 实例能够在共享上下文和直接通信的情况下协作完成复杂任务。**\n\n### 什么是代理团队？[官方]\n\n代理团队（实验性）允许您协调多个协同工作的 Claude Code 会话：\n\n```bash\n# 与子代理的主要区别：\n- 子代理：在同一会话内运行，仅向主代理汇报\n- 代理团队：独立的会话，可以直接相互沟通\n\n# 何时使用代理团队：\n✅ 研究与评审（同时从多个角度进行）\n✅ 新模块\u002F新功能开发（团队成员各自负责不同部分）\n✅ 调试具有竞争性假设的情况（并行调查）\n✅ 跨层协调（前端、后端、测试）\n\n# 不适合使用代理团队的情况：\n❌ 有依赖关系的顺序任务\n❌ 对同一文件的编辑（协调开销过大）\n❌ 简单任务（过于复杂）\n```\n\n### 启用代理团队 [官方]\n\n代理团队默认关闭。可在设置中启用：\n\n```json\n{\n  \"env\": {\n    \"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS\": \"1\"\n  }\n}\n```\n\n或者设置环境变量：\n\n```bash\nexport CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\nclaude\n```\n\n### 开始一个团队 [官方]\n\n```bash\n# 描述任务和团队结构\n> “创建一个代理团队来评审 PR #142。生成三个审查员：\n   - 一名专注于安全影响\n   - 一名检查性能影响\n   - 一名验证测试覆盖率\n   让他们各自审查并报告发现。”\n\n# Claude 创建团队并协调工作\n# 使用 Shift+向上\u002F向下键选择队友并直接与其交流\n```\n\n### 团队显示模式 [官方]\n\n| 模式 | 描述 | 适用场景 |\n|------|-------------|----------|\n| `in-process` | 所有队友都在主终端中 | 任何终端，简单设置 |\n| `tmux` | 每个队友在自己的窗格中 | 并行查看，适用于 tmux\u002FiTerm2 |\n| `auto`（默认） | 如果已在 tmux 会话中，则使用 tmux | 自动选择 |\n\n可在设置中配置：\n\n```json\n{\n  \"teammateMode\": \"in-process\"\n}\n```\n\n或者通过 CLI 标志：\n\n```bash\nclaude --teammate-mode in-process\n```\n\n### 团队控制 [官方]\n\n```bash\n# 选择队友\nShift+向上\u002F向下          # 循环切换队友\n\n# 查看队友会话\nEnter                  # 查看选定队友的会话\nEscape                 # 中断队友的发言\n\n# 管理任务\nCtrl+T                 # 切换共享任务列表\n\n# 委派模式\nShift+Tab              # 切换委派模式（只有负责人协调，不参与具体实施）\n\n# 关闭团队\n> “请研究队友关闭”\n> “清理团队”\n```\n\n### 团队架构 [官方]\n\n| 组件 | 描述 |\n|-----------|-------------|\n| **团队负责人** | 主会话，负责创建团队、生成队友并协调工作 |\n| **队友** | 独立的 Claude Code 实例，分别执行分配的任务 |\n| **任务列表** | 队友共同承担并完成的工作项目 |\n| **信箱** | 用于代理间通信的消息系统 |\n\n**存储位置：**\n- 团队配置：`~\u002F.claude\u002Fteams\u002F{team-name}\u002Fconfig.json`\n- 任务列表：`~\u002F.claude\u002Ftasks\u002F{team-name}\u002F`\n\n### 团队钩子 [官方]\n\n使用钩子来强制执行质量门控：\n\n```json\n{\n  \"hooks\": {\n    \"TeammateIdle\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'if [ ! -f .\u002Fdist\u002Foutput.js ]; then echo \\\"构建产物缺失\\\" >&2; exit 2; fi'\"\n          }\n        ]\n      }\n    ],\n    \"TaskCompleted\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"bash -c 'if ! npm test 2>&1; then echo \\\"测试失败\\\" >&2; exit 2; fi'\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n- **TeammateIdle**：当队友即将进入空闲状态时运行。退出码 2 会发送反馈并让队友继续工作。\n- **TaskCompleted**：当任务被标记为完成时运行。退出码 2 会阻止完成，并提供反馈。\n\n### 当前限制 [官方]\n\n- 无法与正在进行中的队友恢复会话\n- 任务状态可能会滞后（卡住的任务需要手动干预）\n- 关闭速度较慢（队友会先完成当前工作）\n- 每个会话只能有一个团队\n- 不支持嵌套团队（队友无法创建新团队）\n- 领队固定（无法晋升队友）\n- 权限在创建时设定（无法预先为每个队友设置权限）\n- 分屏功能需要 tmux 或 iTerm2 支持\n\n**来源**：[Agent Teams](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fagent-teams)\n\n---\n\n## 插件\n\n**插件将技能、钩子和 MCP 服务器打包在一起，便于共享。**\n\n### 什么是插件？ [官方]\n\n插件是扩展 Claude Code 的软件包：\n\n```bash\n# 一个插件可以包含：\n- 技能（功能和工作流模板）\n- 钩子（自动化）\n- MCP 服务器（外部集成）\n- 子代理定义\n```\n\n### 插件管理 [官方]\n\n```bash\n# 交互式插件管理\n> \u002Fplugin\n\n# 选项：\n- 浏览市场\n- 安装插件\n- 启用\u002F禁用插件\n- 移除插件\n- 添加自定义市场\n- 搜索已安装的插件 [v2.1.14]\n```\n\n**插件固定** [新增 v2.1.14]：现在可以将插件固定到特定的 git 提交 SHA，以确保版本稳定性：\n\n```json\n{\n  \"plugins\": {\n    \"enabledPlugins\": {\n      \"security-toolkit@official#abc123def\": true\n    }\n  }\n}\n```\n\n### 插件结构 [官方]\n\n```\nmy-plugin\u002F\n├── .claude-plugin\u002F\n│   └── plugin.json          # 元数据\n├── commands\u002F                 # 旧版命令（被视为技能）\n│   └── my-command.md\n├── skills\u002F                   # 技能\n│   └── my-skill\u002F\n│       └── SKILL.md\n├── hooks.json               # 钩子定义\n└── agents\u002F                  # MCP 服务器及子代理\n    └── mcp.json\n```\n\n**plugin.json：**\n```json\n{\n  \"name\": \"my-plugin\",\n  \"version\": \"1.0.0\",\n  \"description\": \"我的超棒插件\",\n  \"author\": \"你的名字\",\n  \"homepage\": \"https:\u002F\u002Fgithub.com\u002Fuser\u002Fplugin\",\n  \"keywords\": [\"效率\", \"测试\"]\n}\n```\n\n### 安装插件 [官方]\n\n```bash\n# 从市场安装\n> \u002Fplugin\n# 选择“浏览市场”\n# 选择并安装\n\n# 团队配置\n# .claude\u002Fsettings.json\n{\n  \"plugins\": {\n    \"enabledPlugins\": {\n      \"security-toolkit@official\": true,\n      \"custom-workflows@team\": true\n    }\n  }\n}\n```\n\n### 创建自定义市场 [官方]\n\n```json\n{\n  \"extraKnownMarketplaces\": [\n    {\n      \"name\": \"company-internal\",\n      \"type\": \"github\",\n      \"url\": \"https:\u002F\u002Fgithub.com\u002Fcompany\u002Fclaude-plugins\"\n    },\n    {\n      \"name\": \"local-dev\",\n      \"type\": \"directory\",\n      \"path\": \"\u002Fpath\u002Fto\u002Fplugins\"\n    }\n  ]\n}\n```\n\n### 团队插件自动安装 [官方]\n\n在 `.claude\u002Fsettings.json` 中配置（提交到 git）：\n\n```json\n{\n  \"plugins\": {\n    \"enabledPlugins\": {\n      \"team-workflows@company\": true\n    }\n  },\n  \"extraKnownMarketplaces\": [\n    {\n      \"name\": \"company\",\n      \"type\": \"github\",\n      \"url\": \"https:\u002F\u002Fgithub.com\u002Fcompany\u002Fclaude-plugins\"\n    }\n  ]\n}\n```\n\n当团队成员信任该仓库时，插件会自动安装。\n\n### VSCode 插件功能 [新增]\n\n在 VSCode 中使用 Claude Code 时：\n- **安装次数显示**：查看每个插件已被多少用户安装\n- **信任警告**：从不受信任的来源安装插件时会显示安全提示\n- **原生插件管理** [v2.1.16]：VSCode 扩展内置插件管理支持\n- **远程会话浏览** [v2.1.16]：OAuth 用户可以直接从会话对话框浏览和恢复远程 Claude 会话\n- **`\u002Fusage` 命令** [v2.1.14]：直接在 VSCode 中显示当前套餐使用情况\n- **会话分叉与回溯** [v2.1.19]：所有用户现在都可以使用会话分叉和回溯功能\n- **Python 虚拟环境激活** [v2.1.21]：自动激活可确保 `python` 和 `pip` 使用正确的解释器（通过 `claudeCode.usePythonEnvironment` 设置进行配置）\n- **Claude 与 Chrome 集成** [v2.1.27]：将 Claude Code 连接到 Chrome 浏览器，用于网页自动化和测试\n\n**来源**：[Plugins](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fplugins)\n\n### 桌面应用功能 [新增]\n\nClaude 桌面应用提供了一个原生界面，用于在本地运行 Claude Code 会话，并与网页端的 Claude Code 集成。\n\n**主要功能：**\n- **差异视图**：在创建 PR 之前逐文件审查 Claude 的更改，并添加内联评论\n- **使用 git worktrees 的本地并行会话**：在同一仓库中运行多个会话，每个会话都有独立的工作树\n- **`.worktreeinclude` 文件**：自动将 `.gitignore` 中的文件（如 `.env`）复制到新的工作树中\n- **启动云端会话**：直接从桌面应用启动网页端的 Claude Code\n- **捆绑的 Claude Code 版本**：包含一个稳定且受管理的 Claude Code 版本\n\n**差异视图：**\n- 点击差异统计指标（`+12 -1`）打开差异查看器\n- 点击任意一行添加内联评论\n- 按 Enter 键接受每条评论，按 Cmd+Enter 键发送所有评论\n\n**Git Worktrees：**\n在仓库根目录下创建 `.worktreeinclude` 文件：\n```\n.env\n.env.local\n**\u002F.claude\u002Fsettings.local.json\n```\n\n匹配这些模式且同时存在于 `.gitignore` 中的文件会被复制到新的工作树中。\n\n**安装：**\n- macOS：https:\u002F\u002Fclaude.ai\u002Fapi\u002Fdesktop\u002Fdarwin\u002Funiversal\u002Fdmg\u002Flatest\u002Fredirect\n- Windows x64：https:\u002F\u002Fclaude.ai\u002Fapi\u002Fdesktop\u002Fwin32\u002Fx64\u002Fexe\u002Flatest\u002Fredirect\n- Windows ARM64：https:\u002F\u002Fclaude.ai\u002Fapi\u002Fdesktop\u002Fwin32\u002Farm64\u002Fexe\u002Flatest\u002Fredirect\n\n**来源**：[Desktop Documentation](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fdesktop)\n\n---\n\n## 开发工作流\n\n### 核心开发方法 [社区]\n\n**阶段 1：理解**\n```bash\n# 首先了解代码库\n> “阅读项目结构并解释架构”\n> “使用了什么测试框架？”\n> “给我看看认证流程”\n\n# Claude 将：\n- 阅读 README、package.json 等文件\n- 分析项目结构\n- 识别关键模式\n```\n\n**阶段 2：计划**\n```bash\n# 对于复杂功能，先制定计划\n> “我需要添加用户角色和权限。请制定一个计划。”\n\n# Claude 将：\n- 将功能分解\n- 识别受影响的文件\n- 考虑边界情况\n- 创建 TodoWrite 任务\n```\n\n**阶段 3：实施**\n```bash\n# 逐步实施\n> “实施步骤 1：在用户模型中添加角色”\n\n# 然后验证\n> “运行测试”\n\n# 继续\n> “执行步骤2：为API添加权限检查”\n```\n\n**阶段4：验证**\n```bash\n# 始终验证更改\n> “运行所有测试”\n> “检查TypeScript错误”\n> “审查我们所做的更改”\n\n# 创建提交\n> “为这些更改创建一个git提交”\n```\n\n### 使用TodoWrite进行任务管理 [社区]\n\n对于复杂的多步骤工作：\n\n```bash\n> “添加用户认证系统”\n\n# Claude创建待办事项：\nTodoWrite 待办事项=[\n  {\"内容\": \"创建带有密码哈希的User模型\", \"状态\": \"in_progress\", ...},\n  {\"内容\": \"实现JWT令牌生成\", \"状态\": \"pending\", ...},\n  {\"内容\": \"添加登录\u002F注册端点\", \"状态\": \"pending\", ...},\n  {\"内容\": \"添加认证中间件\", \"状态\": \"pending\", ...},\n  {\"内容\": \"编写集成测试\", \"状态\": \"pending\", ...}\n]\n\n# 随着工作的推进，待办事项会更新：\n# ✅ “创建User模型…”已完成\n# ⏳ “实现JWT令牌…”正在进行中\n# ⏸️ “添加登录\u002F注册…”待处理\n```\n\n### 并行与串行工作 [社区]\n\n**并行（独立任务）：**\n```bash\n> “创建这三个独立的组件”\n\n# Claude可以同时处理所有任务：\n- 组件A（无依赖）\n- 组件B（无依赖）\n- 组件C（无依赖）\n```\n\n**串行（有依赖）：**\n```bash\n> “先设置数据库，再添加用户模型，然后创建API”\n\n# 必须按顺序完成：\n1. 数据库设置（其他步骤依赖于此）\n2. 用户模型（API依赖于此）\n3. API端点（依赖于模型）\n```\n\n### 质量保证模式 [社区]\n\n**自动化验证：**\n```bash\n# 更改后，自动验证\n> “运行以下检查：\n   - TypeScript编译\n   - Linting\n   - 所有测试\n   - 构建流程”\n\n# 或者创建一个技能：\n\u002Fverify-changes\n```\n\n**多视角评审：**\n```bash\n# 使用子代理进行全面评审\n> “从多个角度审查这些更改：\n   - 安全问题\n   - 性能影响\n   - 代码质量\n   - 测试覆盖率”\n\n# 启动专门的评审代理\n```\n\n---\n\n## 工具协同效应\n\nClaude Code的功能构成了一个分层的自动化堆栈。理解它们如何结合使用，能够解锁强大的工作流。\n\n### 快速参考：15种协同模式\n\n| 序号 | 协同效应 | 使用场景 |\n|---|---------|----------|\n| 1 | [探索 → 计划 → 编码 → 提交](#synergy-1-explore--plan--code--commit-official) | 标准开发工作流 |\n| 2 | [测试驱动开发](#synergy-2-test-driven-development-community) | 以质量为先的编码 |\n| 3 | [MCP + 技能](#synergy-3-mcp--skills-official) | 外部工具集成 |\n| 4 | [技能 + 钩子](#synergy-4-skills--hooks-auto-apply--enforce-official) | 自动应用专业知识 + 强制执行规则 |\n| 5 | [子代理 + 后台](#synergy-5-sub-agents--background-tasks-official) | 并行隔离的工作 |\n| 6 | [多Claude工作流](#synergy-6-multi-claude-workflows-community) | Git worktrees用于并行处理 |\n| 7 | [上下文保持](#synergy-7-context-preservation-across-sessions-community) | 会话连续性 |\n| 8 | [质量流水线](#synergy-8-quality-pipeline-hooks--tests--lint-community) | 自动化质量保障 |\n| 9 | [视觉驱动开发](#synergy-9-visual-driven-development-community) | 截图\u002F原型→代码 |\n| 10 | [日志分析流水线](#synergy-10-log-analysis-pipeline-official) | Unix管道 + Claude |\n| 11 | [模式驱动开发](#synergy-11-schema-driven-development-community) | 数据库模式→类型\u002FAPI\u002F测试 |\n| 12 | [依赖管理](#synergy-12-dependency-management-community) | 更新+测试+修复循环 |\n| 13 | [文档生成](#synergy-13-documentation-generation-community) | 代码库→动态文档 |\n| 14 | [安全重构](#synergy-14-refactoring-with-safety-net-community) | 大规模改动而不破坏现有功能 |\n| 15 | [事件响应](#synergy-15-incident-response-community) | 生产环境调试工作流 |\n\n### 功能堆栈 [官方]\n\n每个功能都有其独特的作用，并且彼此相互补充：\n\n| 层级 | 功能 | 目的 | 调用方式 |\n|-------|---------|---------|------------|\n| **连接层** | MCP | 外部工具（GitHub、Jira、数据库等） | 配置完成后自动启用 |\n| **能力层** | 技能 | 行业专业知识 + 工作流程 | 自动触发或通过“\u002F技能名”调用 |\n| **执行层** | 钩子 | 质量门禁、自动操作 | 生命周期事件 |\n| **隔离层** | 子代理 | 并行专业化工作 | 任务委派 |\n| **打包层** | 插件 | 将以上所有功能打包 | 一次性安装 |\n\n**关键洞察：** MCP连接外部系统。技能提供专业知识和工作流程（可自动触发也可手动调用）。钩子用于强制执行标准。子代理则用于隔离繁重的任务。\n\n### 协同效应1：探索→计划→编码→提交 [官方]\n\nAnthropic最佳实践推荐的工作流程如下：\n\n```bash\n# 步骤1：探索——了解现有情况\n“阅读src\u002Fauth\u002F目录，并解释当前的认证流程。\n列出所有涉及的文件及其职责。”\n\n# 步骤2：计划——扩展思维\n“深入思考如何添加OAuth2支持。制定详细计划，\n包括需要修改的文件、新增文件、依赖关系以及测试策略。”\n\n# 步骤3：编码——明确指定文件\n“按照计划实施OAuth2的改动。首先从\nsrc\u002Fauth\u002Foauth.ts开始，然后更新src\u002Fauth\u002Findex.ts使其导出该模块。”\n\n# 步骤4：提交——结构化提交信息\n“创建一个提交，提交信息为：‘feat(auth): 添加OAuth2提供商支持’”\n```\n\n**为何有效：** 每个步骤都在构建上下文。先探索可以避免错误假设。通过“深入思考”进行规划，能够调动更深层次的推理能力。明确指定文件名则减少了歧义。\n\n### 协同效应2：测试驱动开发 [社区]\n\n先编写测试，再进行实现：\n\n```bash\n# 1. 先编写失败的测试\n“为src\u002Futils\u002Fvalidation.ts中的新函数validateEmail编写测试。\n覆盖：合法邮箱、非法格式、空输入、null输入。\n使用Jest框架。该函数尚未实现——测试应该会失败。”\n\n# 2. 确认测试确实失败\n“运行npm test -- --testPathPattern=validation”\n\n# 3. 提交失败的测试\n“提交信息为：‘test(validation): 添加邮箱验证测试（红色）’”\n\n# 4. 实现使测试通过\n“现在在src\u002Futils\u002Fvalidation.ts中实现validateEmail函数，使其通过所有测试。\n使用标准的正则表达式模式，无需外部依赖。”\n\n# 5. 验证并提交\n“再次运行测试。如果全部通过，则提交：‘feat(validation): 实现邮箱验证（绿色）’”\n```\n\n**为何有效：** 测试在实现之前就定义了接口契约。Claude围绕具体目标反复迭代。Git历史清晰地展示了TDD的规范性。\n\n### 协同效应3：MCP + 技能 [官方]\n\nMCP服务器暴露的提示可以转化为技能：\n\n```bash\n# 添加MCP服务器\nclaude mcp add github -- gh-mcp\n\n# 现在可用的命令包括：\n\u002Fgithub-pr-review      # 审查当前PR\n\u002Fgithub-issues         # 列出未解决的问题\n\u002Fgithub-create-pr      # 从当前分支创建PR\n\n# 示例工作流 - 完成工单\n\u002Fgithub-issues         # “给我看看第42号问题”\n# Claude 通过 MCP 获取问题详情\n\n“实现第42号问题中描述的功能。\n请在 src\u002Ffeatures\u002F 中遵循我们的代码规范。”\n\n\u002Fgithub-create-pr      # 创建与问题关联的 PR\n```\n\n**真实的 MCP 集成：** GitHub、Jira、Linear、Notion、PostgreSQL、Slack、Figma、Google Drive。每个集成都增加了特定领域的命令。\n\n### 协同效应 4：技能 + 钩子（自动应用 + 强制执行）[官方]\n\n技能会自动激活；钩子则在生命周期事件时强制执行：\n\n```\n.claude\u002F\n├── skills\u002F\n│   └── security-review\u002F\n│       └── SKILL.md        # 在安全相关任务时自动激活\n└── settings.json           # 钩子：若发现安全问题则阻止提交\n```\n\n**技能定义**（`.claude\u002Fskills\u002Fsecurity-review\u002FSKILL.md`）：\n```markdown\n---\nname: security-review\ndescription: 分析代码中的安全漏洞。在审查认证代码、API 端点或用户输入处理时激活。\nallowed-tools: [Read, Grep, Glob]\n---\n\n激活后，检查以下内容：\n- SQL 注入（查询中使用字符串拼接）\n- XSS（HTML 中未转义的用户输入）\n- 泄露的敏感信息（代码中的 API 密钥、密码等）\n- 认证机制缺陷（缺少令牌验证）\n\n将发现的问题按文件和行号标注，并标明严重程度。\n```\n\n**钩子定义**（在 `settings.json` 中）：\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [{\n      \"tool\": \"Bash\",\n      \"command\": \"git commit\",\n      \"script\": \".claude\u002Fhooks\u002Fsecurity-check.sh\"\n    }]\n  }\n}\n```\n\n**工作流程**：\n```bash\n“审查 src\u002Fauth\u002F 中的认证代码是否存在安全问题”\n# 技能自动激活，发现安全问题\n\n“修复 src\u002Fauth\u002Flogin.ts 第45行的 SQL 注入漏洞”\n# 您进行修复\n\n“提交安全修复”\n# 钩子会在允许提交前运行 security-check.sh\n# 若仍有问题则阻止提交，若无问题则允许提交\n```\n\n### 协同效应 5：子代理 + 后台任务 [官方]\n\n隔离工作并并行执行：\n\n```bash\n# 在后台启动服务（Ctrl+B 或显式命令）\n“在后台运行 npm run dev”\n“在后台运行 npm test -- --watch”\n\n# 查看正在运行的任务\n\u002Ftasks\n\n# 主会话：使用探索代理进行研究\n“使用探索代理查找所有 API 端点及其处理函数”\n\n# 并行进行的工作：\n# - 后台：端口 3000 的开发服务器\n# - 后台：测试监视器随代码变化重新运行\n# - 子代理：扫描代码库以查找端点\n# - 主会话：可用于下一个任务\n\n# 稍后获取代理结果\n“探索代理发现了什么？”\n```\n\n**子代理类型：** `Explore`（代码库搜索）、`Plan`（架构设计），以及在 `.claude\u002Fagents\u002F` 中自定义的代理。\n\n### 协同效应 6：多 Claude 工作流 [社区]\n\n运行多个 Claude 实例以独立工作：\n\n```bash\n# 终端 1：功能开发\ncd feature-branch-worktree\nclaude\n“实现用户仪表板功能”\n\n# 终端 2：代码审查（同一仓库，不同工作树）\ncd review-worktree\nclaude\n“审查 user-dashboard 分支中的更改，重点关注安全性与性能”\n\n# 终端 3：文档编写\ncd docs-worktree\nclaude\n“根据最近的更改更新 API 文档”\n```\n\n**进阶：Claude 审查 Claude：**\n```bash\n# Claude 1 编写代码\n“为 src\u002Fapi\u002F 中的 API 端点实现限流功能”\n\n# Claude 2 进行审查（不同会话）\n“审查限流功能的实现。检查以下内容：\n- 边界情况（达到限制时会发生什么？）\n- 竞争条件（并发请求）\n- 配置灵活性（是否可以在不部署的情况下调整限制？）”\n```\n\n### 协同效应 7：跨会话上下文保持 [社区]\n\n结合 CLAUDE.md 和技能以实现连续性：\n\n**项目 CLAUDE.md：**\n```markdown\n# 项目：电商 API\n\n## 当前冲刺\n- [ ] 实现支付 Webhook\n- [ ] 添加库存跟踪\n- [x] 用户认证（已于 1 月 10 日完成）\n\n## 关键决策\n- 使用 Stripe 处理支付（参见 docs\u002Fadr\u002F001-payment-provider.md）\n- 使用 PostgreSQL 管理库存（参见 src\u002Fdb\u002Fschema.sql）\n\n## 命令\nnpm run dev      # 在端口 3000 上启动\nnpm test         # 运行 Jest 测试\nnpm run db:seed  # 初始化测试数据\n```\n\n**用于加载上下文的技能**（`.claude\u002Fskills\u002Fresume\u002FSKILL.md`）：\n```markdown\n---\nname: resume\ndescription: 继续当前冲刺的工作\n---\n\n阅读 CLAUDE.md 和当前冲刺的任务。查看 Git 提交记录。总结已完成、正在进行和接下来要做的工作。询问我想要继续做什么。\n```\n\n**使用方法：**\n```bash\nclaude\n\u002Fresume\n# Claude 读取上下文，总结当前状态，准备继续工作\n```\n\n### 协同效应 8：质量流水线（钩子 + 测试 + Lint）[社区]\n\n自动化质量保证：\n\n**钩子配置：**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [{\n      \"tool\": \"Write\",\n      \"script\": \"npm run lint:fix -- $FILE\"\n    }, {\n      \"tool\": \"Edit\",\n      \"script\": \"npm run lint:fix -- $FILE\"\n    }],\n    \"PreToolUse\": [{\n      \"tool\": \"Bash\",\n      \"command\": \"git commit\",\n      \"script\": \".claude\u002Fhooks\u002Fpre-commit.sh\"\n    }]\n  }\n}\n```\n\n**预提交钩子脚本：**\n```bash\n#!\u002Fbin\u002Fbash\nnpm run lint || exit 1\nnpm test || exit 1\necho \"所有检查已通过\"\n```\n\n**结果：** 每次文件编辑都会自动运行 Lint。每次提交都需要通过测试。无需人工干预即可确保质量。\n\n### 协同效应 9：视觉驱动开发 [社区]\n\n使用截图和原型作为实现目标：\n\n```bash\n# 分享设计原型\n“这是新仪表板的 Figma 原型 @mockups\u002Fdashboard.png\n请使用我们现有的 Button、Card 和 Chart 组件，在 src\u002Fcomponents\u002FDashboard.tsx 中实现它。布局必须完全一致。”\n\n# 根据视觉反馈迭代\n“这是当前效果的截图 @screenshots\u002Fcurrent.png\n与原型对比一下。问题在于卡片之间的间距不对，\n而且图表的颜色也不匹配。”\n\n# 调试视觉问题\n“这张截图显示了移动端的布局错误 @bugs\u002Fmobile-layout.png\n侧边栏覆盖了内容。请修复 src\u002Fstyles\u002Flayout.css 中的响应式样式。”\n```\n\n**为什么有效：** Claude 能够识别图像。具体的视觉目标可以减少歧义。迭代速度很快。\n\n### 协同效应 10：日志分析流水线 [官方]\n\nUnix 管道 + Claude 实现实时分析：\n\n```bash\n# 监控日志中的异常\ntail -f \u002Fvar\u002Flog\u002Fapp.log | claude -p \"如果看到错误或异常模式，请提醒我\"\n\n# 分析崩溃转储\ncat crash.log | claude -p \"分析这次崩溃。找出根本原因并提出修复建议。\"\n\n# 解析并汇总\ngrep \"ERROR\" app.log | claude -p \"将这些错误按类型和频率分类。哪种最为严重？\"\n\n# CI\u002FCD 集成\nnpm test 2>&1 | claude -p \"如果测试失败，请解释原因并提出修复建议\"\n```\n\n**为什么有效：** Claude 可以与 Unix 管道集成，能够与现有工具组合使用。\n\n### 协同效应 11：模式驱动开发 [社区]\n\n数据库模式作为事实来源：\n\n```bash\n# 从模式生成类型\n“读取 prisma\u002Fschema.prisma，并在 src\u002Ftypes\u002Fdatabase.ts 中生成 TypeScript 接口。\n包括 JSDoc 注释，解释每个字段的作用。”\n\n# 根据模式创建 API 端点\n“基于 schema.prisma 中的 User 模型，在 src\u002Fapi\u002Fusers.ts 中创建 CRUD 端点。使用 zod 进行验证。”\n\n# 生成测试 fixture\n“读取模式并在 tests\u002Ffixtures\u002Fusers.ts 中创建真实的测试 fixture。覆盖边界情况：空字符串、最大长度、特殊字符。”\n\n# 迁移安全检查\n“比较 prisma\u002Fschema.prisma 与当前数据库。识别破坏性更改，并提出迁移策略。”\n```\n\n**为什么有效：** 模式是契约。一切皆由此生成，它是单一事实来源。\n\n### 协同效应 12：依赖管理 [社区]\n\n在一个流程中完成更新、测试和修复：\n\n```bash\n# 检查更新\n“运行 npm outdated。对于每个重大更新，解释破坏性变更及升级所需的工作量。”\n\n# 带安全网的升级\n“将 lodash 升级到 v5。运行测试。如果出现问题，立即修复。仅在测试通过时提交代码。”\n\n# 安全审计流程\n“运行 npm audit。针对每个漏洞：\n1. 检查我们是否真的使用了受影响的代码路径\n2. 如果是，升级或寻找替代方案\n3. 如果否，记录为何可以接受”\n\n# 许可证合规\n“检查所有依赖项的许可证。标记任何 GPL 或未知许可证。我们只需要 MIT\u002FApache\u002FBSD 许可证。”\n```\n\n**为什么有效：** 依赖管理非常繁琐。Claude 负责研究和修复工作。\n\n### 协同效应 13：文档生成 [社区]\n\n代码库探索 → 实时文档：\n\n```bash\n# API 文档\n“探索 src\u002Fapi\u002F 目录，并在 docs\u002Fapi.yaml 中生成 OpenAPI 规范。包含来自实际代码的请求\u002F响应示例。”\n\n# 架构文档\n“分析代码库结构。创建 docs\u002FARCHITECTURE.md，说明：文件夹结构、数据流、使用的关键模式。”\n\n# 新员工入职指南\n“为新开发者创建 docs\u002FONBOARDING.md。内容包括：设置步骤、需要首先理解的关键文件、常见任务以及你在代码中发现的陷阱。”\n\n# 从提交记录生成变更日志\n“阅读过去一个月的 git 日志。按功能、修复和破坏性更改分组，生成 CHANGELOG.md。”\n```\n\n**为什么有效：** 文档始终与代码保持同步。它源自源代码，而非记忆。\n\n### 协同效应 14：带安全网的重构 [社区]\n\n大规模重构而不破坏系统：\n\n```bash\n# 放心重命名\n“在整个代码库中将 User 类重命名为 Account。更新所有导入、类型和文档。完成后运行测试。”\n\n# 提取组件\n“Dashboard 组件有 500 行代码。将其图表逻辑提取到 src\u002Fcomponents\u002FDashboardChart.tsx 中。确保所有行为完全一致。测试必须仍然通过。”\n\n# 更改数据结构\n“从存储 user.fullName 迁移到 user.firstName + user.lastName。更新：数据库模式、API 响应、前端显示和测试。为现有数据创建迁移脚本。”\n\n# 升级编码模式\n“将 src\u002Fservices\u002F 目录中的所有回调式异步代码替换为 async\u002Fawait。一次处理一个文件，每处理完一个文件就进行测试。”\n```\n\n**为什么有效：** TodoWrite 跟踪进度。测试验证正确性。安全地逐步修改。\n\n### 协同效应 15：事件响应 [社区]\n\n系统性调试生产环境问题：\n\n```bash\n# 初步分类\n“生产环境返回 500 错误。以下是错误日志：\n[粘贴日志]\n找出最可能的原因，并列出需要调查的文件。”\n\n# 根因分析\n“阅读已识别的文件，追踪从 API 端点到错误的代码路径。精确说明哪里出错以及原因。”\n\n# 以最小影响范围修复\n“实施尽可能小的修复方案。不要进行重构。只需止住‘出血’即可。添加 TODO 以便日后进行彻底修复。”\n\n# 事后文档记录\n“创建 docs\u002Fincidents\u002F2024-01-15-500-errors.md，记录以下内容：发生了什么、根本原因、已应用的修复措施以及预防措施。”\n```\n\n**为什么有效：** 结构化的方法可以防止慌乱。文档则能避免问题再次发生。\n\n### 提示最佳实践 [官方]\n\n基于 [Anthropic 的指导](https:\u002F\u002Fwww.anthropic.com\u002Fengineering\u002Fclaude-code-best-practices)：\n\n| 不要写... | 应该写... |\n|-----------|-----------|\n| “添加测试” | “为 src\u002Futils\u002Fdate.ts 编写 Jest 测试，覆盖：使用有效日期格式化日期、无效输入以及时区处理” |\n| “修复这个 bug” | “登录失败是因为邮箱中包含 ‘+’。修复 src\u002Fauth\u002Fvalidate.ts:23，使其能够处理邮箱地址中的加号” |\n| “审查一下这个” | “审查 src\u002Fapi\u002Fusers.ts，查看是否存在 N+1 查询、缺失的错误处理以及 SQL 注入风险” |\n| “让它更快一点” | “对 \u002Fapi\u002Fproducts 端点进行性能剖析。找出最慢的操作并优化之。目标：响应时间 \u003C100ms” |\n\n**思考模式**（逐步加深推理深度）：\n- `\"think\"` - 标准扩展思考\n- `\"think hard\"` - 更全面的分析\n- `\"think harder\"` - 深入探索各种选项\n- `\"ultrathink\"` - 最大化推理预算\n\n**文件引用：**\n```bash\n# 使用 Tab 键补全或明确路径\n“阅读 @src\u002Fauth\u002Flogin.ts 并解释认证流程”\n\n# 多个文件\n“比较 @src\u002Fapi\u002Fv1\u002Fusers.ts 和 @src\u002Fapi\u002Fv2\u002Fusers.ts —— 有什么变化？”\n```\n\n### 关键原则 [社区]\n\n**1. 理解每个功能的触发时机：**\n\n| 功能 | 触发时机... |\n|------|-------------|\n| MCP | 需要外部数据或操作 |\n| 技能 | 上下文匹配描述（自动） |\n| 命令 | 用户输入 `\u002F命令`（手动） |\n| 钩子 | 生命周期事件触发（PreToolUse、PostToolUse 等） |\n| 子代理 | 任务被委派以独立完成工作 |\n\n**2. 组合能成倍提升价值：**\n```\n仅 MCP           = 1 倍（获取数据）\nMCP + 技能         = 3 倍（获取数据 + 自动专业知识）\nMCP + 技能 + 钩子  = 9 倍（获取数据 + 专业知识 + 强制执行）\n```\n每一层都会使前一层的效果倍增。请务必投入精力进行前期配置。\n\n**3. 提示是基础：**\n如果提示过于模糊，所有协同效应都将失效。首先要掌握具体性：\n- 明确指定文件名\n- 清晰说明具体要求\n- 定义明确的成功标准\n\n**4. 我们展示了 15 种协同效应，但还有更多。**\n这些模式只是起点。您可以组合、调整它们，甚至发现属于自己的方法。最适合您的工作流，就是那些专为您的项目量身定制的。\n\n**5. 设置成本可以摊销：**\n花一小时配置 `.claude\u002F` 文件夹，就能在未来无数次会话中节省数百小时。请把它当作基础设施来对待。\n\n---\n\n## 示例库\n\n### 示例 1：添加身份验证\n\n```bash\n# 了解当前系统\n> “分析当前的用户管理系统”\n\n# 规划\n> “制定添加基于 JWT 的身份验证计划”\n\n# 实施\n> “按照计划实现身份验证系统”\n# (Claude 创建 TodoWrite 任务并逐步完成)\n\n# 测试\n> “为身份验证创建全面的测试”\n\n# 安全审查\n> “审查身份验证实现的安全性问题”\n\n# 文档\n> “更新 API 文档，加入身份验证端点”\n\n# 提交\n> “为身份验证功能创建一个 git 提交”\n```\n\n### 示例 2：性能优化\n\n```bash\n# 识别问题\n> “分析代码库中的性能瓶颈”\n\n# 制定优化计划\n> “针对发现的最关键问题制定优化计划”\n\n# 实施优化\n> “实施数据库查询优化”\n\n# 基准测试\n> “创建基准测试以衡量改进效果”\n\n# 验证\n> “运行基准测试并比较前后结果”\n```\n\n### 示例 3：Bug 调查\n\n```bash\n# 提供背景信息\n> “用户报告登录偶尔失败。以下是错误日志：[粘贴日志]”\n\n# 使用调试代理进行调查\n> “使用调试代理调查此问题”\n\n# 根因分析\n> “解释导致此问题的原因以及为什么是间歇性的”\n\n# 修复\n> “针对此问题实施修复方案”\n\n# 预防\n> “添加测试和日志记录，以防止未来再次发生”\n\n# 文档化\n> “更新 CLAUDE.md，记录我们从该问题中学到的内容”\n```\n\n### 示例 4：API 迁移\n\n```bash\n# 分析现有 API\n> “记录 v1 API 中的所有端点”\n\n# 制定迁移计划\n> “基于以下变更制定从 v1 到 v2 的迁移计划：[列出变更]”\n\n# 实现新版本\n> “在 v1 的基础上实现 v2 API”\n\n# 确保向后兼容性\n> “创建兼容层，使 v1 客户端仍能正常工作”\n\n# 测试\n> “编写测试用例，确保 v1 和 v2 均正常运行”\n\n# 文档化\n> “为 API 消费者生成迁移指南”\n```\n\n### 示例 5：设置 CI\u002FCD\n\n```bash\n# 调研\n> “调研适用于 Node.js 项目的 GitHub Actions 最佳实践”\n\n# 创建工作流\n> “创建一个 GitHub Actions 工作流，用于：\n   - 在拉取请求上运行\n   - 检查 TypeScript 编译\n   - 执行代码风格检查\n   - 运行所有测试\n   - 报告测试覆盖率”\n\n# 安全扫描\n> “将安全扫描加入工作流”\n\n# 部署\n> “在合并到主分支时自动部署到预发布环境”\n\n# 文档化\n> “在 README.md 中记录 CI\u002FCD 配置”\n```\n\n### 示例 6：多目录项目\n\n```bash\n# 添加目录\n> “将前端和后端目录添加到工作区”\n\n# 同步更改\n> “更新后端中的 User 类型定义，并将其同步到前端”\n\n# 跨项目验证\n> “确保前端的 API 调用与后端端点一致”\n\n# 并行测试\n> “在后台并行运行后端测试和前端测试”\n\n# 监控两端\n> “启动两个开发服务器，并监控错误”\n```\n\n### 示例 7：后台开发工作流\n\n```bash\n# 在后台启动所有开发服务\n> “在后台启动前端开发服务器”\n> “在后台启动后端 API 服务器”\n> “在后台以监听模式运行测试”\n\n# 配置状态栏以跟踪所有服务\n\u002Fstatusline\n\n# 同时监控所有服务\n> “监控所有后台进程是否有错误”\n\n# Claude 监控所有后台任务的日志\n# 识别跨服务的问题\n# 在不停止服务的情况下提出修复建议\n\n# 动态修复问题\n> “我看到一个 API 超时错误”\n# Claude 检查后端日志，找出原因并提出解决方案\n\n# 检查所有后台任务\n\u002Fbashes\n\n# 如需停止特定服务\n\u002Fkill \u003Cid>\n```\n\n### 示例 8：智能上下文管理\n\n```bash\n# 开始重大功能开发\n> “构建一个完整的用户认证系统，包含 JWT、刷新令牌和密码重置功能”\n\n# 随着工作的推进，上下文逐渐积累……\n# 阅读了大量文件并执行了多次操作后\n# 上下文变得非常庞大\n\n# 使用 microcompact 进行智能清理\n\u002Fcompact “focus”\n# 保留：当前认证相关的工作、近期更改、已学习的模式\n# 移除：旧文件读取、已完成的搜索、过时的上下文\n\n# 继续无缝开发，保持干净的上下文\n> “为系统添加双因素认证”\n# 当前认证工作所需的完整上下文仍然可用\n\n# 切换到新功能，进行大规模上下文重置\n\u002Fcompact\n# 完全重置，以便全新开始\n\n> “实现 Stripe 支付集成”\n# 为支付功能提供一个全新的起点\n```\n\n### 示例 9：安全优先开发\n\n```bash\n# 结合安全考虑进行规划\n> “设计我们表单的用户输入处理系统，重点关注安全最佳实践”\n\n# 实施并立即进行安全审查\n> “实现表单验证系统”\n> “审查表单验证代码是否存在安全漏洞”\n\n# 修复已发现的问题\n> “修复电子邮件字段验证中的 XSS 漏洞”\n> “验证修复是否解决了所有注入途径”\n\n# 记录安全模式\n> “更新 CLAUDE.md，记录我们的输入验证安全模式”\n\n# 设置持续的安全监控\n> “创建一个 GitHub Action，在每次 PR 提交时运行安全扫描”\n```\n\n### 示例 10：全栈多仓库开发\n\n```bash\n# 初始化多仓库工作区\n\u002Fadd-dir ~\u002Fprojects\u002Fbackend\n\u002Fadd-dir ~\u002Fprojects\u002Ffrontend\n\u002Fadd-dir ~\u002Fprojects\u002Fshared-types\n\n# 在各项目之间同步类型定义\n> “更新 shared-types 中的 User 类型，并确保后端和前端保持一致”\n\n# 并行类型检查\n> “在后台同时对三个项目运行 TypeScript 类型检查”\n\n# 监控并修复类型错误\n> “检查后台任务中是否存在类型错误”\n> “修复在前端发现的类型不匹配问题”\n\n# 跨仓库验证\n> “验证后端的所有 API 类型是否与前端客户端的预期一致”\n\n# 启动所有开发服务器\n> “在后台启动后端服务器、前端服务器以及类型监听服务”\n\n# 统一的开发体验\n> “构建结账流程，协调后端 API 和前端 UI 的更改”\n# Claude 在所有仓库中协同完成更改\n```\n\n---\n\n## 最佳实践\n\n### 针对开发者 [社区]\n\n**1. 首先设置 CLAUDE.md**\n```markdown\n- 记录项目结构\n- 列出重要命令\n- 注明规范和模式\n- 添加已知陷阱\n- 随着学习不断更新\n```\n\n**2. 使用描述性请求**\n```bash\n# 良好\n> “为登录端点添加输入验证，检查邮箱格式和密码长度”\n\n# 效果较差\n> “修复登录”\n```\n\n**3. 验证更改**\n```bash\n# 提交前务必审查\n> “向我展示所有更改”\n> “运行测试以验证这些更改”\n```\n\n**4. 增量式开发**\n```bash\n# 将大型功能分解为步骤\n> “首先，让我们添加数据库模型”\n> “现在添加 API 端点”\n> “最后添加前端表单”\n```\n\n**5. 智能利用工具**\n```bash\n# 使用 Grep 查找模式\n> “查找所有使用原生 SQL 的数据库查询”\n\n# 使用 Glob 发现文件\n> “查找所有测试文件”\n\n# 使用子代理进行探索\n> “让 Explore 代理绘制出认证流程”\n```\n\n### 决策模式 [社区]\n\n常见场景的快速决策树：\n\n**某处出现问题：**\n```\n→ 能否复现？\n  → 是：系统性调试\n  → 否：先收集更多信息\n→ 之前是否正常工作？\n  → 是：检查最近的改动（git diff）\n  → 否：检查假设\n→ 错误信息是否清晰？\n  → 是：直接解决\n  → 否：通过日志追踪执行流程\n```\n\n**添加新功能：**\n```\n→ 是否已有类似功能？\n  → 是：沿用该模式\n  → 否：调研最佳实践\n→ 是否涉及现有代码？\n  → 是：先理解其逻辑（阅读、分析）\n  → 否：独立设计\n→ 是否包含复杂逻辑？\n  → 是：先拆解（使用TodoWrite）\n  → 否：直接实现\n```\n\n**代码运行缓慢：**\n```\n→ 是否已测量性能？ → 否：先进行性能分析\n→ 是否已知瓶颈？ → 否：找出瓶颈（使用ultrathink）\n→ 是否有解决方案？ → 否：先调研，再实施并再次测量\n```\n\n**问题发生时的恢复策略：**\n```bash\n# 确认事实\n> “当前代码库的状态是什么？”\n\n# 寻找最小可行方案\n> “最简单的修复方案是什么？”\n\n# 质疑假设\n> “让我重新阅读相关代码”\n\n# 找到稳定状态\n> “让我们使用\u002Frewind回退到上一个可用状态”\n```\n\n**基于复杂度的方法：**\n| 任务类型 | 方法 |\n|-----------|------|\n| 简单（拼写错误） | 直接修复 |\n| 较简单（添加按钮） | 快速实现 |\n| 中等（新功能） | 计划 → 实施 → 测试 |\n| 复杂（架构调整） | 研究 → 设计 → 原型 → 实施 → 迁移 |\n| 不明情况 | 先探索评估，再选择合适方法 |\n\n### 团队协作 [社区]\n\n**1. 共享配置**\n```bash\n# 提交至Git：\n.claude\u002F\n├── settings.json      # 共享权限与配置\n├── commands\u002F          # 团队工作流\n├── skills\u002F            # 团队技能\n└── agents\u002F            # MCP服务器及子代理\n\n# Git忽略：\n.claude\u002Fsettings.local.json  # 个人覆盖配置\n```\n\n**2. 在CLAUDE.md中记录规范**\n```markdown\n## 团队约定\n- 所有API路由遵循RESTful风格\n- 数据库迁移使用Prisma\n- 测试采用AAA模式（安排、行动、断言）\n- 永不直接提交到主分支\n```\n\n**3. 创建工作流技能**\n```bash\n# .claude\u002Fskills\u002F\n├── code-review\u002F\n│   └── SKILL.md\n├── deploy-staging\u002F\n│   └── SKILL.md\n├── run-checks\u002F\n│   └── SKILL.md\n└── security-audit\u002F\n    └── SKILL.md\n```\n\n**4. 使用钩子确保标准执行**\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Edit|Write\",\n        \"hooks\": [\n          {\"type\": \"command\", \"command\": \"eslint-check.sh\"}\n        ]\n      }\n    ]\n  }\n}\n```\n\n### 安全措施 [社区]\n\n**1. 保护敏感文件**\n```json\n{\n  \"permissions\": {\n    \"deny\": {\n      \"Write\": [\"*.env\", \".env.*\", \"*.key\", \"*.pem\"],\n      \"Edit\": [\"*.env\", \".env.*\", \"*.key\", \"*.pem\", \".git\u002F*\"]\n    }\n  }\n}\n```\n\n**2. 执行前审查**\n```json\n{\n  \"permissions\": {\n    \"defaultMode\": \"ask\"\n  }\n}\n```\n\n**3. 使用钩子进行审计**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"echo \\\"$(date): $TOOL_NAME\\\" >> .claude\u002Faudit.log\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**4. 定期安全审查**\n```bash\n# 使用安全审查技能或命令\n> “对认证系统进行安全审计”\n```\n\n---\n\n## 故障排除\n\n### 常见问题 [社区]\n\n**问题：“上下文过大”错误**\n```bash\n# 解法1：压缩上下文\n> \u002Fcompact\n\n# 解法2：智能清理\n> \u002Fcompact \"focus\"\n\n# 预防：长时间会话中定期压缩\n```\n\n**问题：编辑工具报“未找到字符串”错误**\n```bash\n# 解决方案：先读取文件以确认具体内容\n> 读取文件以查看确切内容\n\n# 确保完全匹配，包括：\n- 空格和缩进\n- 换行符\n- 特殊字符\n\n# 如果字符串多次出现，可扩大上下文范围\n```\n\n**问题：权限被拒绝**\n```bash\n# 解法1：在提示时授予权限\n\n# 解法2：提前在settings.json中配置\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": [\"npm test\"],\n      \"Edit\": {}\n    }\n  }\n}\n```\n\n**问题：Claude无法识别最新文件更改**\n```bash\n# 解决方案：明确要求重新读取\n> “请再次读取app.ts文件”\n\n# 或者提供具体更改内容\n> “我刚刚更新了配置，以下是变更内容：[粘贴]”\n```\n\n**问题：后台任务无响应**\n```bash\n# 检查状态\n> \u002Fbashes\n\n# 如果卡住则终止\n> \u002Fkill \u003Cid>\n\n# 重启\n> “请在后台重新启动开发服务器”\n```\n\n**问题：Git操作失败**\n```bash\n# 检查Git状态\n> “运行git status”\n\n# 常见解决方法：\n- 未暂存的更改：“请先使用git add暂存文件”\n- 合并冲突：“请显示冲突并协助解决”\n- 分支问题：“请切换到正确的分支”\n```\n\n**问题：MCP服务器无法运行**\n```bash\n# 检查配置\n> “请展示MCP配置”\n\n# 确认服务器是否已启动\n> “请检查MCP服务器是否正确启动”\n\n# 查看日志\n~\u002F.claude\u002Flogs\u002Fmcp-\u003Cserver-name>.log\n\n# 重新安装\n> “请重新安装MCP服务器软件包”\n```\n\n### 错误恢复模式 [社区]\n\n针对常见错误场景的系统化处理方法。\n\n#### 会话中断后的恢复\n\n```bash\n# 若会话中途中断：\n1. 检查最近的历史记录：\n   > “我刚才在做什么？”\n\n2. 查看文件变更：\n   git diff\n\n3. 重建状态：\n   > “根据最近的变更，继续我们之前的工作”\n```\n\n#### 钩子故障\n\n```bash\n# 若钩子意外阻止操作：\n1. 检查钩子输出：\n   claude --debug\n\n2. 手动测试钩子：\n   echo '{\"tool_name\":\"Edit\",\"tool_input\":{...}}' | ~\u002F.claude\u002Fhooks\u002Fscript.sh\n\n3. 暂时禁用：\n   mv ~\u002F.claude\u002Fsettings.json ~\u002F.claude\u002Fsettings.json.bak\n\n4. 修复并恢复：\n   # 修复钩子脚本后，再恢复设置\n```\n\n#### 任务中上下文溢出\n\n```bash\n# 当复杂任务过程中出现“上下文过大”提示时：\n\n# 快速恢复：\n> \u002Fcompact \"focus\"\n> “继续完成[简要任务摘要]”\n\n# 如需彻底重置：\n> \u002Fcompact\n> “让我简要说明一下：[关键上下文]”\n\n# 预防措施：\n- 每约50次操作使用一次\u002Fcompact \"focus\"\n- 新功能应开启全新会话\n```\n\n#### 工具权限问题\n\n```bash\n# 当权限反复被请求时：\n\n# 永久授权：\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": {},      # 允许所有Bash操作\n      \"Edit\": {},      # 允许所有编辑\n      \"Write\": {}      # 允许所有写入\n    }\n  }\n}\n\n# 或针对特定场景授权：\n{\n  \"permissions\": {\n    \"allow\": {\n      \"Bash\": [\"npm test\", \"npm run build\"]\n    }\n  }\n}\n```\n\n#### 网络\u002FAPI超时\n\n```bash\n# 若操作超时：\n\n# 使用指数退避重试：\n第一次尝试失败\n等待2秒后重试\n等待4秒后重试\n等待8秒后重试\n\n# 若持续超时，则更换模型：\n> “请换一个模型再试”\n\n# 检查网络连接：\nping anthropic.com\ncurl -v https:\u002F\u002Fapi.anthropic.com\n```\n\n#### 丢失工作的恢复\n\n```bash\n\n# 如果更改未保存：\n\n1. 检查 Git：\n   git status\n   git diff\n\n2. 检查文件备份：\n   ls -la ~\u002F.claude\u002Fbackups\u002F\n\n3. 查看会话记录：\n   # 会话记录保存在 ~\u002F.claude\u002Ftranscripts\u002F\n\n4. 根据记忆重建：\n   > “根据我们的对话，重新创建 [功能]”\n```\n\n#### 针对持续性问题的调试模式\n\n```bash\n# 启用全面调试：\nclaude --debug --log-level trace\n\n# 实时跟踪日志：\ntail -f ~\u002F.claude\u002Flogs\u002Fclaude.log\n\n# 过滤特定问题：\ngrep -i error ~\u002F.claude\u002Flogs\u002Fclaude.log\ngrep -i \"mcp\" ~\u002F.claude\u002Flogs\u002Fclaude.log\n```\n\n---\n\n## 安全考虑\n\n### 安全模型 [官方]\n\nClaude Code 的运行机制包括：\n\n**1. 权限系统**\n- 工具需要明确的权限\n- 权限是会话特定的\n- 可以在设置中预先配置\n\n**2. 沙箱机制**（macOS\u002FLinux）\n```json\n{\n  \"sandbox\": {\n    \"enabled\": true,\n    \"allowUnsandboxedCommands\": false\n  }\n}\n```\n\n**3. 文件访问控制**\n```json\n{\n  \"permissions\": {\n    \"additionalDirectories\": [\"\u002Fallowed\u002Fpath\"],\n    \"deny\": {\n      \"Read\": [\"*.key\", \"*.pem\"],\n      \"Write\": [\"*.env\"],\n      \"Edit\": [\".git\u002F*\"]\n    }\n  }\n}\n```\n\n### 最佳安全实践 [社区]\n\n**1. 绝不提交敏感信息**\n```bash\n# 在设置中阻止\n{\n  \"permissions\": {\n    \"deny\": {\n      \"Write\": [\"*.env\", \"*.key\", \"*.pem\", \"*secret*\"],\n      \"Edit\": [\"*.env\", \"*.key\", \"*.pem\", \"*secret*\"]\n    }\n  }\n}\n\n# 使用钩子扫描敏感信息\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Write|Edit\",\n        \"hooks\": [\n          {\"type\": \"command\", \"command\": \"detect-secrets-hook.sh\"}\n        ]\n      }\n    ]\n  }\n}\n```\n\n**2. 审核 AI 生成的代码**\n```bash\n# 始终在部署前审核\n> “请解释这段代码的安全影响”\n> “请检查其中是否存在潜在漏洞”\n```\n\n**3. 限制工具访问**\n```json\n\u002F\u002F 用于执行分析的子代理\n{\n  \"allowedTools\": [\"Read\", \"Grep\", \"Glob\"]  \u002F\u002F 不允许修改\n}\n\n\u002F\u002F 用于实现的代理\n{\n  \"allowedTools\": [\"Read\", \"Write\", \"Edit\", \"Bash\"]  \u002F\u002F 允许修改\n}\n```\n\n**4. 审计追踪**\n```json\n{\n  \"hooks\": {\n    \"PostToolUse\": [\n      {\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"logger.sh\"  \u002F\u002F 记录所有操作\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n**5. 网络限制**\n```json\n{\n  \"sandbox\": {\n    \"network\": {\n      \"allowUnixSockets\": [\"\u002Fvar\u002Frun\u002Fdocker.sock\"],\n      \"allowLocalBinding\": true,\n      \"httpProxyPort\": 8080\n    }\n  }\n}\n```\n\n**来源：** [设置](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings)、[沙箱机制](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsandboxing)\n\n---\n\n## SDK 集成\n\n**Claude Code 可通过 TypeScript\u002FPython SDK 以编程方式使用。**\n\n### 使用场景 [官方]\n\n- 自动化 CI\u002FCD 流程\n- 在 Claude Code 上构建自定义工具\n- 创建自动化代码审查系统\n- 集成到现有开发工具中\n- 批量处理多个项目\n\n### TypeScript SDK 示例 [官方]\n\n```typescript\nimport { ClaudeCodeSDK } from '@anthropic-ai\u002Fclaude-code';\n\nconst sdk = new ClaudeCodeSDK({\n  apiKey: process.env.ANTHROPIC_API_KEY\n});\n\n\u002F\u002F 启动会话\nconst session = await sdk.startSession({\n  projectDir: '\u002Fpath\u002Fto\u002Fproject',\n  systemPrompt: '你是一名代码审查员'\n});\n\n\u002F\u002F 发送任务\nconst response = await session.chat({\n  message: '请审查这个代码库是否存在安全问题'\n});\n\nconsole.log(response.content);\n\n\u002F\u002F 结束会话\nawait session.end();\n```\n\n### Python SDK 示例 [官方]\n\n```python\nfrom anthropic_sdk import ClaudeCodeSDK\n\nsdk = ClaudeCodeSDK(api_key=os.environ[\"ANTHROPIC_API_KEY\"])\n\n# 开始会话\nsession = sdk.start_session(\n    project_dir=\"\u002Fpath\u002Fto\u002Fproject\",\n    system_prompt=\"你是一名测试生成员\"\n)\n\n# 发送任务\nresponse = session.chat(\n    message=\"为所有 API 端点生成测试\"\n)\n\nprint(response.content)\n\n# 结束会话\nsession.end()\n```\n\n**来源：** [SDK 概览](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsdk\u002Fsdk-overview)\n\n---\n\n## 实验性概念\n\n> ⚠️ **警告**：本节包含尚未在官方文档中验证的理论概念和模式。这些是供高级用户探索的实验性想法。\n\n### 概念：认知模式 [实验性]\n\n关于根据任务类型优化 Claude 处理方式的**未经验证的理论**：\n\n```bash\n# 简单创作模式\n> “创建 5 个类似的 React 组件”\n# 理论：并行处理，基于模板\n\n# 优化模式\n> “优化这个算法”\n# 理论：深度分析，多种方法\n\n# 研究模式\n> “研究并实现 X 的最佳实践”\n# 理论：网络搜索 → 分析 → 实施流程\n```\n\n**状态**：官方文档并未支持“模式”这一说法。Claude Code 对所有任务都采用相同的模型。\n\n### 概念：内核架构 [实验性]\n\n关于多层智能的**未经验证的理论框架**：\n\n```\n理论：\n┌─────────────────┐\n│   协调器  │\n└────────┬────────┘\n         │\n    ┌────┴────┬────────┬─────────┐\n    │         │        │         │\n  内存   意图  提取  验证\n  内核   内核  内核   内核\n```\n\n**状态**：这是一个概念模型，而非实际的 Claude Code 功能。Claude Code 使用的是：\n- 子代理（真实功能）\n- 技能（真实功能）\n- 钩子（真实功能）\n\n但并没有所谓的“内核架构”系统。\n\n### 概念：元待办系统 [实验性]\n\n关于由 AI 验证的高级任务管理的**未经验证的理论**：\n\n```bash\n# 理论：多代理任务验证\n1. 捕捉意图（四种方法）\n2. 多代理验证\n3. 背景执行\n4. 学习整合\n```\n\n**状态**：TodoWrite 是一个真实存在的工具，但带有多代理验证的“元待办”仍属于理论范畴。请按照文档说明使用实际的 TodoWrite 工具。\n\n### 为何要分开 [编辑说明]\n\n原始指南将以下内容混在一起：\n- **真实功能**（技能、钩子、MCP）\n- **使用模式**（如何使用这些功能）\n- **理论框架**（未经验证的概念）\n\n这导致了人们对 Claude Code 实际功能与概念性想法之间的混淆。\n\n**对于阅读此指南的人工智能代理而言**：请重点关注标有 `[OFFICIAL]` 和 `[COMMUNITY]` 的部分。将 `[EXPERIMENTAL]` 视为可尝试的想法，而非已确立的功能。\n\n---\n\n## 其他资源\n\n### 官方文档 [官方]\n- **主文档**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview\n- **CLI 参考**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fcli-reference\n- **设置**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsettings\n- **技能**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fskills\n- **钩子**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fhooks\n- **MCP**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fmcp\n- **子代理**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fsub-agents\n- **插件**：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Fplugins\n\n### 社区资源 [社区]\n- **GitHub**：https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\n- **Awesome Claude Code**：https:\u002F\u002Fgithub.com\u002Fhesreallyhim\u002Fawesome-claude-code\n- **Awesome Claude Skills**：https:\u002F\u002Fgithub.com\u002Ftravisvn\u002Fawesome-claude-skills\n\n### 获取帮助\n- **GitHub Issues**: https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Fissues\n- **Discord**: 请查看 Anthropic 的社区频道\n- **文档**: https:\u002F\u002Fcode.claude.com\n\n---\n\n## 更改日志\n\n### Claude Code CLI 发布 [官方]\n\n完整详情请参阅[官方 CHANGELOG.md](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Fblob\u002Fmain\u002FCHANGELOG.md)。\n\n**版本 2.1.39**（2026年2月10日）- 最新\n- ⚡ 改进了终端渲染性能\n- 🐛 修复了致命错误被吞没而非显示的问题\n- 🐛 修复了会话关闭后进程挂起的问题\n- 🐛 修复了终端屏幕边界处字符丢失的问题\n- 🐛 修复了详细转录视图中的空白行问题\n\n**版本 2.1.38**（2026年2月10日）\n- 🐛 修复了 VS Code 终端滚动到顶部的回归问题（在 2.1.37 中引入）\n- 🐛 修复了 Tab 键会排队发送斜杠命令而非自动补全的问题\n- 🐛 修复了使用环境变量包装器的命令的 bash 权限匹配问题\n- 🐛 修复了不使用流式传输时工具使用之间的文本消失的问题\n- 🐛 修复了在 VS Code 扩展中恢复时出现重复会话的问题\n- 🔒 改进了 heredoc 分隔符解析，以防止命令走私\n- 🔒 在沙盒模式下阻止向 `.claude\u002Fskills` 目录写入\n\n**版本 2.1.37**（2026年2月7日）\n- 🐛 修复了启用 `\u002Fextra-usage` 后 `\u002Ffast` 无法立即使用的问题\n\n**版本 2.1.36**（2026年2月7日）\n- ⚡ **Fast 模式现已适用于 Opus 4.6** [新功能]\n\n**版本 2.1.34**（2026年2月6日）\n- 🐛 修复了代理团队设置在两次渲染之间更改时导致的崩溃问题\n- 🐛 修复了被排除在沙盒之外的命令在启用 `autoAllowBashIfSandboxed` 时绕过 Bash 提问权限的问题\n\n**版本 2.1.33**（2026年2月6日）\n- 🤖 现在 tmux 中的代理队友会话可以正确地发送和接收消息\n- 🪝 新增了用于多代理工作流的 `TeammateIdle` 和 `TaskCompleted` 钩子事件 [新功能]\n- 🔧 增加了通过 `Task(agent_type)` 语法限制子代理的支持\n- 📝 为代理添加了 `memory` 前置字段（`user`、`project` 或 `local` 范围）\n- 🔌 插件名称现在会显示在技能描述中，以便更好地发现\n- 🐛 修复了提交新消息时扩展思考被打断的问题\n- 🐛 修复了流式传输端点上的 API 代理 404 错误\n- 🐛 修复了通过 `settings.json` 环境变量设置的代理配置未应用于 WebFetch 的问题\n- 📊 改进了 `\u002Fresume` 会话选择器，使其标题更清晰（移除了原始 XML 标记）\n- 📝 增强了 API 连接失败的错误信息（显示具体原因，如 ECONNREFUSED、SSL 错误）\n- 🔌 [VSCode] 添加了支持 OAuth 的远程会话功能\n- 🔌 [VSCode] 在会话选择器中增加了 Git 分支和消息数量，并支持按分支名称搜索\n- 🔌 [VSCode] 修复了加载或切换会话时滚动到底部时出现的下拉不足问题\n\n**版本 2.1.32**（2026年2月5日）\n- ✨ **Claude Opus 4.6 现已可用！** [新功能]\n- 🤖 新增了研究预览版的 **Agent Teams** 功能，用于多代理协作 [新功能]\n- 🧠 Claude 现在会在工作时自动记录并回忆 **记忆** [新功能]\n- 📊 在消息选择器中新增了“从这里总结”选项，用于部分对话的总结\n- 📁 在额外目录（`--add-dir`）内的 `.claude\u002Fskills\u002F` 中的技能现在会自动加载\n- 🐛 修复了 `@` 文件补全在子目录中显示错误相对路径的问题\n- 🔄 `--resume` 现在会复用之前对话中的 `--agent` 值\n- 🐛 修复了包含 JavaScript 模板字面量的 heredocs 导致的 bash “Bad substitution” 错误\n- 📊 技能字符预算现在会根据上下文窗口进行调整（上下文的 2%）\n- 🐛 修复了泰语\u002F老挝语空格元音渲染问题\n- 🔌 [VSCode] 修复了斜杠命令在前面有文本时错误执行的问题\n- 🔌 [VSCode] 在加载过往对话时增加了加载动画\n\n**版本 2.1.31**（2026年2月4日）\n- 💡 在退出时增加了会话恢复提示，说明如何稍后再继续对话\n- 🌐 在复选框选择中增加了来自日本 IME 的全角空格输入支持\n- 🤖 改进了系统提示，引导模型使用专用工具（Read、Edit、Glob、Grep），而不是 bash 等效工具\n- 🐛 修复了 PDF 过大导致会话永久卡死的问题\n- 🐛 修复了在沙盒模式下 bash 命令错误报告“只读文件系统”错误的问题\n- 🐛 修复了在进入计划模式后由于 `~\u002F.claude.json` 中缺少默认字段而导致的崩溃问题\n- 🐛 修复了在流式 API 路径中 `temperatureOverride` 被忽略的问题\n- 🐛 修复了 LSP 关闭\u002F退出与严格语言服务器兼容性的问题\n- ⚡ 减少了旋转动画期间终端布局的抖动\n- 📝 改进了 PDF 和请求大小错误信息（显示实际限制：100 页、20MB）\n- 💰 移除了针对第三方提供商用户（Bedrock、Vertex、Foundry）的误导性 Anthropic API 定价显示\n\n**版本 2.1.30**（2026年2月3日）\n- 📄 为 Read 工具添加了用于 PDF 的 `pages` 参数（例如，`pages: \"1-5\"`）[新功能]\n- 📄 大型 PDF（超过 10 页）现在在被提及时会返回轻量级引用\n- 🔑 为没有动态客户端注册的 MCP 服务器添加了预配置的 OAuth 凭证\n- 🔍 新增了用于排查会话问题的 `\u002Fdebug` 命令 [新功能]\n- 📊 在任务结果中增加了 token 数量、工具使用次数和持续时间指标\n- ♿ 新增了减少运动模式的配置选项（`prefersReducedMotion` 设置）[新功能]\n- 🐛 修复了 API 对话历史中出现的幽灵“(无内容)”文本块\n- 🐛 修复了提示缓存失效问题（现在会在工具描述或 schema 变化时正确重新验证）\n- 🐛 修复了在对话中带有思考块的情况下 `\u002Flogin` 后出现 400 错误的问题\n- 🐛 修复了恢复会话时因转录损坏而导致的挂起问题\n- 🐛 修复了 Max 20x 用户的速率限制消息\n- 🐛 修复了子代理无法访问 SDK 提供的 MCP 工具的问题\n- 🐛 修复了 Windows 上使用 `.bashrc` 文件时 bash 执行失败的问题\n- 🐛 修复了 VS Code 中的重复会话问题\n- ⚡ 使用 `--resume` 时，内存占用减少了 68%，尤其在会话较多的情况下\n- 📊 `TaskStop` 工具现在会显示已停止的命令\u002F任务描述\n- ⚡ `\u002Fmodel` 现在会立即执行，而不是排队\n- ⌨️ [VSCode] 在问题对话框中支持多行输入（Shift+Enter）\n\n**版本 2.1.29**（2026年1月31日）\n- ⚡ 修复了在使用 `saved_hook_context` 恢复会话时的启动性能问题\n\n**版本 2.1.27**（2026年1月30日）\n- 🔗 新增了 `--from-pr` 标志，用于恢复与特定 GitHub PR 编号或 URL 相关的会话\n- 🔗 现在会话在通过 `gh pr create` 创建时会自动链接到 PR\n- 🔒 权限现在会尊重内容级别的 `ask` 而不是工具级别的 `allow`（例如，`allow: [\"Bash\"]，ask: [\"Bash(rm *)\"]`)\n- 🔍 工具调用失败和拒绝现在会被添加到调试日志中\n- 🐛 修复了 `\u002Fcontext` 命令彩色输出显示的问题\n- 🐛 修复了状态栏与 PR 状态一起复制后台任务指示器的问题\n- 🔌 [VSCode] 启用了与 Chrome 集成的 Claude\n- 🪟 [Windows] 修复了使用 `.bashrc` 文件的用户 bash 命令执行失败的问题\n- 🪟 [Windows] 修复了控制台窗口在派生子进程时闪烁的问题\n- 🔌 [VSCode] 修复了 OAuth 令牌过期导致长时间会话后出现 401 错误的问题\n\n**版本 2.1.25**（2026年1月29日）\n- 🔧 修复了 Bedrock 和 Vertex 上网关用户的测试版标头验证错误\n- 💡 临时解决方案：设置 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1` 以避免该错误\n\n**版本 2.1.23**（2026年1月29日）\n- ⚙️ 新增可自定义的加载动词设置（`spinnerVerbs`）\n- 🔧 修复了位于企业代理后或使用客户端证书的用户的 mTLS 和代理连接问题\n- 🔧 修复了按用户隔离的临时目录，以防止在共享系统上出现权限冲突\n- 🐛 修复了启用提示缓存范围时导致 400 错误的竞争条件\n- 🐛 修复了无头流式会话结束时未取消待处理的异步钩子的问题\n- 🐛 修复了接受建议时选项卡补全无法更新输入框的问题\n- 🐛 修复了 ripgrep 搜索超时 silently 返回空结果而非报告错误的问题\n- ⚡ 通过优化屏幕数据布局提升了终端渲染性能\n- ⏱️ 将 Bash 命令修改为在显示已用时间的同时也显示超时持续时间\n- 🟣 将已合并的拉取请求在提示符底部显示紫色状态指示器\n- 🔌 [IDE] 修复了无头模式下 Bedrock 用户的模型选项显示错误区域字符串的问题\n\n**版本 2.1.22**（2026年1月28日）\n- 🔧 修复了非交互式（-p）模式下的结构化输出\n\n**版本 2.1.21**（2026年1月28日）\n- 🌐 在选项选择提示中增加了对来自日语 IME 的全角数字输入的支持\n- 🐛 修复了 Shell 补全缓存文件在退出时被截断的问题\n- 🐛 修复了在工具执行过程中中断的会话恢复时出现的 API 错误\n- 🐛 修复了对于具有大输出令牌限制的模型，自动压缩过早触发的问题\n- 🐛 修复了任务 ID 在删除后可能被重复使用的问题\n- 🐛 修复了 Windows 系统上 VS Code 扩展中文件搜索无法正常工作的问题\n- 📊 改进了读取\u002F搜索进度指示器，在进行中时显示“正在读取…”，完成时则显示“已读”\n- 🤖 改进了 Claude，使其优先选择文件操作工具（读取、编辑、写入），而非 Bash 等效命令（cat、sed、awk）\n- 🐍 [VSCode] 新增了 Python 虚拟环境的自动激活功能（`claudeCode.usePythonEnvironment` 设置）\n- 🔌 [VSCode] 修复了消息操作按钮背景颜色不正确的问题\n\n**版本 2.1.20**（2026年1月27日）\n- ⌨️ 在 Vim 普通模式中支持箭头键历史导航\n- ⌨️ 在帮助菜单中新增了外部编辑器快捷键（Ctrl+G）\n- 📊 提示符底部新增 PR 审核状态指示器（已批准\u002F要求更改\u002F待处理\u002F草稿）\n- 📁 支持通过 `--add-dir` 从额外目录加载 `CLAUDE.md` 文件（需设置 `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1`）\n- 🗑️ 通过 `TaskUpdate` 工具实现任务删除\n- 📱 根据终端高度动态调整任务列表\n- 📋 `\u002Fcopy` 命令现已向所有用户开放\n- ⚙️ 配置备份现带有时间戳并进行轮转（保留最近 5 个）\n- 🐛 修复了会话压缩问题，该问题会导致恢复时加载完整历史记录\n- 🐛 修复了智能体在主动工作期间忽略用户消息的问题\n- 🐛 修复了宽字符（表情符号、CJK 文字）渲染出现的瑕疵\n- 🐛 修复了 MCP 响应中包含特殊 Unicode 字符时的 JSON 解析错误\n- 🐛 修复了在浏览命令历史时草稿提示丢失的问题\n- 🐛 修复了取消工具使用时可能出现的崩溃问题\n\n**版本 2.1.19**（2026年1月23日）\n- ✨ 新增环境变量 `CLAUDE_CODE_ENABLE_TASKS`——将其设置为 `false` 可使用旧版任务系统\n- ✨ 新增简写 `$0`、$1 等，用于在自定义命令中访问单个参数\n- 🔄 将索引参数语法从 `$ARGUMENTS.0` 更改为 `$ARGUMENTS[0]`（方括号语法）\n- ✅ 不再需要审批那些没有额外权限或钩子的技能\n- 🐛 修复了在不支持 AVX 指令集的处理器上发生的崩溃问题\n- 🐛 修复了关闭终端时残留的 Claude Code 进程问题（处理 EIO 错误，并回退至 SIGKILL 信号）\n- 🐛 修复了 `\u002Frename` 和 `\u002Ftag` 在从不同目录恢复会话时未能更新正确会话的问题\n- 🐛 修复了从不同目录通过自定义标题恢复会话的问题\n- 🐛 修复了使用提示暂存功能（Ctrl+S）时粘贴文本丢失的问题\n- 🐛 修复了智能体列表显示“Sonnet（默认）”而非“继承（默认）”的问题\n- 🐛 修复了后台运行的钩子命令未能提前返回的问题\n- 🐛 修复了文件写入预览遗漏空行的问题\n- 🔌 [SDK] 新增了将 `queued_command` 附件消息重放为 `SDKUserMessageReplay` 事件的功能\n- 🔌 [VSCode] 启用了所有用户的会话分叉和回溯功能\n\n**版本 2.1.17**（2026年1月22日）\n- 🔧 修复了在不支持 AVX 指令集的处理器上发生的崩溃问题\n\n**版本 2.1.16**（2026年1月22日）\n- ✨ 新的任务管理系统，支持依赖关系跟踪\n- 🔌 [VSCode] 原生插件管理支持\n- 🔌 [VSCode] OAuth 用户可通过“会话”对话框浏览并恢复远程 Claude 会话\n- 🐛 修复了在恢复大量使用子智能体的会话时出现的内存不足崩溃问题\n- 🐛 修复了运行 `\u002Fcompact` 后“剩余上下文”警告仍未消失的问题\n- 🐛 修复了恢复界面中的会话标题未尊重用户语言设置的问题\n- 🪟 [IDE] 修复了 Windows 系统上 Claude Code 侧边栏视图容器启动时无法显示的竞争条件问题\n\n**版本 2.1.15**（2026年1月21日）\n- ⚠️ 对 npm 安装添加了弃用通知——引导用户运行 `claude install` 或访问 https:\u002F\u002Fdocs.anthropic.com\u002Fen\u002Fdocs\u002Fclaude-code\u002Fgetting-started\n- ⚡ 使用 React Compiler 提升了 UI 渲染性能\n- 🐛 修复了“距离自动压缩还剩上下文”警告在执行 `\u002Fcompact` 后仍未消失的问题\n- 🐛 修复了 MCP stdio 服务器超时未杀死子进程而导致 UI 卡死的问题\n\n**版本 2.1.14**（2026年1月20日）\n- ⌨️ 在 Bash 模式中新增基于历史的自动补全功能（`!`）——按下 Tab 键即可补全部分命令\n- 🔍 在已安装插件列表中新增搜索功能\n- 📌 支持将插件固定到特定的 Git 提交 SHA 值\n- 🔧 修复了上下文窗口阻塞限制计算过于激进的问题（约 65% 而不是约 98%）\n- 🐛 修复了导致并行子智能体运行时崩溃的内存问题\n- 🐛 修复了长时间运行会话中流资源清理不彻底造成的内存泄漏问题\n- 🐛 修复了在 Bash 模式中输入 `@` 符号时触发文件自动补全的问题\n- 📊 [VSCode] 新增了 `\u002Fusage` 命令，用于显示当前套餐使用情况\n\n**版本 2.1.12**（2026年1月17日）\n- 🔧 修复了消息渲染错误\n\n**版本 2.1.11**（2026年1月17日）\n- 🔧 修复了 HTTP\u002FSSE 传输方式下过多的 MCP 连接请求问题\n\n**版本 2.1.10**（2026年1月17日）\n- 🪝 新增 `Setup` 钩子事件，可通过 `--init`、`--init-only` 或 `--maintenance` CLI 标志触发\n- ⌨️ 登录时新增键盘快捷键 ‘c’，用于复制 OAuth URL\n- 🐛 修复了包含 JavaScript 模板字面量的 heredoc 的 Bash 命令问题\n- ⚡ 改进了启动流程，以便在 REPL 准备就绪之前捕获按键输入\n- 📎 文件建议现在显示为可移除的附件\n- 🔌 [VSCode] 新增了插件安装次数显示及信任警告\n\n**版本 2.1.9**（2026年1月16日）\n- ✨ `auto:N` 语法用于 MCP 工具搜索的自动启用阈值（上下文窗口百分比）\n- 📁 `plansDirectory` 设置，用于自定义计划文件存储位置\n- ⌨️ 在 AskUserQuestion 的“其他”输入中支持外部编辑器（Ctrl+G）\n- 🔗 将会话 URL 关联到来自网页会话的提交和 PR\n- 🪝 `PreToolUse` 钩子现在可以向模型返回 `additionalContext`\n- 🔧 技能中的 `${CLAUDE_SESSION_ID}` 字符串替换\n- 🐛 修复了并行工具调用导致长时间会话出现孤立 tool_result 错误的问题\n- 🐛 修复了 MCP 服务器重新连接时卡在缓存连接 Promise 上的问题\n- 🐛 修复了 Kitty 键盘协议终端中 Ctrl+Z 挂起功能无法使用的问题\n\n**版本 2.1.7**（2026年1月14日）\n- ⚙️ `showTurnDuration` 设置，用于隐藏回合持续时间消息\n- 💬 权限提示的反馈功能\n- 📱 任务通知中内联显示代理响应\n- 🔒 安全修复：通配符权限规则漏洞\n- 🪟 Windows 文件同步兼容性改进\n- 🔧 MCP 工具搜索自动模式默认启用\n- 🔗 OAuth\u002FAPI 控制台 URL 迁移到 `platform.claude.com`\n\n**版本 2.1.6**（2026年1月13日）\n- 🔍 `\u002Fconfig` 命令中的搜索功能\n- 📊 `\u002Fstats` 中的日期范围筛选（7\u002F30 天、全部时间）\n- 🔄 `\u002Fdoctor` 命令中的更新部分\n- 📁 发现嵌套的 `.claude\u002Fskills` 目录\n- 📈 `context_window.used_percentage` 和 `remaining_percentage` 状态字段\n- 🔒 权限绕过安全修复（Shell 行续写）\n\n**版本 2.1.5**（2026年1月12日）\n- 📁 `CLAUDE_CODE_TMPDIR` 环境变量，用于覆盖临时目录\n\n**版本 2.1.3**（2026年1月9日）\n- 🔀 合并了斜杠命令和技能（简化心智模型）\n- 📻 `\u002Fconfig` 中的发布通道切换（稳定版\u002F最新版）\n- ⚠️ 权限规则不可达性检测及警告\n- 📝 修复了计划文件在 `\u002Fclear` 操作后的持久化问题\n- ⏱️ 工具钩子执行超时设置为 10 分钟\n\n**版本 2.1.2**（2026年1月9日）\n- 🖼️ 拖拽图片的源路径元数据\n- 🔗 OSC 8 超链接支持文件路径（iTerm 支持）\n- 🪟 支持 Windows 包管理器（winget）\n- ⌨️ 计划模式下 Shift+Tab 实现“自动接受编辑”\n- 🔒 修复了 Bash 处理中的命令注入漏洞\n- 🧹 修复了 tree-sitter 解析树中的内存泄漏\n- 💾 大输出将持久化到磁盘而非截断\n\n**版本 2.1.0**（2025年12月23日）\n- 🔄 自动技能热重载\n- 🔀 `context: fork` 支持技能子代理\n- 🌐 `language` 设置，用于 Claude 的响应语言\n- ⌨️ Shift+Enter 在 iTerm2、WezTerm、Ghostty、Kitty 中开箱即用\n- 📁 `respectGitignore` 设置，用于项目级控制\n- 🎯 Bash 工具权限的通配符模式匹配（`*` 语法）\n- ⌨️ 统一的 `Ctrl+B` 后台运行快捷键，适用于 Bash 命令和代理\n- 🌐 `\u002Fteleport` 和 `\u002Fremote-env` 命令，面向 claude.ai 订阅用户\n- ⚡ 代理可在前言中定义钩子\n- ✂️ 新的 Vim 动作：`;` 和 `,` 重复、`y` 操作符、`p`\u002F`P` 粘贴\n- 🔧 `--tools` 标志，用于限制工具使用\n- 📄 `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` 环境变量\n- 🖼️ iTerm2 中支持 Cmd+V 图片粘贴\n\n**版本 2.0.74**（2025年12月19日）\n- 🔍 **LSP 工具**：代码智能的语言服务器协议\n- 📍 跳转到定义、查找引用、悬停文档\n- 🖥️ `\u002Fterminal-setup` 支持 Kitty、Alacritty、Zed、Warp\n- 🎨 `\u002Ftheme` 中的 `Ctrl+T` 快捷键，用于切换语法高亮\n\n**版本 2.0.72**（2025年12月18日）\n- 🌐 Chrome 版本的 Claude（Beta），可通过 Chrome 扩展控制\n- ⚡ Git 仓库中 `@` 文件建议速度提升约 3 倍\n- ⌨️ 思考切换从 Tab 键改为 Alt+T 键\n\n**版本 2.0.70**（2025年12月16日）\n- ⌨️ Enter 键可立即提交提示建议（Tab 键用于编辑）\n- 🎯 MCP 工具权限的通配符语法 `mcp__server__*`\n- 🧠 内存使用优化（大型对话减少 3 倍）\n\n**版本 2.0.67**（2025年12月12日）\n- 💡 Claude 现在会建议提示（Tab 接受或 Enter 提交）\n- 🧠 Opus 4.5 默认启用思考模式\n- 🔍 `\u002Fpermissions` 命令中的搜索功能\n\n**版本 2.0.65**（2025年12月11日）\n- ⌨️ Linux\u002FWindows 使用 Alt+P，macOS 使用 Option+P，在打字时切换模型\n- 📊 状态栏中显示上下文窗口信息\n- 🔧 `CLAUDE_CODE_SHELL` 环境变量，用于检测 Shell\n\n**版本 2.0.64**（2025年12月10日）\n- ⚡ 即时自动压缩\n- 🔄 异步代理和 Bash 命令支持唤醒消息\n- 📊 `\u002Fstats` 提供使用统计和参与度指标\n- 📝 支持命名会话：`\u002Frename` 和 `\u002Fresume \u003Cname>`\n- 📁 支持 `.claude\u002Frules\u002F` 目录\n\n**版本 2.0.60**（2025年12月6日）\n- 🔄 后台代理支持（工作时代理仍运行）\n- 🔧 `--disable-slash-commands` CLI 标志\n- 📝 “共同作者”提交信息中包含模型名称\n- 🔀 `\u002Fmcp enable|disable [server-name]` 快速切换命令\n\n**版本 2.0.51**（2025年11月24日）\n- 🧠 Opus 4.5 发布\n- 🖥️ 引入桌面版 Claude Code\n- 📝 计划模式生成更精确的计划\n\n**版本 2.0.45**（2025年11月19日）\n- ☁️ 支持 Azure AI Foundry\n- 🔐 `PermissionRequest` 钩子，用于自动批准\u002F拒绝逻辑\n\n**版本 2.0.24**（2025年10月21日）\n- 🛡️ Linux\u002FMac 上的 BashTool 沙盒模式\n- 🌐 Claude Code Web → CLI 传送支持\n\n**版本 2.0.20**（2025年10月17日）\n- ⭐ Claude Skills，用于可重用的提示模板\n\n**版本 2.0.12**（2025年10月9日）\n- 🔌 插件系统发布\n- `\u002Fplugin install`、`\u002Fplugin enable\u002Fdisable`、`\u002Fplugin marketplace`\n\n**版本 2.0.10**（2025年10月8日）\n- ✨ 重写了终端渲染器（界面流畅丝滑）\n- 🔀 使用 `@mention` 来启用或禁用 MCP 服务器\n- ⌨️ Bash 模式下 Shell 命令支持 Tab 补全\n- ✏️ PreToolUse 钩子可以修改工具输入\n- ⌨️ 按下 `Ctrl-G` 可以在系统文本编辑器中编辑提示\n\n**版本 2.0.0**（2025年9月29日）\n- 🆕 全新的原生 VS Code 扩展\n- ✨ 整个应用采用全新 UI\n- ⏪ `\u002Frewind` 可撤销代码更改\n- 📊 `\u002Fusage` 用于查看计划限制\n- ⌨️ Tab 键切换思考模式（保持状态）\n- 🔍 Ctrl-R 搜索历史记录\n- 🤖 SDK 更名为 Claude Agent SDK\n- 🔧 `--agents` 标志，用于动态子代理\n\n\n\n### 破坏性变更与弃用 [官方]\n\n**版本 2.1.x 破坏性变更：**\n\n| 变更 | 迁移路径 |\n|--------|----------------|\n| **Windows 管理设置路径** | 从 `C:\\ProgramData\\ClaudeCode\\managed-settings.json` 迁移到 `C:\\Program Files\\ClaudeCode\\managed-settings.json` |\n| **已移除 @-mention 的 MCP 启用\u002F禁用** | 请改用 `\u002Fmcp enable \u003Cname>` 或 `\u002Fmcp disable \u003Cname>` |\n| **工具钩子超时时间延长** | 现为 10 分钟（之前为 60 秒）——如果依赖快速超时，请更新脚本 |\n| **SDK 最低 zod 版本** | 需要 zod ^4.0.0 作为对等依赖项 |\n\n---\n\n### 本指南的变更记录\n\n**版本 2026.1.13（2026年2月11日）**\n- 更新至 v2.1.39（最新版本）\n- 新增 v2.1.38 和 v2.1.39 的变更日志条目：\n  - v2.1.39：终端渲染性能优化、修复致命错误显示问题、修复进程卡死问题、修复屏幕边界字符问题、修复详细日志中的空行问题\n  - v2.1.38：修复 VSCode 滚动到顶部的回归问题、修复 Tab 键自动补全问题、修复 Bash 权限匹配问题、修复流式文本显示问题、修复重复会话问题、增强 heredoc 安全性、强化沙盒技能目录保护\n- 在高级功能中新增 **快速模式** 章节，并附完整文档：\n  - 切换方式（`\u002Ffast` 命令、设置）\n  - 定价表（标准模式 vs 快速模式）\n  - 使用要求（订阅、额外用量、管理员启用）\n  - 使用场景指导（何时使用及避免使用）\n  - 速率限制行为与降级机制\n\n**版本 2026.1.12（2026年2月9日）**\n- 更新至 v2.1.37（最新版本）\n- 新增 v2.1.36 和 v2.1.37 的变更日志条目：\n  - v2.1.37：修复在启用 `\u002Fextra-usage` 后 `\u002Ffast` 未立即可用的问题\n  - v2.1.36：**快速模式现已适用于 Opus 4.6**\n- 在“用量与统计”部分新增 `\u002Fextra-usage` 和 `\u002Ffast` 斜杠命令\n\n**版本 2026.1.11（2026年2月7日）**\n- 更新至 v2.1.34\n- 新增 v2.1.32 至 v2.1.34 的变更日志条目：\n  - v2.1.34：修复代理团队设置崩溃问题，修复沙盒权限绕过被排除命令的问题\n  - v2.1.33：新增 TeammateIdle 和 TaskCompleted 钩子事件，引入 Task(agent_type) 限制语法，为代理添加内存 frontmatter 功能，改进会话选择器，支持 VSCode 远程会话 OAuth，修复多个 bug\n  - v2.1.32：**Claude Opus 4.6 上线**，推出 **代理团队** 功能（研究预览版），新增 **自动记忆** 功能，“从此处总结”消息选择器，支持 --add-dir 目录中的技能，修复多个 bug\n- 新增 **代理团队** 章节，并提供全面文档：\n  - 团队架构（负责人、队友、任务列表、邮箱）\n  - 显示模式（进程内、tmux、自动）\n  - 团队钩子（TeammateIdle、TaskCompleted）\n  - 键盘控制与限制\n- 新增 **自动记忆** 功能文档\n- 新增用于代理团队显示配置的 `--teammate-mode` CLI 标志\n- 将 `TeammateIdle` 和 `TaskCompleted` 钩子事件加入钩子表格\n- 新增 `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` 和 `CLAUDE_CODE_DISABLE_AUTO_MEMORY` 环境变量\n- 更新目录表，添加代理团队链接\n\n**版本 2026.1.10（2026年2月5日）**\n- 更新至 v2.1.31（最新版本）\n- 新增 v2.1.30 和 v2.1.31 的变更日志条目：\n  - v2.1.31：退出时增加会话恢复提示，支持日语 IME 全角空格，优化工具偏好提示，修复 PDF 错误处理问题，改进沙盒 Bash 处理，修复计划模式崩溃问题，修复温度覆盖问题，提升 LSP 兼容性，优化加载动画，改善错误提示信息\n  - v2.1.30：为阅读工具新增 PDF `pages` 参数，新增 `\u002Fdebug` 命令，新增 `prefersReducedMotion` 设置，为 MCP 预配置 OAuth，新增任务结果指标，将会话恢复内存占用降低 68%，支持 VSCode 多行输入，修复多个 bug\n- 在阅读工具部分新增 PDF `pages` 参数说明\n- 新增用于排查会话问题的 `\u002Fdebug` 斜杠命令\n- 新增 `prefersReducedMotion` 无障碍设置说明\n- 更新 PDF 限制说明（100 页、20MB）\n\n**版本 2026.1.9（2026年2月1日）**\n- 更新至 v2.1.29（最新版本）\n- 新增 v2.1.29 的变更日志条目：\n  - 修复带有 `saved_hook_context` 的会话启动性能问题\n\n**版本 2026.1.8（2026年1月31日）**\n- 更新至 v2.1.27（更新时的最新版本）\n- 新增 v2.1.25 和 v2.1.27 的变更日志条目：\n  - v2.1.27：新增 `--from-pr` 标志，用于恢复与 PR 关联的会话；通过 `gh pr create` 创建会话时自动关联权限优先级（内容级别的 `ask` 优先于工具级别的 `allow`）；新增 VSCode Chrome 集成；修复 Windows 相关问题\n  - v2.1.25：修复网关用户 Beta 标头验证问题，提供 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` 解决方案\n- 将 `--from-pr` 标志加入 CLI 标志参考\n- 新增 `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` 环境变量说明\n- 新增 VSCode Chrome 集成功能\n- 新增权限优先级说明（内容级别规则优先于工具级别规则）\n\n**版本 2026.1.7（2026年1月29日）**\n- 更新至 v2.1.23（最新版本）\n- 新增 v2.1.21 至 v2.1.23 的变更日志条目：\n  - v2.1.23：新增可自定义加载动画动词的设置，修复 mTLS\u002F代理连接问题，改进终端渲染效果，优化 Bash 超时显示\n  - v2.1.22：修复非交互模式下的结构化输出问题\n  - v2.1.21：支持日语 IME，在 VSCode 中激活 Python 虚拟环境，修复会话恢复问题，改进文件操作偏好设置\n- 新增 `spinnerVerbs` 设置说明，用于自定义加载动画提示语\n- 新增 VSCode Python 虚拟环境激活功能（`claudeCode.usePythonEnvironment`）\n- 新增合并 PR 的紫色状态指示器行为\n\n**版本 2026.1.6（2026年1月27日）**\n- 更新至 v2.1.20\n- 新增 v2.1.20 的变更日志条目：\n  - 在 Vim 普通模式下支持方向键历史导航\n  - 在帮助菜单中新增外部编辑器快捷键（Ctrl+G）\n  - 在提示符页脚中新增 PR 审核状态指示器\n  - 支持从 `--add-dir` 目录加载 CLAUDE.md 文件（需配合环境变量）\n  - 通过 TaskUpdate 工具实现任务删除\n  - 根据终端高度动态调整任务列表\n  - `\u002Fcopy` 命令现对所有用户开放\n  - 配置备份轮转机制（保留最近 5 个版本）\n  - 修复多个 bug（会话压缩、宽字符、MCP Unicode 等）\n- 新增钩子事件：`PostToolUseFailure`、`SubagentStart`\n- 新增 `\u002Fcopy` 斜杠命令说明\n- 新增 `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` 环境变量\n- 新增桌面应用功能综合章节：\n  - 支持带内联评论的差异视图\n  - 支持 Git worktrees 实现并行会话\n  - 新增 `.worktreeinclude` 文件说明\n  - 提供 macOS 和 Windows 的安装链接\n\n**版本 2026.1.5（2026年1月25日）**\n- 更新至 v2.1.19（最新版本）\n- 新增 v2.1.19 变更日志条目：\n  - `CLAUDE_CODE_ENABLE_TASKS` 环境变量，用于启用旧版任务系统\n  - 自定义命令的简写参数语法（`$0`、$1`)\n  - 将索引参数语法从 `$ARGUMENTS.0` 改为 `$ARGUMENTS[0]`（方括号语法）\n  - 无需额外权限或钩子的技能不再需要审批\n  - 所有用户均可使用 VSCode 会话分叉与回溯功能\n  - 多处 bug 修复（进程清理、会话恢复、提示暂存等）\n- 根据官方文档新增 CLI 标志：\n  - `--json-schema`：用于验证的 JSON 输出\n  - `--permission-prompt-tool`：用于处理 MCP 权限请求\n  - `--setting-sources`：用于配置源控制\n  - `--allow-dangerously-skip-permissions`：用于组合式权限绕过\n  - `--include-partial-messages`：用于流式事件\n  - `--init`、`--init-only`、`--maintenance`：设置钩子标志\n- 增加了带方括号语法和简写形式的索引参数文档\n- 增加了 VSCode 会话分叉与回溯功能\n- 增加了监控\u002F遥测环境变量章节\n- 增加了高级环境变量（`MAX_THINKING_TOKENS`、`MAX_MCP_OUTPUT_TOKENS` 等）\n\n**版本 2026.1.4（2026年1月23日）**\n- 更新至 v2.1.17（包含 AVX 指令修复的最新版本）\n- 新增 v2.1.14 至 v2.1.17 的变更日志条目：\n  - v2.1.17：修复了不支持 AVX 指令的处理器上的崩溃问题\n  - v2.1.16：引入新的任务管理系统，支持依赖跟踪、VSCode 原生插件管理及 OAuth 会话浏览\n  - v2.1.15：npm 安装弃用通知，React 编译器性能提升\n  - v2.1.14：在 bash 模式下实现基于历史记录的自动补全，支持将插件固定到 git 提交 SHA，并新增插件搜索功能\n- 在安装部分增加了 npm 弃用通知\n- 增加了 TodoWrite 依赖跟踪文档\n- 扩展了 VSCode 插件功能章节（原生插件管理、远程会话浏览、`\u002Fusage` 命令）\n- 增加了 Bash 模式自动补全的快捷键说明\n- 增加了关于将插件固定到 git 提交 SHA 的文档\n\n**版本 2026.1.3（2026年1月18日）**\n- 新增 v2.1.10 变更日志（设置钩子、OAuth 复制快捷键、VSCode 插件功能）\n- 为 `--init`、`--init-only`、`--maintenance` 标志新增了 `Setup` 钩子事件\n- 增加了 `PermissionRequest` 钩子事件文档\n- 新增了登录时复制 OAuth URL 的快捷键“c”\n- 增加了 VSCode 插件功能章节（显示安装次数、信任警告）\n- 修正了钩子事件表格，使其包含所有已记录的事件\n\n**版本 2026.1.2（2026年1月18日）**\n- 更新至 v2.1.12（包含消息渲染修复的最新版本）\n- 扩充了 CLI 标志参考，新增 30 多个标志，包括：\n  - 远程会话标志（`--remote`、`--teleport`、`--fork-session`）\n  - 系统提示自定义（`--system-prompt`、`--append-system-prompt`）\n  - 工具\u002F权限管理（`--tools`、`--allowedTools`、`--permission-mode`）\n  - 预算限制（`--max-budget-usd`、`--max-turns`）\n  - MCP 配置（`--mcp-config`、`--strict-mcp-config`）\n- 根据官方文档新增 15 余条斜杠命令：\n  - `\u002Fbug`、`\u002Fcost`、`\u002Fprivacy-settings`、`\u002Foutput-style`、`\u002Fvim`、`\u002Fsandbox`\n  - `\u002Fagents`、`\u002Finit`、`\u002Finstall-github-app`、`\u002Fpr-comments`、`\u002Freview`\n  - `\u002Fsecurity-review`、`\u002Ftodos`、`\u002Flogin`、`\u002Flogout`、`\u002Frelease-notes`\n- 重写了 MCP 安装章节，引入了新的传输类型：\n  - HTTP 传输（推荐用于托管服务）\n  - Stdio 传输（适用于本地包）\n  - 安装范围（本地、项目、用户）\n  - CLI 命令（`claude mcp add\u002Flist\u002Fget\u002Fremove`）\n- 修正了对 `\u002Fmicrocompact` 的引用（现为 `\u002Fcompact`，并附可选说明）\n- 更新了 MCP 的 OAuth 认证示例\n\n**版本 2026.1.1（2026年1月17日）**\n- 更新至 v2.1.11（最新版本）\n- 新增 v2.1.9 至 v2.1.11 的变更日志条目\n- 将所有文档链接由 docs.anthropic.com 更改为 code.claude.com\n- 增加了新的安装方式（curl 脚本、Homebrew、WinGet）\n- 增加了 MCP 工具搜索 `auto:N` 语法文档\n- 增加了 `plansDirectory` 设置文档\n- 增加了 `${CLAUDE_SESSION_ID}` 技能变量替换\n- 增加了重大变更与弃用章节\n- 增加了 PreToolUse 的 `additionalContext` 钩子功能\n\n**版本 2026.1（2026年1月）**\n- 重大更新，涵盖 v2.0.34 至 v2.1.7\n- 新增 **LSP 工具** 文档（跳转到定义、查找引用、悬停提示）\n- 新增 **思考模式** 章节（标签切换、超思考模式、Alt+T）\n- 新增 **计划模式** 文档\n- 新增 **后台任务与代理** 章节（Ctrl+B）\n- 新增全面的 **键盘快捷键** 参考\n- 新增 **环境变量** 全面列表\n- 新增 **提示建议** 文档\n- 新增 20 余条斜杠命令（如 `\u002Frewind`、`\u002Fstats`、`\u002Fusage`、`\u002Fconfig`、`\u002Fdoctor`、`\u002Fterminal-setup`、`\u002Frename`、`\u002Fresume`、`\u002Fteleport`、`\u002Fremote-env` 等）\n- 新增设置文档（语言、署名、respectGitignore 等）\n- 新增 `.claude\u002Frules\u002F` 目录文档\n- 新增通配符权限语法\n- 更新变更日志至 v2.1.7\n\n**版本 2025.0（2025年1月）**\n- 全面重写，聚焦于经过验证的功能\n- 明确区分官方内容与实验性内容\n- 新增技能系统文档\n- 新增插件文档\n- 新增 `\u002Fstatusline` 和 `\u002Fadd-dir` 命令\n- 新增 CLI 标志参考章节\n- 加强了 `@filename` 引用语法文档\n- 提供了全面的示例和模式\n- 所有内容均经官方文档核验\n\n**早期版本**曾将 Claude.ai 的网页功能（REPL、Artifacts）与 Claude Code CLI 功能混杂在一起，造成混淆。而本版本则完全专注于 Claude Code CLI。\n\n---\n\n\n\n## 自动更新流程\n\n本指南是一份**动态文档**，能够自动跟随 Claude Code 的开发进展保持最新状态。\n\n### 工作原理\n\n每两天一次的自动化流水线（UTC 时间凌晨 3 点）会运行 Claude Code，执行以下步骤：\n\n1. **检查官方来源：**\n   - [官方文档](https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview)：官方文档\n   - [GitHub 发布页面](https:\u002F\u002Fgithub.com\u002Fanthropics\u002Fclaude-code\u002Freleases)：版本变更日志\n   - [Anthropic 变更日志](https:\u002F\u002Fwww.anthropic.com\u002Fchangelog)：产品更新\n\n2. **与当前指南内容进行对比**\n\n3. **根据核实后的变更进行更新：**\n   - 新功能与能力\n   - 更改的 CLI 标志或命令\n   - 新工具或集成\n   - Bug 修复或弃用信息\n\n4. **自动提交更改**，并附详细提交信息\n\n### 更新日志\n\n有关自动化更新的历史记录，请参阅 [update-log.md](.\u002Fupdate-log.md)。\n\n### 手动触发\n\n也可手动运行更新：\n```bash\n.\u002Fscripts\u002Fupdate-guide.sh\n```\n\n## 许可\n\n本指南由社区维护，与 Anthropic 官方无关联。信息来源于官方文档（code.claude.com）及社区经验。\n\n如需官方信息，请始终参考：https:\u002F\u002Fcode.claude.com\u002Fdocs\u002Fen\u002Foverview\n\n---\n\n**指南结束**\n\n> **面向 AI 代理**：您已阅读完经过验证的 Claude Code 指南。所有标注为 `[OFFICIAL]` 的功能均已在 code.claude.com 上记录。标注为 `[COMMUNITY]` 的功能则是广泛使用的模式。而 `[EXPERIMENTAL]` 部分的内容属于理论性内容，在依赖之前应先进行测试。","# Claude Code CLI 快速上手指南\n\n## 环境准备\n\n在开始之前，请确保您的开发环境满足以下要求：\n\n*   **操作系统**：\n    *   macOS (Intel\u002FApple Silicon)\n    *   Linux (主流发行版)\n    *   Windows (需使用 PowerShell, CMD, 或 WSL2)\n*   **前置依赖**：\n    *   已安装 `curl` (macOS\u002FLinux 默认自带，Windows 需确保可用)\n    *   **API Key**：您需要拥有 Anthropic API Key 或在终端登录 `claude.ai` 账户。\n*   **网络环境**：由于服务由 Anthropic 提供，中国大陆用户可能需要配置网络代理以确保连接稳定。\n\n## 安装步骤\n\n根据您的操作系统，选择以下任一方式进行安装：\n\n### macOS \u002F Linux \u002F WSL2 (推荐)\n使用官方一键安装脚本：\n```bash\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.sh | bash\n```\n\n### Windows PowerShell\n```powershell\nirm https:\u002F\u002Fclaude.ai\u002Finstall.ps1 | iex\n```\n\n### Windows CMD\n```cmd\ncurl -fsSL https:\u002F\u002Fclaude.ai\u002Finstall.cmd -o install.cmd && install.cmd && del install.cmd\n```\n\n### 其他安装方式\n*   **macOS (Homebrew)**:\n    ```bash\n    brew install --cask claude-code\n    ```\n*   **Windows (WinGet)**:\n    ```cmd\n    winget install Anthropic.ClaudeCode\n    ```\n*   **NPM (不推荐，已弃用)**:\n    ```bash\n    npm install -g @anthropic-ai\u002Fclaude-code\n    ```\n\n### 验证安装\n安装完成后，运行以下命令检查版本：\n```bash\nclaude --version\n```\n\n## 基本使用\n\n### 1. 启动交互式会话\n在终端中输入以下命令即可启动 Claude Code。首次运行时，系统会引导您进行 API Key 配置或登录。\n\n```bash\nclaude\n```\n\n启动后，您可以直接使用自然语言描述任务，例如：\n> \"为当前的 API 添加用户认证功能\"\n> \"重构 src\u002Futils 目录下的代码以优化性能\"\n\n### 2. 执行单次任务 (非交互模式)\n如果您希望在脚本中使用或仅获取一次执行结果，可以使用 `-p` (print) 模式：\n\n```bash\nclaude -p \"分析当前项目的依赖项并列出过期的包\"\n```\n\n### 3. 常用操作示例\n\n*   **查看帮助与指令**：\n    在交互会话中输入：\n    ```text\n    \u002Fhelp\n    ```\n\n*   **继续上一次会话**：\n    ```bash\n    claude --continue\n    ```\n\n*   **指定模型运行**：\n    ```bash\n    claude --model opus \"优化数据库查询逻辑\"\n    ```\n\n*   **后台任务管理**：\n    查看正在运行的后台进程：\n    ```text\n    \u002Fbashes\n    ```\n\n### 4. 权限与安全\nClaude Code 采用增量授权机制。对于读取文件、搜索等安全操作无需授权；但对于**修改文件**、**执行命令**或**访问网络**，首次操作时会向您请求许可。您可以在项目根目录创建 `.claude\u002Fsettings.json` 来配置默认权限策略。","某后端工程师正紧急接手一个遗留微服务项目，需要在半天内理解复杂架构并修复一个隐蔽的并发 Bug。\n\n### 没有 claude-code-guide 时\n- **文档滞后导致命令试错**：官方 CLI 命令每两周就有更新，工程师依赖过时的博客教程，频繁遇到 `--resume` 或 `\u002Fcompact` 等参数报错，浪费大量时间排查版本差异。\n- **高级功能无人问津**：由于缺乏对 MCP 集成、Sub-Agents（子代理）及 Hooks 系统的清晰指引，工程师仅将其当作普通聊天机器人使用，无法让 AI 自主运行测试或并行处理多个文件修改。\n- **上下文管理失控**：在长对话中不知如何使用 `\u002Fcompact` 指令压缩上下文，导致 Claude 逐渐“遗忘”早期关键代码逻辑，重复解释需求，效率极低。\n- **安全边界模糊**：不清楚沙箱执行机制和权限配置，不敢让 AI 直接执行数据库迁移脚本，只能手动操作，失去了自动化闭环的机会。\n\n### 使用 claude-code-guide 后\n- **指令精准零试错**：查阅实时更新的 Quick Reference 章节，直接使用最新的 `claude -p` 非交互模式生成补丁，并利用准确的 Session 管理命令无缝衔接中断的工作流。\n- **释放 Agent 全部潜能**：参考 Examples Library 快速配置 MCP 连接本地数据库，并启用 Sub-Agents 并行重构三个微服务模块，将原本串行的工作变为并发处理。\n- **长任务记忆持久化**：依据最佳实践，在关键节点主动使用 `\u002Fcompact [instructions]` 提炼核心逻辑，确保 AI 始终聚焦于并发锁的竞争条件分析，无遗漏。\n- **安全高效闭环**：对照 Security 章节配置沙箱规则，放心授权 claude-code-guide 自动运行集成测试并回滚失败变更，实现了从定位到修复的全自动无人值守流程。\n\nclaude-code-guide 通过将碎片化的官方文档转化为可执行的实战手册，帮助开发者将 AI 编码助手从“简单的问答工具”升级为“真正的全栈自动驾驶仪”。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002FCranot_claude-code-guide_d872fe45.png","Cranot",null,"https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002FCranot_835b0f37.png","CosmoHac","Greece","DimitriosMitsos","https:\u002F\u002Fagentskb.com","https:\u002F\u002Fgithub.com\u002FCranot",[81],{"name":82,"color":83,"percentage":84},"Shell","#89e051",100,2567,283,"2026-04-04T22:50:43","macOS, Linux, Windows","未说明",{"notes":91,"python":89,"dependencies":92},"该工具是运行在终端的 CLI 应用程序，而非本地部署的 AI 模型，因此无需 GPU、特定显存或 CUDA 环境。主要通过官方脚本、包管理器（Homebrew, WinGet）或 NPM 安装。需要网络连接以调用 Anthropic API。权限管理支持‘询问’、‘允许’和‘拒绝’模式，可配置全局或项目级设置。",[93,94],"Node.js (隐含，通过 NPM\u002FHomebrew\u002FWinget 安装)","@anthropic-ai\u002Fclaude-code",[35,13,52],"2026-03-27T02:49:30.150509","2026-04-11T16:50:06.555353",[],[]]