Add Vietnamese (Tiếng Việt) Localization (#42)

* feat(i18n): add Vietnamese localization infrastructure

Add comprehensive infrastructure for Vietnamese translation of the
claude-howto documentation:

Features:
- Parallel vi/ directory structure for Vietnamese content
- Modified build_epub.py with --lang flag for Vietnamese EPUB
- Vietnamese-specific pre-commit hooks for quality checks
- Translation support files (glossary, style guide, queue tracker)
- sync_translations.py script to detect outdated translations

Infrastructure:
- vi/ directory with all 10 module subdirectories
- TRANSLATION_NOTES.md: comprehensive glossary and style guide
- TRANSLATION_QUEUE.md: progress tracking for 66+ files
- vi/README.md: Vietnamese landing page

EPUB Build:
- Added --lang CLI flag (en/vi) to build_epub.py
- Language-specific metadata (title, subtitle)
- Automatic root path adjustment for vi/ directory
- Dynamic output filename (claude-howto-guide-vi.epub)

Quality Assurance:
- Vietnamese markdown linting
- Vietnamese cross-reference checking
- Vietnamese Mermaid syntax validation
- Vietnamese link checking
- Vietnamese EPUB build validation

Ready for translation work to begin.

* feat(vi): translate INDEX.md to Vietnamese

Complete Vietnamese translation of INDEX.md - the comprehensive
index of all example files in the repository.

Translation follows vi/TRANSLATION_NOTES.md guidelines:
- Technical terms kept per glossary (slash command → "lệnh slash")
- File paths and code blocks preserved in English
- Table structure and formatting maintained
- All 882 lines translated

Content includes:
- Complete file tree (10 modules, 100+ files)
- Feature coverage matrix
- Quick start guides by use case
- Learning path progression
- Search by keyword sections

Progress: 1/5 core documents completed

* feat(vi): translate CATALOG.md to Vietnamese

Complete Vietnamese translation of CATALOG.md - the quick reference
guide to all Claude Code features.

Translation follows vi/TRANSLATION_NOTES.md guidelines:
- Technical terms kept per glossary (slash command → "lệnh slash")
- All command names preserved (/help, /optimize, etc.)
- Code blocks, JSON examples, and bash commands unchanged
- All tables and formatting maintained
- 517 lines translated with complete feature coverage

Content includes:
- Summary statistics (99 built-in + 43 examples = 117 total)
- Complete built-in commands reference (55+ commands)
- Custom commands examples (8 commands)
- Permission modes (6 modes)
- Subagents (6 built-in + 10 custom)
- Skills (5 bundled + 4 custom)
- Plugins (3 complete plugins)
- MCP servers (1 built-in + 8 common servers)
- Hooks (25 events + 7 example hooks)
- Memory files (7 types)
- New features (March 2026) - 17 new features
- Installation priority guide
- Complete one-command installation

Progress: 2/5 core documents completed

* docs(vi): translate learning roadmap to Vietnamese

- Add complete Vietnamese translation of LEARNING-ROADMAP.md (747 lines)
- Include self-assessment quiz for level determination
- Translate three learning levels: Beginner, Intermediate, Advanced
- Translate all milestones (1A, 1B, 2A, 2B, 3A, 3B) with hands-on exercises
- Preserve Mermaid diagram for learning path visualization
- Maintain progress tracking checklists and learning tips

* docs(vi): translate quick reference guide to Vietnamese

- Add complete Vietnamese translation of QUICK_REFERENCE.md (507 lines)
- Include installation quick commands for all features
- Translate feature cheat sheet with usage examples
- Translate common use cases (code review, documentation, DevOps, etc.)
- Preserve all code snippets, commands, and file paths in English
- Maintain file locations reference diagram
- Include learning path and new features (March 2026) sections
- Keep tips & tricks, feature matrix, and checklist intact

* docs(vi): translate module 01 - slash commands to Vietnamese

- Add complete Vietnamese translation of 01-slash-commands/README.md (553 lines)
- Translate slash commands overview and architecture
- Include 55+ built-in commands reference table with Vietnamese descriptions
- Translate bundled skills section (5 skills)
- Document custom commands (now skills) migration path
- Include frontmatter reference, arguments, and dynamic context sections
- Preserve all command names, code examples, and Mermaid diagrams
- Translate 8 available commands in folder with usage examples
- Include installation, troubleshooting, and best practices sections

* docs(vi): update translation queue progress - Module 01 README done

- Mark 01-slash-commands/README.md as completed (2026-04-02)
- Update Module 01 progress: 1/9 files (11%)
- Update overall progress: 6/66 files (9%)
- Update Priority 2 progress: 1/31 files (3%)
- Add recent completion note to queue header

* docs(vi): translate slash command - commit to Vietnamese

- Translate commit.md slash command to Vietnamese
- Keep all git commands and technical syntax intact
- Translate instructions and descriptions
- Maintain conventional commits format documentation

* docs(vi): translate slash command - doc-refactor to Vietnamese

- Translate doc-refactor.md slash command to Vietnamese
- Keep all technical terms and file paths intact
- Translate documentation refactoring instructions
- Maintain structure and numbering

* docs(vi): translate slash command - generate-api-docs to Vietnamese

- Translate generate-api-docs.md slash command to Vietnamese
- Keep all technical terms and file paths intact
- Translate API documentation generation instructions
- Maintain output format specifications

* docs(vi): translate slash command - optimize to Vietnamese

- Translate optimize.md slash command to Vietnamese
- Keep all technical terms and code concepts intact
- Translate code optimization instructions
- Maintain issue priority and response format

* docs(vi): translate slash command - pr to Vietnamese

- Translate pr.md slash command to Vietnamese
- Keep all commands and technical syntax intact
- Translate PR preparation checklist instructions
- Maintain conventional commits format documentation

* docs(vi): translate slash command - push-all to Vietnamese

- Translate push-all.md slash command to Vietnamese (153 lines)
- Keep all git commands and technical syntax intact
- Translate comprehensive workflow with safety checks
- Maintain API key validation patterns and error handling
- Preserve when to use/avoid sections and alternatives

* docs(vi): translate slash command - setup-ci-cd to Vietnamese

- Translate setup-ci-cd.md slash command to Vietnamese
- Keep all tool names and technical terms intact
- Translate CI/CD pipeline implementation instructions
- Maintain pre-commit hooks and GitHub Actions sections

* docs(vi): translate slash command - unit-test-expand to Vietnamese

- Translate unit-test-expand.md slash command to Vietnamese
- Keep all framework names and technical terms intact
- Translate test coverage expansion instructions
- Maintain testing frameworks and scenario sections

* docs(vi): update translation queue - Module 01 complete (100%)

- Mark all 9 Module 01 files as completed (2026-04-02)
- Update Module 01 progress: 9/9 files (100%) 
- Update overall progress: 14/66 files (21%)
- Update Priority 2 progress: 9/31 files (29%)
- Update header with Module 01 completion milestone

Module 01: Slash Commands - All files translated:
 README.md (overview, built-in commands, skills)
 commit.md (git commit with context)
 doc-refactor.md (documentation restructuring)
 generate-api-docs.md (API documentation generator)
 optimize.md (code optimization analysis)
 pr.md (pull request preparation)
 push-all.md (stage, commit, push with safety)
 setup-ci-cd.md (CI/CD pipeline implementation)
 unit-test-expand.md (test coverage expansion)

* docs(vi): translate module 02 - memory guide to Vietnamese

- Add complete Vietnamese translation of 02-memory/README.md (1162 lines)
- Translate memory system overview and architecture
- Include quick reference for memory commands (/init, /memory, #)
- Document complete memory hierarchy (8 levels with precedence)
- Translate auto memory section with architecture diagrams
- Include practical examples (project, directory-specific, personal memory)
- Add best practices, installation instructions, and troubleshooting
- Preserve all code examples, file paths, and technical terms
- Maintain Mermaid diagrams and tables

* docs(vi): translate example project CLAUDE.md to Vietnamese

- Translate project-CLAUDE.md example memory file
- Keep all technical terms, commands, and code style intact
- Translate descriptions and explanations
- Maintain project configuration structure

* docs(vi): translate example personal CLAUDE.md to Vietnamese

- Translate personal-CLAUDE.md example memory file
- Keep all technical terms, tools, and preferences intact
- Translate descriptions and explanations
- Maintain personal preferences structure

* docs(vi): translate example directory-specific CLAUDE.md to Vietnamese

- Translate directory-api-CLAUDE.md example memory file
- Keep all technical terms, API standards, and code examples intact
- Translate descriptions and explanations
- Maintain API module standards structure

* docs(vi): update translation queue - Module 02 complete (100%)

- Mark all 4 Module 02 files as completed (2026-04-02)
- Update Module 02 progress: 4/4 files (100%) 
- Update overall progress: 18/66 files (27%)
- Update Priority 2 progress: 13/31 files (42%)
- Update header with Module 02 completion milestone

Module 02: Memory - All files translated:
 README.md (1162 lines - comprehensive memory guide)
 project-CLAUDE.md (example project memory)
 personal-CLAUDE.md (example personal preferences)
 directory-api-CLAUDE.md (example directory-specific rules)

* docs(vi): translate module 03 - skills guide to Vietnamese

- Add complete Vietnamese translation of 03-skills/README.md (805 lines)
- Translate Agent Skills overview and architecture
- Include progressive disclosure loading mechanism (3 levels)
- Document skill types, locations, and automatic discovery
- Translate skill creation process and SKILL.md format
- Include required and optional frontmatter fields
- Document skill content types (reference vs task)
- Translate controlling skill invocation and string substitutions
- Include dynamic context injection with shell commands
- Document running skills in subagents with context: fork
- Translate 6 practical examples with directory structures
- Add supporting files, management, and best practices sections
- Preserve all code examples, YAML frontmatter, and Mermaid diagrams
- Maintain tables, troubleshooting guides, and security considerations

* docs(vi): translate skill - blog-draft to Vietnamese

- Translate blog-draft/SKILL.md to Vietnamese (275 lines)
- Keep all workflow steps and technical structure intact
- Translate instructions and descriptions
- Maintain version tracking and file structure
- Preserve all markdown formatting and code examples

* docs(vi): translate skill - brand-voice to Vietnamese

- Translate brand-voice/SKILL.md to Vietnamese (73 lines)
- Keep brand identity, tone, and vocabulary intact
- Translate writing guidelines and examples
- Maintain preferred/avoided terms sections
- Preserve good/bad examples with explanations

* docs(vi): translate skill - claude-md to Vietnamese

- Translate claude-md/SKILL.md to Vietnamese (213 lines)
- Keep all golden rules and core principles intact
- Translate execution flow and content strategy
- Maintain WHAT/WHY/HOW structure
- Preserve quality constraints and validation checklist
- Keep anti-patterns and output format sections

* docs(vi): translate skill - code-review to Vietnamese

- Translate code-review/SKILL.md to Vietnamese (71 lines)
- Keep all review categories and template intact
- Translate security, performance, quality, maintainability sections
- Maintain review template structure
- Preserve version history

* docs(vi): translate skill - refactor to Vietnamese

- Translate refactor/SKILL.md to Vietnamese (427 lines)
- Keep all Martin Fowler refactoring methodology intact
- Translate 6-phase workflow with detailed steps
- Maintain core principles and safety rules
- Preserve code smell catalog and refactoring techniques
- Keep quick start example with before/after code
- Maintain version history and references sections

* docs(vi): update translation queue - Module 03 complete (100%)

- Mark all 6 Module 03 files as completed (2026-04-02)
- Update Module 03 progress: 6/6 files (100%) 
- Update overall progress: 24/66 files (36%)
- Update Priority 2 progress: 19/31 files (61%)
- Update header with Module 03 completion milestone

Module 03: Skills - All files translated:
 README.md (805 lines - comprehensive skills guide)
 blog-draft/SKILL.md (275 lines - blog post creation workflow)
 brand-voice/SKILL.md (73 lines - brand voice consistency)
 claude-md/SKILL.md (213 lines - CLAUDE.md best practices)
 code-review/SKILL.md (71 lines - comprehensive code review)
 refactor/SKILL.md (427 lines - Fowler refactoring methodology)

* docs(vi): translate Module 04 Subagents README

Complete Vietnamese translation of subagents reference guide:
- Configuration and built-in subagents (general-purpose, Plan, Explore, Bash, statusline-setup, Claude Code Guide)
- Agent management with /agents command
- Automatic delegation vs explicit invocation
- Resumable agents and chaining
- Persistent memory across agent sessions
- Background subagents for parallel work
- Worktree isolation for safe experimentation
- Agent Teams (experimental feature)
- Best practices and usage patterns

* docs(vi): complete Module 04 Subagents translation

Translate all 6 subagent example definitions:
- code-reviewer.md: Expert code review specialist
- debugger.md: Root cause analysis and debugging
- documentation-writer.md: Technical documentation creation
- implementation-agent.md: Full-stack feature implementation
- secure-reviewer.md: Security-focused code review
- test-engineer.md: Comprehensive test coverage

Update translation queue progress:
- Module 04: 7/7 files (100%) 
- Overall: 31/66 files (47%)
- Next: Module 05 (MCP)

* docs(vi): complete Module 05 MCP translation

Translate comprehensive MCP (Model Context Protocol) guide:
- Overview and architecture diagrams
- Installation methods (HTTP, Stdio, SSE, WebSocket)
- OAuth 2.0 authentication support
- MCP tool search and dynamic updates
- Elicitation and prompt slash commands
- Configuration management (local, project, user scopes)
- Practical examples (GitHub, Database, Filesystem, Slack MCPs)
- MCP vs Memory decision matrix
- Code execution approach for solving context bloat
- MCPorter runtime reference
- Security best practices and troubleshooting

Translate 4 MCP configuration JSON examples:
- filesystem-mcp.json: File operations
- github-mcp.json: GitHub integration
- database-mcp.json: SQL queries
- multi-mcp.json: Multiple servers configuration

Update translation queue progress:
- Module 05: 5/5 files (100%) 
- Overall: 36/66 files (55%)
- Next: Module 06 (Hooks)

* docs(vi): complete Module 06 Hooks translation

Translate comprehensive Hooks guide:
- Overview and architecture
- Configuration structure (user, project, local scopes)
- Four hook types: command, HTTP, prompt, agent
- 25 hook events with matcher patterns
- Component-scoped hooks and subagent frontmatter
- JSON input/output format and exit codes
- Environment variables and best practices
- Security considerations and debugging
- Installation instructions

Copy 9 hook example files (code, no translation needed):
- format-code.sh: Auto-format code after write/edit
- log-bash.sh: Bash command logging
- notify-team.sh: Team notifications
- pre-commit.sh: Pre-commit validation
- security-scan.sh: Security scanning
- validate-prompt.sh: Prompt validation
- context-tracker.py: Token usage tracking
- context-tracker-tiktoken.py: Accurate token counting

Update translation queue progress:
- Module 06: 9/9 files (100%) 
- Overall: 45/67 files (67%)
- Next: Module 07 (Plugins)

* docs(vi): complete Module 07 Plugins translation

Translate comprehensive Plugins guide:
- Overview and architecture diagrams
- Plugin loading process and lifecycle
- Plugin types (Official, Community, Organization, Personal)
- Plugin definition structure and manifest
- Plugin structure example with all directories
- LSP server configuration and examples
- Plugin options (v2.1.83+) with userConfig
- Persistent plugin data via CLAUDE_PLUGIN_DATA
- Inline plugins via settings (v2.1.80+)
- Standalone vs Plugin approach comparison
- Practical examples (PR Review, DevOps, Documentation plugins)
- Plugin marketplace and distribution
- Marketplace configuration and definition schema
- Plugin source types and distribution methods
- Plugin CLI commands and installation methods
- Plugin features comparison table
- Testing, hot-reload, and managed settings
- Plugin security restrictions
- Publishing workflow and best practices
- Complete troubleshooting guide

Copy all plugin subdirectories (code, no translation needed):
- devops-automation/: Deployment workflows, incident management
- documentation/: API docs, README generation, templates
- pr-review/: Pull request review automation

Update translation queue progress:
- Module 07: 10+/10+ files (100%) 
- Overall: 55+/67 files (82%)
- Next: Module 08-10 (Checkpoints, Advanced Features, CLI)

* docs(vi): complete Modules 08-10 translation

Module 08: Checkpoints and Rewind (2 files)
- Overview and architecture
- Access methods (keyboard shortcut, slash command)
- Five rewind options (restore code+conversation, conversation, code, summarize, cancel)
- Automatic checkpoints and retention policies
- Use cases and practical examples
- Integration with git and best practices

Module 09: Advanced Features (3 files)
- Planning Mode: Two-phase implementation approach
- Extended Thinking: Deep reasoning for complex problems
- Auto Mode: Background safety classifier
- Background Tasks, Scheduled Tasks
- Permission Modes (default, acceptEdits, plan, auto, dontAsk, bypassPermissions)
- Print Mode, Session Management
- Voice Dictation, Channels, Remote Control
- Web Sessions, Desktop App, Task List
- Git Worktrees, Sandboxing, Managed Settings

Module 10: CLI Reference (1 file)
- CLI commands reference
- Core flags and options
- Interactive vs Print Mode
- Model selection and configuration
- System prompt customization
- Tool & permission management
- Output formats and scripting

Update translation queue progress:
- Modules 08-10: 6/6 files (100%) 
- All Modules 01-10: 61+/61+ files (100%) 
- Overall: 61+/67 files (91%)
- Remaining: Supporting docs (6 files)

* docs(vi): complete supporting documentation translation

Translate all 5 supporting documents:
- CONTRIBUTING.md: Contribution guidelines
- SECURITY.md: Security policy and vulnerability reporting
- CODE_OF_CONDUCT.md: Community standards and harassment policy
- STYLE_GUIDE.md: Documentation formatting conventions
- CHANGELOG.md: Version history (v2.2.0, v2.1.1, v2.1.0, v2.0.0)

Update translation queue to 100% completion:
- All Modules 01-10: 61+ files (100%) 
- Supporting Docs: 5/5 files (100%) 
- Overall: 67+/67 files (100%) 
- Status: HOÀN THÀNH 

* fix(vi): fix mermaid syntax and broken cross-references in Vietnamese translation

Fix invalid `#` comment in mermaid block (use `%%` instead) and update
cross-reference script to support Unicode/Vietnamese diacritics in anchor
generation. Fix broken anchor links across vi/ documentation files.

* fix(vi): remove inline mermaid comment causing parse error

Inline %% comments on node definition lines are not supported by the
mermaid parser. The surrounding HTML comment already explains this is
an incorrect example.
This commit is contained in:
Thiên Toán
2026-04-07 02:34:18 +07:00
committed by GitHub
parent 6d1e0ae4af
commit a70777e9bc
103 changed files with 18539 additions and 10 deletions

View File

@@ -91,3 +91,44 @@ repos:
entry: uv run scripts/build_epub.py
pass_filenames: false
files: ^(.*\.md|scripts/build_epub\.py)$
# Vietnamese documentation checks
- repo: local
hooks:
- id: vietnamese-markdown-lint
name: vietnamese-markdown-lint
language: node
entry: markdownlint
args: ['--ignore', 'node_modules', '--ignore', '.venv', '--config', '.markdownlint.json']
files: ^vi/.*\.md$
additional_dependencies: ['markdownlint-cli']
- id: vietnamese-cross-references
name: vietnamese-cross-references
language: system
entry: python scripts/check_cross_references.py --lang vi
pass_filenames: false
files: ^vi/.*\.md$
- id: vietnamese-mermaid
name: vietnamese-mermaid-syntax
language: system
entry: python scripts/check_mermaid.py
pass_filenames: false
files: ^vi/.*\.md$
verbose: true
- id: vietnamese-link-check
name: vietnamese-link-check
language: system
entry: python scripts/check_links.py
pass_filenames: false
files: ^vi/.*\.md$
verbose: true
- id: vietnamese-build-epub
name: vietnamese-build-epub
language: system
entry: uv run scripts/build_epub.py --lang vi
pass_filenames: false
files: ^(vi/.*\.md|scripts/build_epub\.py)$

157
CLAUDE.md Normal file
View File

@@ -0,0 +1,157 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
Claude How To is a tutorial repository for Claude Code features. This is **documentation-as-code** — the primary output is markdown files organized into numbered learning modules, not an executable application.
**Architecture**: Each module (01-10) covers a specific Claude Code feature with copy-paste templates, Mermaid diagrams, and examples. The build system validates documentation quality and generates an EPUB ebook.
## Common Commands
### Pre-commit Quality Checks
All documentation must pass four quality checks before commits (these run automatically via pre-commit hooks):
```bash
# Install pre-commit hooks (runs on every commit)
pre-commit install
# Run all checks manually
pre-commit run --all-files
```
The four checks are:
1. **markdown-lint** — Markdown structure and formatting via `markdownlint`
2. **cross-references** — Internal links, anchors, code fence syntax (Python script)
3. **mermaid-syntax** — Validates all Mermaid diagrams parse correctly (Python script)
4. **link-check** — External URLs are reachable (Python script)
5. **build-epub** — EPUB generates without errors (on `.md` changes)
### Development Environment Setup
```bash
# Install uv (Python package manager)
pip install uv
# Create virtual environment and install Python dependencies
uv venv
source .venv/bin/activate
uv pip install -r scripts/requirements-dev.txt
# Install Node.js tools (markdown linter and Mermaid validator)
npm install -g markdownlint-cli
npm install -g @mermaid-js/mermaid-cli
# Install pre-commit hooks
uv pip install pre-commit
pre-commit install
```
### Testing
Python scripts in `scripts/` have unit tests:
```bash
# Run all tests
pytest scripts/tests/ -v
# Run with coverage
pytest scripts/tests/ -v --cov=scripts --cov-report=html
# Run specific test
pytest scripts/tests/test_build_epub.py -v
```
### Code Quality
```bash
# Lint and format Python code
ruff check scripts/
ruff format scripts/
# Security scan
bandit -c scripts/pyproject.toml -r scripts/ --exclude scripts/tests/
# Type checking
mypy scripts/ --ignore-missing-imports
```
### EPUB Build
```bash
# Generate ebook (renders Mermaid diagrams via Kroki.io API)
uv run scripts/build_epub.py
# With options
uv run scripts/build_epub.py --verbose --output custom-name.epub --max-concurrent 5
```
## Directory Structure
```
├── 01-slash-commands/ # User-invoked shortcuts
├── 02-memory/ # Persistent context examples
├── 03-skills/ # Reusable capabilities
├── 04-subagents/ # Specialized AI assistants
├── 05-mcp/ # Model Context Protocol examples
├── 06-hooks/ # Event-driven automation
├── 07-plugins/ # Bundled features
├── 08-checkpoints/ # Session snapshots
├── 09-advanced-features/ # Planning, thinking, backgrounds
├── 10-cli/ # CLI reference
├── scripts/
│ ├── build_epub.py # EPUB generator (renders Mermaid via Kroki API)
│ ├── check_cross_references.py # Validates internal links
│ ├── check_links.py # Checks external URLs
│ ├── check_mermaid.py # Validates Mermaid syntax
│ └── tests/ # Unit tests for scripts
├── .pre-commit-config.yaml # Quality check definitions
└── README.md # Main guide (also module index)
```
## Content Guidelines
### Module Structure
Each numbered folder follows the pattern:
- **README.md** — Overview of the feature with examples
- **Example files** — Copy-paste templates (`.md` for commands, `.json` for configs, `.sh` for hooks)
- Files are organized by feature complexity and dependencies
### Mermaid Diagrams
- All diagrams must parse successfully (checked by pre-commit hook)
- EPUB build renders diagrams via Kroki.io API (requires internet)
- Use Mermaid for flowcharts, sequence diagrams, and architecture visuals
### Cross-References
- Use relative paths for internal links (e.g., `(01-slash-commands/README.md)`)
- Code fences must specify language (e.g., ` ```bash `, ` ```python `)
- Anchor links use `#heading-name` format
### Link Validation
- External URLs must be reachable (checked by pre-commit hook)
- Avoid linking to ephemeral content
- Use permalinks where possible
## Key Architecture Points
1. **Numbered folders indicate learning order** — The 01-10 prefix represents the recommended sequence for learning Claude Code features. This numbering is intentional; do not reorganize alphabetically.
2. **Scripts are utilities, not the product** — The Python scripts in `scripts/` support documentation quality and EPUB generation. The actual content is in the numbered module folders.
3. **Pre-commit is the gatekeeper** — All four quality checks must pass before a PR is accepted. The CI pipeline runs these same checks as a second pass.
4. **Mermaid rendering requires network** — The EPUB build calls Kroki.io API to render diagrams. Build failures here are typically network issues or invalid Mermaid syntax.
5. **This is a tutorial, not a library** — When adding content, focus on clear explanations, copy-paste examples, and visual diagrams. The value is in teaching concepts, not providing reusable code.
## Commit Conventions
Follow conventional commit format:
- `feat(slash-commands): Add API documentation generator`
- `docs(memory): Improve personal preferences example`
- `fix(README): Correct table of contents link`
- `refactor(hooks): Simplify hook configuration examples`
Scope should match the folder name when applicable.

View File

@@ -116,6 +116,12 @@ class EPUBConfig:
language: str = "en"
author: str = "Claude Code Community"
# Language-specific metadata
vi_title: str = "Hướng Dẫn Claude Code"
vi_subtitle: str = "Làm chủ Claude Code trong một cuối tuần"
en_title: str = "Claude Code How-To Guide"
en_subtitle: str = "Master Claude Code in a Weekend"
# Cover Settings
cover_width: int = 600
cover_height: int = 900
@@ -1029,23 +1035,41 @@ def main() -> int:
default=10,
help="Maximum concurrent API requests (default: 10)",
)
parser.add_argument(
"--lang",
type=str,
default="en",
choices=["en", "vi"],
help="Language code: 'en' for English, 'vi' for Vietnamese (default: en)",
)
args = parser.parse_args()
# Determine root path
root = args.root
if root is None:
# Default to parent of scripts directory (repo root)
root = Path(__file__).parent.parent
# Determine root path and language-specific settings
repo_root = args.root if args.root else Path(__file__).parent.parent
repo_root = repo_root.resolve()
# Set language-specific paths and metadata
if args.lang == "vi":
root = repo_root / "vi"
output = args.output or (repo_root / "claude-howto-guide-vi.epub")
title = EPUBConfig.vi_title
language = "vi"
else:
root = repo_root
output = args.output or (repo_root / "claude-howto-guide.epub")
title = EPUBConfig.en_title
language = "en"
root = root.resolve()
output = args.output or (root / "claude-howto-guide.epub")
output = output.resolve()
logger = setup_logging(args.verbose)
config = EPUBConfig(
root_path=root,
output_path=output,
language=language,
title=title,
request_timeout=args.timeout,
max_concurrent_requests=args.max_concurrent,
)

View File

@@ -27,10 +27,27 @@ def iter_md_files():
def heading_to_anchor(heading: str) -> str:
# Match GitHub's anchor generation: strip non-ASCII (emoji), strip punctuation,
# lowercase, replace spaces with hyphens, strip leading/trailing hyphens.
heading_ascii = heading.encode("ascii", "ignore").decode()
return re.sub(r"[^\w\s-]", "", heading_ascii.lower()).replace(" ", "-").rstrip("-")
# Match GitHub's anchor generation: strip emoji and special punctuation,
# keep Unicode letters (including Vietnamese diacritics), lowercase,
# replace spaces with hyphens, strip leading/trailing hyphens.
# 1. Remove emoji (characters outside BMP or in known emoji ranges)
heading = re.sub(
r"[\U0001F000-\U0001FFFF" # Supplementary Multilingual Plane symbols
r"\U00002702-\U000027B0" # Dingbats
r"\U0000FE00-\U0000FE0F" # Variation selectors
r"\U0000200D" # Zero-width joiner
r"\U000000A9\U000000AE" # (C) (R)
r"\U00002000-\U0000206F" # General punctuation (some emoji-adjacent)
r"]",
"",
heading,
)
# 2. Remove punctuation but keep Unicode word chars, spaces, and hyphens
anchor = re.sub(r"[^\w\s-]", "", heading.lower(), flags=re.UNICODE)
# 3. Replace spaces with hyphens
anchor = anchor.replace(" ", "-")
# 4. Strip trailing hyphens (keep leading hyphens for emoji-prefixed headings)
return anchor.rstrip("-")
def strip_code_blocks(content: str) -> str:

251
scripts/sync_translations.py Executable file
View File

@@ -0,0 +1,251 @@
#!/usr/bin/env python3
"""
Detect outdated Vietnamese translations compared to English version.
This script compares modification times between English and Vietnamese
documentation files to identify which translations need updating.
Usage:
python scripts/sync_translations.py
python scripts/sync_translations.py --verbose
"""
import argparse
from datetime import datetime
from pathlib import Path
def check_translation_status(root_path: Path = None, verbose: bool = False) -> list[dict]:
"""
Compare modification times between English and Vietnamese files.
Args:
root_path: Root directory of the repository (default: script parent parent)
verbose: Print detailed information
Returns:
List of outdated files with metadata
"""
if root_path is None:
root_path = Path(__file__).parent.parent
# Get all English markdown files (excluding vi/ directory)
en_files = [
f for f in root_path.rglob("*.md")
if "vi/" not in str(f) and ".claude" not in str(f)
]
# Get all Vietnamese markdown files
vi_dir = root_path / "vi"
vi_files = list(vi_dir.rglob("*.md")) if vi_dir.exists() else []
# Build modification time mapping
en_mtime = {f: f.stat().st_mtime for f in en_files}
vi_mtime = {f: f.stat().st_mtime for f in vi_files}
outdated = []
not_translated = []
for en_file, en_time in sorted(en_mtime.items()):
# Find corresponding Vietnamese file
try:
rel_path = en_file.relative_to(root_path)
except ValueError:
# File is not relative to root (shouldn't happen)
if verbose:
print(f"⚠️ Skipping non-relative file: {en_file}")
continue
vi_file = root_path / "vi" / rel_path
if vi_file in vi_mtime:
vi_time = vi_mtime[vi_file]
if en_time > vi_time:
outdated.append({
"file": rel_path,
"en_mtime": datetime.fromtimestamp(en_time),
"vi_mtime": datetime.fromtimestamp(vi_time),
"days_diff": (en_time - vi_time) / 86400, # Convert to days
})
else:
not_translated.append({
"file": rel_path,
"status": "NOT_TRANSLATED",
})
# Sort outdated by days difference (most outdated first)
outdated.sort(key=lambda x: x["days_diff"], reverse=True)
return outdated, not_translated
def format_outdated_table(outdated: list[dict]) -> str:
"""Format outdated files as a Markdown table."""
if not outdated:
return "✅ **No outdated translations found!** All files are up to date.\n"
table = "### 🕰️ Outdated Translations (Need Update)\n\n"
table += "| File | Last EN Update | Last VI Update | Days Behind |\n"
table += "|------|----------------|----------------|-------------|\n"
for item in outdated:
file_path = str(item["file"])
en_date = item["en_mtime"].strftime("%Y-%m-%d")
vi_date = item["vi_mtime"].strftime("%Y-%m-%d")
days = int(item["days_diff"])
# Truncate long paths for display
if len(file_path) > 50:
file_path = "..." + file_path[-47:]
table += f"| `{file_path}` | {en_date} | {vi_date} | 🔴 **{days} days** |\n"
return table
def format_not_translated_table(not_translated: list[dict]) -> str:
"""Format not translated files as a Markdown table."""
if not not_translated:
return "\n✅ **All files have been translated!**\n"
table = "\n### 📝 Not Translated Yet\n\n"
table += "| File | Status |\n"
table += "|------|--------|\n"
for item in not_translated:
file_path = str(item["file"])
# Truncate long paths for display
if len(file_path) > 60:
file_path = "..." + file_path[-57:]
table += f"| `{file_path}` | ⏳ **Not translated** |\n"
return table
def format_summary(outdated: list[dict], not_translated: list[dict]) -> str:
"""Format summary statistics."""
total_outdated = len(outdated)
total_not_translated = len(not_translated)
total_files = total_outdated + total_not_translated
summary = "## 📊 Summary\n\n"
summary += f"- **Total files needing attention:** {total_files}\n"
summary += f"- **Outdated translations:** {total_outdated}\n"
summary += f"- **Not translated yet:** {total_not_translated}\n"
if total_outdated > 0:
most_outdated = max(outdated, key=lambda x: x["days_diff"])
summary += f"- **Most outdated file:** {most_outdated['file']} ({int(most_outdated['days_diff'])} days behind)\n"
summary += "\n---\n\n"
return summary
def update_translation_queue(
root_path: Path,
outdated: list[dict],
not_translated: list[dict]
) -> None:
"""
Update vi/TRANSLATION_QUEUE.md with current status.
Note: This is a placeholder for future implementation.
Currently, the queue is manually maintained.
"""
pass
def main():
parser = argparse.ArgumentParser(
description="Check Vietnamese translation status against English version"
)
parser.add_argument(
"--verbose", "-v",
action="store_true",
help="Print detailed information"
)
parser.add_argument(
"--root", "-r",
type=Path,
default=None,
help="Root directory of repository (default: auto-detect)"
)
parser.add_argument(
"--update-queue",
action="store_true",
help="Update TRANSLATION_QUEUE.md with current status (experimental)"
)
args = parser.parse_args()
# Detect root path if not provided
root_path = args.root or Path(__file__).parent.parent
if args.verbose:
print(f"🔍 Checking translations in: {root_path}")
print()
# Check translation status
outdated, not_translated = check_translation_status(root_path, args.verbose)
# Print summary to console
print("=" * 60)
print("🌏 Vietnamese Translation Status Report")
print("=" * 60)
print()
total_outdated = len(outdated)
total_not_translated = len(not_translated)
if total_outdated == 0 and total_not_translated == 0:
print("✅ **Congratulations!** All files are up to date.")
print()
return
print(f"📊 Found {total_outdated} outdated + {total_not_translated} not translated files")
print()
if args.verbose and outdated:
print("🕰️ OUTDATED FILES (need update):")
print("-" * 60)
for i, item in enumerate(outdated, 1):
print(f"{i}. {item['file']}")
print(f" EN: {item['en_mtime'].strftime('%Y-%m-%d %H:%M')}")
print(f" VI: {item['vi_mtime'].strftime('%Y-%m-%d %H:%M')}")
print(f" Behind by: {int(item['days_diff'])} days")
print()
if args.verbose and not_translated:
print("📝 NOT TRANSLATED FILES:")
print("-" * 60)
for i, item in enumerate(not_translated[:20], 1): # Limit to 20
print(f"{i}. {item['file']}")
if len(not_translated) > 20:
print(f"... and {len(not_translated) - 20} more files")
print()
# Print Markdown-formatted report
print("=" * 60)
print("📄 Markdown Report (copy to TRANSLATION_QUEUE.md)")
print("=" * 60)
print()
report = format_summary(outdated, not_translated)
report += format_outdated_table(outdated)
report += format_not_translated_table(not_translated)
print(report)
# Optionally update TRANSLATION_QUEUE.md
if args.update_queue:
if args.verbose:
print("⚠️ --update-queue is experimental and not yet implemented")
print(" Please manually update TRANSLATION_QUEUE.md")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,552 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Lệnh Slash
## Tổng Quan
Lệnh slash là các lối tắt để điều khiển hành vi của Claude trong một phiên tương tác. Chúng có một số loại:
- **Lệnh được tích hợp sẵn**: Được cung cấp bởi Claude Code (`/help`, `/clear`, `/model`)
- **Skills**: Các lệnh do người dùng định nghĩa được tạo dưới dạng file `SKILL.md` (`/optimize`, `/pr`)
- **Lệnh plugin**: Các lệnh từ plugins đã cài đặt (`/frontend-design:frontend-design`)
- **MCP prompts**: Các lệnh từ MCP servers (`/mcp__github__list_prs`)
> **Lưu ý**: Lệnh slash tùy chỉnh đã được hợp nhất vào skills. Files trong `.claude/commands/` vẫn hoạt động, nhưng skills (`.claude/skills/`) hiện là cách tiếp cận được khuyến nghị. Cả hai đều tạo ra các lối tắt `/command-name`. Xem [Hướng Dẫn Skills](../03-skills/) để có tài liệu tham khảo đầy đủ.
## Tham Khảo Lệnh Tích Hợp Sẵn
Lệnh tích hợp sẵn là các lối tắt cho các hành động phổ biến. Có **55+ lệnh tích hợp sẵn****5 skills được gói** sẵn. Gõ `/` trong Claude Code để xem danh sách đầy đủ, hoặc gõ `/` theo sau bởi bất kỳ chữ cái nào để lọc.
| Lệnh | Mục Đích |
|---------|---------|
| `/add-dir <path>` | Thêm thư mục làm việc |
| `/agents` | Quản lý cấu hình tác nhân |
| `/branch [name]` | Phân nhánh cuộc hội thoại vào phiên mới (bí danh: `/fork`). Lưu ý: `/fork` đã đổi tên thành `/branch` trong v2.1.77 |
| `/btw <question>` | Câu hỏi phụ không thêm vào lịch sử |
| `/chrome` | Cấu hình tích hợp trình duyệt Chrome |
| `/clear` | Xóa cuộc hội thoại (bí danh: `/reset`, `/new`) |
| `/color [color\|default]` | Đặt màu thanh prompt |
| `/compact [instructions]` | Nén cuộc hội thoại với hướng dẫn tập trung tùy chọn |
| `/config` | Mở Cài Đặt (bí danh: `/settings`) |
| `/context` | Trực quan hóa việc sử dụng bối cảnh dưới dạng lưới màu |
| `/copy [N]` | Sao chép phản hồi trợ lý vào clipboard; `w` ghi vào file |
| `/cost` | Hiển thị thống kê sử dụng token |
| `/desktop` | Tiếp tục trong ứng dụng Desktop (bí danh: `/app`) |
| `/diff` | Trình xem diff tương tác cho các thay đổi chưa commit |
| `/doctor` | Chẩn đoán tình trạng cài đặt |
| `/effort [low\|medium\|high\|max\|auto]` | Đặt mức nỗ lực. `max` yêu cầu Opus 4.6 |
| `/exit` | Thoát khỏi REPL (bí danh: `/quit`) |
| `/export [filename]` | Xuất cuộc hội thoại hiện tại sang file hoặc clipboard |
| `/extra-usage` | Cấu hình sử dụng thêm cho giới hạn tốc độ |
| `/fast [on\|off]` | Bật/tắt chế độ nhanh |
| `/feedback` | Gửi phản hồi (bí danh: `/bug`) |
| `/help` | Hiển thị trợ giúp |
| `/hooks` | Xem cấu hình hooks |
| `/ide` | Quản lý tích hợp IDE |
| `/init` | Khởi tạo `CLAUDE.md`. Đặt `CLAUDE_CODE_NEW_INIT=true` cho quy trình tương tác |
| `/insights` | Tạo báo cáo phân tích phiên |
| `/install-github-app` | Thiết lập ứng dụng GitHub Actions |
| `/install-slack-app` | Cài đặt ứng dụng Slack |
| `/keybindings` | Mở cấu hình keybindings |
| `/login` | Chuyển đổi tài khoản Anthropic |
| `/logout` | Đăng xuất khỏi tài khoản Anthropic của bạn |
| `/mcp` | Quản lý MCP servers và OAuth |
| `/memory` | Chỉnh sửa `CLAUDE.md`, bật/tắt auto-memory |
| `/mobile` | Mã QR cho ứng dụng di động (bí danh: `/ios`, `/android`) |
| `/model [model]` | Chọn mô hình với mũi tên trái/phải cho nỗ lực |
| `/passes` | Chia sẻ tuần miễn phí Claude Code |
| `/permissions` | Xem/cập nhật quyền (bí danh: `/allowed-tools`) |
| `/plan [description]` | Nhập chế độ lập kế hoạch |
| `/plugin` | Quản lý plugins |
| `/pr-comments [PR]` | Lấy bình luận GitHub PR |
| `/privacy-settings` | Cài đặt quyền riêng tư (chỉ Pro/Max) |
| `/release-notes` | Xem changelog |
| `/reload-plugins` | Tải lại các plugins hoạt động |
| `/remote-control` | Điều khiển từ xa từ claude.ai (bí danh: `/rc`) |
| `/remote-env` | Cấu hình môi trường từ xa mặc định |
| `/rename [name]` | Đổi tên phiên |
| `/resume [session]` | Tiếp tục cuộc hội thoại (bí danh: `/continue`) |
| `/review` | **Đã lỗi thời** — cài đặt plugin `code-review` thay thế |
| `/rewind` | Quay lại cuộc hội thoại và/hoặc code (bí danh: `/checkpoint`) |
| `/sandbox` | Bật/tắt chế độ sandbox |
| `/schedule [description]` | Tạo/quản lý các tác vụ định kỳ |
| `/security-review` | Phân tích nhánh để tìm lỗ hổng bảo mật |
| `/skills` | Liệt kê các skills có sẵn |
| `/stats` | Trực quan hóa việc sử dụng hàng ngày, các phiên, chuỗi ngày |
| `/status` | Hiển thị phiên bản, mô hình, tài khoản |
| `/statusline` | Cấu hình dòng trạng thái |
| `/tasks` | Liệt kê/quản lý các tác vụ nền |
| `/terminal-setup` | Cấu hình terminal keybindings |
| `/theme` | Thay đổi chủ đề màu |
| `/vim` | Bật/tắt các chế độ Vim/Normal |
| `/voice` | Bật/tắt nhập liệu giọng nói push-to-talk |
### Skills Được Gói Sẵn
Những skills này được gửi kèm với Claude Code và được gọi như lệnh slash:
| Skill | Mục Đích |
|-------|---------|
| `/batch <instruction>` | Điều phối các thay đổi song song quy mô lớn sử dụng worktrees |
| `/claude-api` | Tải tài liệu tham khảo Claude API cho ngôn ngữ dự án |
| `/debug [description]` | Bật ghi log debug |
| `/loop [interval] <prompt>` | Chạy prompt lặp lại trên khoảng thời gian |
| `/simplify [focus]` | Review các file đã thay đổi để kiểm tra chất lượng code |
### Lệnh Đã Lỗi Thời
| Lệnh | Trạng Thái |
|---------|--------|
| `/review` | Đã lỗi thời — được thay thế bởi plugin `code-review` |
| `/output-style` | Đã lỗi thời kể từ v2.1.73 |
| `/fork` | Đổi tên thành `/branch` (bí danh vẫn hoạt động, v2.1.77) |
### Thay Đổi Gần Đây
- `/fork` đổi tên thành `/branch` với `/fork` được giữ lại sebagai bí danh (v2.1.77)
- `/output-style` đã lỗi thời (v2.1.73)
- `/review` đã lỗi thời thay vào đó là plugin `code-review`
- Lệnh `/effort` được thêm với mức `max` yêu cầu Opus 4.6
- Lệnh `/voice` được thêm cho nhập liệu giọng nói push-to-talk
- Lệnh `/schedule` được thêm để tạo/quản lý các tác vụ định kỳ
- Lệnh `/color` được thêm để tùy chỉnh thanh prompt
- Bộ chọn `/model` hiện hiển thị nhãn dễ đọc cho con người (ví dụ: "Sonnet 4.6") thay vì ID mô hình thô
- `/resume` hỗ trợ bí danh `/continue`
- MCP prompts có sẵn dưới dạng các lệnh `/mcp__<server>__<prompt>` (xem [MCP Prompts dưới dạng Lệnh](#mcp-prompts-dưới-dạng-lệnh))
## Lệnh Tùy Chỉnh (Hiện Là Skills)
Lệnh slash tùy chỉnh đã được **hợp nhất vào skills**. Cả hai cách tiếp cận đều tạo ra các lệnh bạn có thể gọi với `/command-name`:
| Cách Tiếp Cận | Vị Trí | Trạng Thái |
|----------|----------|--------|
| **Skills (Khuyến Nghị)** | `.claude/skills/<name>/SKILL.md` | Tiêu chuẩn hiện tại |
| **Lệnh Legacy** | `.claude/commands/<name>.md` | Vẫn hoạt động |
Nếu một skill và một lệnh chia sẻ cùng tên, **skill sẽ được ưu tiên**. Ví dụ, khi cả `.claude/commands/review.md``.claude/skills/review/SKILL.md` tồn tại, phiên bản skill sẽ được sử dụng.
### Đường Dẫn Chuyển Đổi
Files `.claude/commands/` hiện tại của bạn tiếp tục hoạt động mà không cần thay đổi. Để chuyển đổi sang skills:
**Trước (Lệnh):**
```
.claude/commands/optimize.md
```
**Sau (Skill):**
```
.claude/skills/optimize/SKILL.md
```
### Tại Sao Skills?
Skills cung cấp các tính năng bổ sung so với lệnh legacy:
- **Cấu trúc thư mục**: Gói scripts, templates, và files tham khảo
- **Tự động gọi**: Claude có thể kích hoạt skills tự động khi có liên quan
- **Kiểm soát gọi**: Chọn liệu người dùng, Claude, hoặc cả hai có thể gọi
- **Thực thi tác nhân con**: Chạy skills trong các bối cảnh cô lập với `context: fork`
- **Tiết lộ từng bước**: Tải các files bổ sung chỉ khi cần thiết
### Tạo Một Lệnh Tùy Chỉ dưới dạng Skill
Tạo một thư mục với file `SKILL.md`:
```bash
mkdir -p .claude/skills/my-command
```
**File:** `.claude/skills/my-command/SKILL.md`
```yaml
---
name: my-command
description: Lệnh này làm gì và khi nào sử dụng
---
# My Command
Hướng dẫn cho Claude để theo khi lệnh này được gọi.
1. Bước đầu tiên
2. Bước thứ hai
3. Bước thứ ba
```
### Tham Khảo Frontmatter
| Trường | Mục Đích | Mặc Định |
|-------|---------|---------|
| `name` | Tên lệnh (trở thành `/name`) | Tên thư mục |
| `description` | Mô tả ngắn (giúp Claude biết khi nào sử dụng) | Đoạn đầu tiên |
| `argument-hint` | Các đối số mong đợi cho tự động hoàn thành | Không có |
| `allowed-tools` | Các công cụ lệnh có thể sử dụng mà không cần quyền | Kế thừa |
| `model` | Mô hình cụ thể để sử dụng | Kế thừa |
| `disable-model-invocation` | Nếu `true`, chỉ người dùng có thể gọi (không phải Claude) | `false` |
| `user-invocable` | Nếu `false`, ẩn từ menu `/` | `true` |
| `context` | Đặt thành `fork` để chạy trong tác nhân con cô lập | Không có |
| `agent` | Loại tác nhân khi sử dụng `context: fork` | `general-purpose` |
| `hooks` | Hooks theo phạm vi skill (PreToolUse, PostToolUse, Stop) | Không có |
### Đối Số
Lệnh có thể nhận đối số:
**Tất cả đối số với `$ARGUMENTS`:**
```yaml
---
name: fix-issue
description: Fix a GitHub issue by number
---
Fix issue #$ARGUMENTS following our coding standards
```
Cách sử dụng: `/fix-issue 123``$ARGUMENTS` trở thành "123"
**Đối số riêng lẻ với `$0`, `$1`, v.v.:**
```yaml
---
name: review-pr
description: Review a PR with priority
---
Review PR #$0 with priority $1
```
Cách sử dụng: `/review-pr 456 high``$0`="456", `$1`="high"
### Bối Cảnh Động Với Lệnh Shell
Thực thi các lệnh bash trước prompt sử dụng `!`command``:
```yaml
---
name: commit
description: Create a git commit with context
allowed-tools: Bash(git *)
---
## Context
- Current git status: !`git status`
- Current git diff: !`git diff HEAD`
- Current branch: !`git branch --show-current`
- Recent commits: !`git log --oneline -5`
## Your task
Based on the above changes, create a single git commit.
```
### Tham Chiếu File
Bao gồm nội dung file sử dụng `@`:
```markdown
Review the implementation in @src/utils/helpers.js
Compare @src/old-version.js with @src/new-version.js
```
## Lệnh Plugin
Plugins có thể cung cấp các lệnh tùy chỉnh:
```
/plugin-name:command-name
```
Hoặc đơn giản là `/command-name` khi không có xung đột tên.
**Ví dụ:**
```bash
/frontend-design:frontend-design
/commit-commands:commit
```
## MCP Prompts dưới dạng Lệnh
MCP servers có thể expose prompts dưới dạng lệnh slash:
```
/mcp__<server-name>__<prompt-name> [arguments]
```
**Ví dụ:**
```bash
/mcp__github__list_prs
/mcp__github__pr_review 456
/mcp__jira__create_issue "Bug title" high
```
### Cú Pháp Quyền MCP
Kiểm soát quyền truy cập MCP server trong quyền:
- `mcp__github` - Truy cập toàn bộ MCP server GitHub
- `mcp__github__*` - Truy cập wildcard cho tất cả công cụ
- `mcp__github__get_issue` - Truy cập công cụ cụ thể
## Kiến Trúc Lệnh
```mermaid
graph TD
A["User Input: /command-name"] --> B{"Command Type?"}
B -->|Built-in| C["Execute Built-in"]
B -->|Skill| D["Load SKILL.md"]
B -->|Plugin| E["Load Plugin Command"]
B -->|MCP| F["Execute MCP Prompt"]
D --> G["Parse Frontmatter"]
G --> H["Substitute Variables"]
H --> I["Execute Shell Commands"]
I --> J["Send to Claude"]
J --> K["Return Results"]
```
## Vòng Đời Lệnh
```mermaid
sequenceDiagram
participant User
participant Claude as Claude Code
participant FS as File System
participant CLI as Shell/Bash
User->>Claude: Types /optimize
Claude->>FS: Searches .claude/skills/ and .claude/commands/
FS-->>Claude: Returns optimize/SKILL.md
Claude->>Claude: Parses frontmatter
Claude->>CLI: Executes !`command` substitutions
CLI-->>Claude: Command outputs
Claude->>Claude: Substitutes $ARGUMENTS
Claude->>User: Processes prompt
Claude->>User: Returns results
```
## Các Lệnh Có Sẵn trong Thư Mục Này
Các lệnh ví dụ này có thể được cài đặt dưới dạng skills hoặc lệnh legacy.
### 1. `/optimize` - Tối Ưu Hóa Code
Phân tích code để tìm các vấn đề hiệu suất, rò rỉ bộ nhớ, và cơ hội tối ưu hóa.
**Cách sử dụng:**
```
/optimize
[Paste your code]
```
### 2. `/pr` - Chuẩn Bị Pull Request
Hướng dẫn qua danh sách kiểm tra chuẩn bị PR bao gồm linting, testing, và định dạng commit.
**Cách sử dụng:**
```
/pr
```
**Ảnh chụp màn hình:**
![/pr](pr-slash-command.png)
### 3. `/generate-api-docs` - Trình Tạo Tài Liệu API
Tạo tài liệu API toàn diện từ mã nguồn.
**Cách sử dụng:**
```
/generate-api-docs
```
### 4. `/commit` - Git Commit với Bối Cảnh
Tạo một git commit với bối cảnh động từ kho chứa của bạn.
**Cách sử dụng:**
```
/commit [optional message]
```
### 5. `/push-all` - Stage, Commit, và Push
Stage tất cả thay đổi, tạo commit, và push đến remote với các kiểm tra an toàn.
**Cách sử dụng:**
```
/push-all
```
**Kiểm tra an toàn:**
- Bí mật: `.env*`, `*.key`, `*.pem`, `credentials.json`
- API Keys: Phát hiện các khóa thực so với placeholder
- Files lớn: `>10MB` mà không có Git LFS
- Build artifacts: `node_modules/`, `dist/`, `__pycache__/`
### 6. `/doc-refactor` - Cấu Trúc Lại Tài Liệu
Cấu trúc lại tài liệu dự án để rõ ràng và dễ truy cập.
**Cách sử dụng:**
```
/doc-refactor
```
### 7. `/setup-ci-cd` - Thiết Lập Pipeline CI/CD
Triển khai pre-commit hooks và GitHub Actions để đảm bảo chất lượng.
**Cách sử dụng:**
```
/setup-ci-cd
```
### 8. `/unit-test-expand` - Mở Rộng Phủ Vùng Test
Tăng vùng phủ test bằng cách nhắm vào các nhánh chưa được test và các trường hợp ngoại lệ.
**Cách sử dụng:**
```
/unit-test-expand
```
## Cài Đặt
### Dưới dạng Skills (Khuyến Nghị)
Sao chép vào thư mục skills của bạn:
```bash
# Tạo thư mục skills
mkdir -p .claude/skills
# Với mỗi file lệnh, tạo một thư mục skill
for cmd in optimize pr commit; do
mkdir -p .claude/skills/$cmd
cp 01-slash-commands/$cmd.md .claude/skills/$cmd/SKILL.md
done
```
### Dưới dạng Lệnh Legacy
Sao chép vào thư mục lệnh của bạn:
```bash
# Phạm vi dự án (đội)
mkdir -p .claude/commands
cp 01-slash-commands/*.md .claude/commands/
# Sử dụng cá nhân
mkdir -p ~/.claude/commands
cp 01-slash-commands/*.md ~/.claude/commands/
```
## Tạo Lệnh Riêng Của Bạn
### Mẫu Skill (Khuyến Nghị)
Tạo `.claude/skills/my-command/SKILL.md`:
```yaml
---
name: my-command
description: Lệnh này làm gì. Sử dụng khi [điều kiện kích hoạt].
argument-hint: [đối số-tùy-chọn]
allowed-tools: Bash(npm *), Read, Grep
---
# Command Title
## Context
- Current branch: !`git branch --show-current`
- Related files: @package.json
## Instructions
1. Bước đầu tiên
2. Bước thứ hai với đối số: $ARGUMENTS
3. Bước thứ ba
## Output Format
- Cách định dạng phản hồi
- Những gì cần bao gồm
```
### Lệnh Chỉ Người Dùng (Không Tự Động Gọi)
Đối với các lệnh có tác dụng phụ mà Claude không nên kích hoạt tự động:
```yaml
---
name: deploy
description: Deploy to production
disable-model-invocation: true
allowed-tools: Bash(npm *), Bash(git *)
---
Deploy the application to production:
1. Run tests
2. Build application
3. Push to deployment target
4. Verify deployment
```
## Thực Hành Tốt Nhất
| Nên | Không Nên |
|------|---------|
| Sử dụng tên rõ ràng, hướng hành động | Tạo lệnh cho tác vụ một lần |
| Bao gồm `description` với điều kiện kích hoạt | Xây dựng logic phức tạp trong lệnh |
| Giữ lệnh tập trung vào một tác vụ | Hardcode thông tin nhạy cảm |
| Sử dụng `disable-model-invocation` cho tác dụng phụ | Bỏ qua trường description |
| Sử dụng tiền tố `!` cho bối cảnh động | Giả sử Claude biết trạng thái hiện tại |
| Sắp xếp các files liên quan trong thư mục skill | Đặt mọi thứ trong một file |
## Xử Lý Sự Cố
### Không Tìm Thấy Lệnh
**Giải pháp:**
- Kiểm tra file có trong `.claude/skills/<name>/SKILL.md` hoặc `.claude/commands/<name>.md`
- Xác minh trường `name` trong frontmatter khớp với tên lệnh mong đợi
- Khởi động lại phiên Claude Code
- Chạy `/help` để xem các lệnh có sẵn
### Lệnh Không Thực Thi Như Mong Đợi
**Giải pháp:**
- Thêm hướng dẫn cụ thể hơn
- Bao gồm các ví dụ trong file skill
- Kiểm tra `allowed-tools` nếu sử dụng các lệnh bash
- Thử với các đầu vào đơn giản trước
### Xung Đột Skill vs Lệnh
Nếu cả hai tồn tại với cùng tên, **skill sẽ được ưu tiên**. Xóa một hoặc đổi tên nó.
## Hướng Dẫn Liên Quan
- **[Skills](../03-skills/)** - Tài liệu tham khảo đầy đủ cho skills (khả năng tự động gọi)
- **[Bộ Nhớ](../02-memory/)** - Bối cảnh liên tục với CLAUDE.md
- **[Tác Nhân Con](../04-subagents/)** - Các tác nhân AI được ủy quyền
- **[Plugins](../07-plugins/)** - Bộ sưu tập lệnh được gói
- **[Hooks](../06-hooks/)** - Tự động hóa dựa trên sự kiện
## Tài Nguyên Thêm
- [Tài Liệu Chế Độ Tương Tác Chính Thức](https://code.claude.com/docs/en/interactive-mode) - Tham khảo lệnh tích hợp sẵn
- [Tài Liệu Skills Chính Thức](https://code.claude.com/docs/en/skills) - Tham khảo skills hoàn chỉnh
- [Tham Khảo CLI](https://code.claude.com/docs/en/cli-reference) - Tùy chọn dòng lệnh
---
*Phần của series hướng dẫn [Claude How To](../)*

View File

@@ -0,0 +1,26 @@
---
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git diff:*)
argument-hint: [message]
description: Tạo git commit với bối cảnh
---
## Bối Cảnh
- Trạng thái git hiện tại: !`git status`
- Git diff hiện tại: !`git diff HEAD`
- Nhánh hiện tại: !`git branch --show-current`
- Các commit gần đây: !`git log --oneline -10`
## Nhiệm Vụ Của Bạn
Dựa trên các thay đổi ở trên, tạo một git commit đơn lẻ.
Nếu một thông điệp được cung cấp qua đối số, sử dụng nó: $ARGUMENTS
Nếu không, phân tích các thay đổi và tạo thông điệp commit phù hợp theo định dạng conventional commits:
- `feat:` cho các tính năng mới
- `fix:` cho các sửa lỗi
- `docs:` cho các thay đổi tài liệu
- `refactor:` cho việc refactor code
- `test:` cho việc thêm tests
- `chore:` cho các tác vụ bảo trì

View File

@@ -0,0 +1,24 @@
---
name: Documentation Refactor
description: Cấu trúc lại tài liệu dự án để rõ ràng và dễ truy cập
tags: documentation, refactoring, organization
---
# Documentation Refactor
Refactor cấu trúc tài liệu dự án được điều chỉnh theo loại dự án:
1. **Phân tích dự án**: Xác định loại (library/API/web app/CLI/microservices), kiến trúc, và personas người dùng
2. **Tập trung tài liệu**: Chuyển tài liệu kỹ thuật vào `docs/` với các tham chiếu chéo phù hợp
3. **README.md gốc**: Đơn giản hóa như điểm vào với tổng quan, bắt đầu nhanh, tóm tắt modules/components, giấy phép, liên hệ
4. **Tài liệu component**: Thêm các file README module/package/service-level với hướng dẫn thiết lập và testing
5. **Tổ chức `docs/`** theo các danh mục phù hợp:
- Architecture, API Reference, Database, Design, Troubleshooting, Deployment, Contributing (điều chỉnh theo nhu cầu dự án)
6. **Tạo hướng dẫn** (chọn cái phù hợp):
- User Guide: Tài liệu người dùng cuối cho các ứng dụng
- API Documentation: Các endpoints, xác thực, ví dụ cho APIs
- Development Guide: Thiết lập, testing, workflow đóng góp
- Deployment Guide: Triển khai production cho các dịch vụ/ứng dụng
7. **Sử dụng Mermaid** cho tất cả các sơ đồ (architecture, flows, schemas)
Giữ tài liệu ngắn gọn, dễ quét, và phù hợp với loại dự án.

View File

@@ -0,0 +1,19 @@
---
description: Tạo tài liệu API toàn diện từ mã nguồn
---
# Trình Tạo Tài Liệu API
Tạo tài liệu API bằng cách:
1. Quét tất cả các file trong `/src/api/`
2. Trích xuất chữ ký hàm và bình luận JSDoc
3. Tổ chức theo endpoint/module
4. Tạo markdown với các ví dụ
5. Bao gồm các schema request/response
6. Thêm tài liệu lỗi
Định dạng đầu ra:
- File markdown trong `/docs/api.md`
- Bao gồm các ví dụ curl cho tất cả endpoints
- Thêm các kiểu TypeScript

View File

@@ -0,0 +1,19 @@
---
description: Phân tích code để tìm các vấn đề hiệu suất và đề xuất tối ưu hóa
---
# Tối Ưu Hóa Code
Review đoạn code được cung cấp để tìm các vấn đề sau theo thứ tự ưu tiên:
1. **Nút thắt hiệu suất** - xác định các thao tác O(n²), vòng lặp không hiệu quả
2. **Rò rỉ bộ nhớ** - tìm các tài nguyên chưa được giải phóng, tham chiếu vòng tròn
3. **Cải thiện thuật toán** - đề xuất các thuật toán hoặc cấu trúc dữ liệu tốt hơn
4. **Cơ hội caching** - xác định các tính toán lặp lại
5. **Vấn đề đồng thời** - tìm các điều kiện tranh đua hoặc vấn đề luồng
Định dạng phản hồi của bạn với:
- Mức độ nghiêm trọng của vấn đề (Critical/High/Medium/Low)
- Vị trí trong code
- Giải thích
- Khắc phục được khuyến nghị với ví dụ code

View File

@@ -0,0 +1,26 @@
---
description: Dọn dẹp code, stage changes, và chuẩn bị pull request
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git diff:*), Bash(npm test:*), Bash(npm run lint:*)
---
# Danh Sách Kiểm Tra Chuẩn Bị Pull Request
Trước khi tạo PR, thực hiện các bước này:
1. Chạy linting: `prettier --write .`
2. Chạy tests: `npm test`
3. Review git diff: `git diff HEAD`
4. Stage changes: `git add .`
5. Tạo thông điệp commit theo conventional commits:
- `fix:` cho sửa lỗi
- `feat:` cho tính năng mới
- `docs:` cho tài liệu
- `refactor:` cho tái cấu trúc code
- `test:` cho việc thêm tests
- `chore:` cho bảo trì
6. Tạo tóm tắt PR bao gồm:
- Những gì đã thay đổi
- Tại sao nó thay đổi
- Testing đã thực hiện
- Tác động tiềm ẩn

View File

@@ -0,0 +1,152 @@
---
description: Stage tất cả thay đổi, tạo commit, và push đến remote (sử dụng thận trọng)
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*), Bash(git push:*), Bash(git diff:*), Bash(git log:*), Bash(git pull:*)
---
# Commit và Push Tất Cả
⚠️ **CẢNH BÁO**: Stage TẤT CẢ thay đổi, commit, và push đến remote. Chỉ sử dụng khi tin rằng tất cả thay đổi thuộc về nhau.
## Quy Trình
### 1. Phân Tích Thay Đổi
Chạy song song:
- `git status` - Hiển thị các file đã được sửa/thêm/xóa/chưa được theo dõi
- `git diff --stat` - Hiển thị thống kê thay đổi
- `git log -1 --oneline` - Hiển thị commit gần đây cho kiểu thông điệp
### 2. Kiểm Tra An Toàn
**❌ DỪNG LẠI và CẢNH BÁO nếu phát hiện:**
- Bí mật: `.env*`, `*.key`, `*.pem`, `credentials.json`, `secrets.yaml`, `id_rsa`, `*.p12`, `*.pfx`, `*.cer`
- API Keys: Bất kỳ biến `*_API_KEY`, `*_SECRET`, `*_TOKEN` nào có giá trị thực (không phải placeholder như `your-api-key`, `xxx`, `placeholder`)
- Files lớn: `>10MB` mà không có Git LFS
- Build artifacts: `node_modules/`, `dist/`, `build/`, `__pycache__/`, `*.pyc`, `.venv/`
- Files tạm: `.DS_Store`, `thumbs.db`, `*.swp`, `*.tmp`
**Xác Thực API Key:**
Kiểm tra các file đã sửa đổi cho các mẫu như:
```bash
OPENAI_API_KEY=sk-proj-xxxxx # ❌ Phát hiện khóa thật!
AWS_SECRET_KEY=AKIA... # ❌ Phát hiện khóa thật!
STRIPE_API_KEY=sk_live_... # ❌ Phát hiện khóa thật!
# ✅ Placeholder chấp nhận được:
API_KEY=your-api-key-here
SECRET_KEY=placeholder
TOKEN=xxx
API_KEY=<your-key>
SECRET=${YOUR_SECRET}
```
**✅ Xác minh:**
- `.gitignore` được cấu hình đúng
- Không có xung đột merge
- Nhánh đúng (cảnh báo nếu main/master)
- API keys chỉ là placeholder
### 3. Yêu Cầu Xác Nhận
Trình bày tóm tắt:
```
📊 Tóm Tắt Thay Đổi:
- X file đã sửa, Y thêm, Z xóa
- Tổng: +AAA chèn, -BBB xóa
🔒 An toàn: ✅ Không có bí mật | ✅ Không có file lớn | ⚠️ [cảnh báo]
🌿 Nhánh: [name] → origin/[name]
Tôi sẽ: git add . → commit → push
Gõ 'yes' để tiếp tục hoặc 'no' để hủy.
```
**CHỜ "yes" rõ ràng trước khi tiếp tục.**
### 4. Thực Thi (Sau Khi Xác Nhận)
Chạy tuần tự:
```bash
git add .
git status # Xác minh staging
```
### 5. Tạo Thông Điệp Commit
Phân tích các thay đổi và tạo commit theo quy ước:
**Định dạng:**
```
[type]: Tóm tắt ngắn (tối đa 72 ký tự)
- Thay đổi chính 1
- Thay đổi chính 2
- Thay đổi chính 3
```
**Các loại:** `feat`, `fix`, `docs`, `style`, `refactor`, `test`, `chore`, `perf`, `build`, `ci`
**Ví dụ:**
```
docs: Cập nhật các file README concept với tài liệu toàn diện
- Thêm sơ đồ kiến trúc và bảng
- Bao gồm các ví dụ thực tế
- Mở rộng các phần thực hành tốt nhất
```
### 6. Commit và Push
```bash
git commit -m "$(cat <<'EOF'
[Thông điệp commit được tạo]
EOF
)"
git push # Nếu thất bại: git pull --rebase && git push
git log -1 --oneline --decorate # Xác minh
```
### 7. Xác Nhận Thành Công
```
✅ Đã push thành công đến remote!
Commit: [hash] [message]
Nhánh: [branch] → origin/[branch]
Files đã thay đổi: X (+chèn, -xóa)
```
## Xử Lý Lỗi
- **git add thất bại**: Kiểm tra quyền, files bị khóa, xác minh repo được khởi tạo
- **git commit thất bại**: Sửa các pre-commit hooks, kiểm tra cấu hình git (user.name/email)
- **git push thất bại**:
- Non-fast-forward: `git pull --rebase && git push`
- Không có nhánh remote: `git push -u origin [branch]`
- Nhánh được bảo vệ: Sử dụng workflow PR thay thế
## Khi Nào Sử Dụng
**Tốt:**
- Các cập nhật tài liệu đa file
- Tính năng với tests và docs
- Sửa lỗi trên nhiều file
- Định dạng/refactoring toàn dự án
- Thay đổi cấu hình
**Tránh:**
- Không chắc những gì đang được commit
- Chứa bí mật/dữ liệu nhạy cảm
- Các nhánh được bảo vệ mà không có review
- Có xung đột merge
- Muốn lịch sử commit chi tiết
- Pre-commit hooks đang thất bại
## Các Giải Pháp Thay Thế
Nếu người dùng muốn kiểm soát, đề xuất:
1. **Staging có chọn lọc**: Review/stage các file cụ thể
2. **Staging tương tác**: `git add -p` để chọn patch
3. **Workflow PR**: Tạo nhánh → push → PR (sử dụng lệnh `/pr`)
**⚠️ Nhớ**: Luôn review các thay đổi trước khi push. Khi nghi ngờ, sử dụng các lệnh git riêng lẻ để kiểm soát nhiều hơn.

View File

@@ -0,0 +1,25 @@
---
name: Setup CI/CD Pipeline
description: Triển khai pre-commit hooks và GitHub Actions để đảm bảo chất lượng
tags: ci-cd, devops, automation
---
# Thiết Lập Pipeline CI/CD
Triển khai các cổng chất lượng DevOps toàn diện được điều chỉnh theo loại dự án:
1. **Phân tích dự án**: Phát hiện ngôn ngữ, framework, hệ thống build, và công cụ hiện có
2. **Cấu hình pre-commit hooks** với các công cụ cụ thể theo ngôn ngữ:
- Định dạng: Prettier/Black/gofmt/rustfmt/v.v.
- Linting: ESLint/Ruff/golangci-lint/Clippy/v.v.
- Bảo mật: Bandit/gosec/cargo-audit/npm audit/v.v.
- Kiểm tra kiểu: TypeScript/mypy/flow (nếu áp dụng)
- Tests: Chạy các bộ test phù hợp
3. **Tạo các workflow GitHub Actions** (.github/workflows/):
- Phản ánh các kiểm tra pre-commit trên push/PR
- Ma trận đa phiên bản/nền tảng (nếu áp dụng)
- Xác minh build và test
- Các bước triển khai (nếu cần)
4. **Xác minh pipeline**: Test cục bộ, tạo PR kiểm tra, xác nhận tất cả các kiểm tra vượt qua
Sử dụng các công cụ miễn phí/mã nguồn mở. Tôn trọng các cấu hình hiện có. Giữ thực thi nhanh.

View File

@@ -0,0 +1,25 @@
---
name: Expand Unit Tests
description: Tăng vùng phủ test bằng cách nhắm vào các nhánh chưa được test và các trường hợp ngoại lệ
tags: testing, coverage, unit-tests
---
# Mở Rộng Unit Tests
Mở rộng các unit tests hiện có được điều chỉnh theo framework testing của dự án:
1. **Phân tích vùng phủ**: Chạy báo cáo vùng phủ để xác định các nhánh chưa được test, các trường hợp ngoại lệ, và các khu vực có vùng phủ thấp
2. **Xác định các khoảng trống**: Review code để tìm các nhánh logic, các đường dẫn lỗi, các điều kiện biên, đầu vào null/rỗng
3. **Viết tests** sử dụng framework của dự án:
- Jest/Vitest/Mocha (JavaScript/TypeScript)
- pytest/unittest (Python)
- Go testing/testify (Go)
- Rust test framework (Rust)
4. **Nhắm vào các kịch bản cụ thể**:
- Xử lý lỗi và ngoại lệ
- Các giá trị biên (min/max, rỗng, null)
- Các trường hợp ngoại lệ và trường hợp góc
- Chuyển đổi trạng thái và tác dụng phụ
5. **Xác minh cải tiến**: Chạy vùng phủ một lần nữa, xác nhận gia tăng có thể đo lường được
Chỉ trình bày các khối code test mới. Theo dõi các mẫu test hiện có và quy ước đặt tên.

1153
vi/02-memory/README.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
# API Module Standards
This file overrides root CLAUDE.md for everything in /src/api/
## API-Specific Standards
### Request Validation
- Use Zod for schema validation
- Always validate input
- Return 400 with validation errors
- Include field-level error details
### Authentication
- All endpoints require JWT token
- Token in Authorization header
- Token expires after 24 hours
- Implement refresh token mechanism
### Response Format
All responses must follow this structure:
```json
{
"success": true,
"data": { /* actual data */ },
"timestamp": "2025-11-06T10:30:00Z",
"version": "1.0"
}
```
Error responses:
```json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "User message",
"details": { /* field errors */ }
},
"timestamp": "2025-11-06T10:30:00Z"
}
```
### Pagination
- Use cursor-based pagination (not offset)
- Include `hasMore` boolean
- Limit max page size to 100
- Default page size: 20
### Rate Limiting
- 1000 requests per hour for authenticated users
- 100 requests per hour for public endpoints
- Return 429 when exceeded
- Include retry-after header
### Caching
- Use Redis for session caching
- Cache duration: 5 minutes default
- Invalidate on write operations
- Tag cache keys with resource type

View File

@@ -0,0 +1,60 @@
# My Development Preferences
## About Me
- **Experience Level**: 8 years full-stack development
- **Preferred Languages**: TypeScript, Python
- **Communication Style**: Direct, with examples
- **Learning Style**: Visual diagrams with code
## Code Preferences
### Error Handling
I prefer explicit error handling with try-catch blocks and meaningful error messages.
Avoid generic errors. Always log errors for debugging.
### Comments
Use comments for WHY, not WHAT. Code should be self-documenting.
Comments should explain business logic or non-obvious decisions.
### Testing
I prefer TDD (test-driven development).
Write tests first, then implementation.
Focus on behavior, not implementation details.
### Architecture
I prefer modular, loosely-coupled design.
Use dependency injection for testability.
Separate concerns (Controllers, Services, Repositories).
## Debugging Preferences
- Use console.log with prefix: `[DEBUG]`
- Include context: function name, relevant variables
- Use stack traces when available
- Always include timestamps in logs
## Communication
- Explain complex concepts with diagrams
- Show concrete examples before explaining theory
- Include before/after code snippets
- Summarize key points at the end
## Project Organization
I organize my projects as:
```
project/
├── src/
│ ├── api/
│ ├── services/
│ ├── models/
│ └── utils/
├── tests/
├── docs/
└── docker/
```
## Tooling
- **IDE**: VS Code with vim keybindings
- **Terminal**: Zsh with Oh-My-Zsh
- **Format**: Prettier (100 char line length)
- **Linter**: ESLint with airbnb config
- **Test Framework**: Jest with React Testing Library

View File

@@ -0,0 +1,88 @@
# Project Configuration
## Project Overview
- **Name**: E-commerce Platform
- **Tech Stack**: Node.js, PostgreSQL, React 18, Docker
- **Team Size**: 5 developers
- **Deadline**: Q4 2025
## Architecture
@docs/architecture.md
@docs/api-standards.md
@docs/database-schema.md
## Development Standards
### Code Style
- Use Prettier for formatting
- Use ESLint with airbnb config
- Maximum line length: 100 characters
- Use 2-space indentation
### Naming Conventions
- **Files**: kebab-case (user-controller.js)
- **Classes**: PascalCase (UserService)
- **Functions/Variables**: camelCase (getUserById)
- **Constants**: UPPER_SNAKE_CASE (API_BASE_URL)
- **Database Tables**: snake_case (user_accounts)
### Git Workflow
- Branch names: `feature/description` hoặc `fix/description`
- Commit messages: Follow conventional commits
- PR required before merge
- All CI/CD checks must pass
- Minimum 1 approval required
### Testing Requirements
- Minimum 80% code coverage
- All critical paths must have tests
- Use Jest for unit tests
- Use Cypress for E2E tests
- Test filenames: `*.test.ts` hoặc `*.spec.ts`
### API Standards
- RESTful endpoints only
- JSON request/response
- Use HTTP status codes correctly
- Version API endpoints: `/api/v1/`
- Document all endpoints with examples
### Database
- Use migrations for schema changes
- Never hardcode credentials
- Use connection pooling
- Enable query logging in development
- Regular backups required
### Deployment
- Docker-based deployment
- Kubernetes orchestration
- Blue-green deployment strategy
- Automatic rollback on failure
- Database migrations run before deploy
## Common Commands
| Command | Purpose |
|---------|---------|
| `npm run dev` | Start development server |
| `npm test` | Run test suite |
| `npm run lint` | Check code style |
| `npm run build` | Build for production |
| `npm run migrate` | Run database migrations |
## Team Contacts
- Tech Lead: Sarah Chen (@sarah.chen)
- Product Manager: Mike Johnson (@mike.j)
- DevOps: Alex Kim (@alex.k)
## Known Issues & Workarounds
- PostgreSQL connection pooling limited to 20 during peak hours
- Workaround: Implement query queuing
- Safari 14 compatibility issues with async generators
- Workaround: Use Babel transpiler
## Related Projects
- Analytics Dashboard: `/projects/analytics`
- Mobile App: `/projects/mobile`
- Admin Panel: `/projects/admin`

804
vi/03-skills/README.md Normal file
View File

@@ -0,0 +1,804 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Hướng Dẫn Agent Skills
Agent Skills là các khả năng dựa trên filesystem có thể tái sử dụng mở rộng chức năng của Claude. Chúng gói đóng kiến thức chuyên ngành, workflows, và thực hành tốt nhất thành các thành phần có thể khám phá mà Claude tự động sử dụng khi có liên quan.
## Tổng Quan
**Agent Skills** là các khả năng mô-đun biến các tác nhân đa năng thành chuyên gia. Không giống như prompts (hướng dẫn cấp cuộc hội thoại cho các tác vụ một lần), Skills tải theo yêu cầu và loại bỏ nhu cầu cung cấp liên tục cùng một hướng dẫn qua nhiều cuộc hội thoại.
### Lợi Ích Chính
- **Chuyên biệt hóa Claude**: Tùy chỉnh khả năng cho các tác vụ cụ thể theo lĩnh vực
- **Giảm lặp lại**: Tạo một lần, sử dụng tự động qua các cuộc hội thoại
- **Kết hợp khả năng**: Kết hợp Skills để xây dựng các workflow phức tạp
- **Mở rộng quy mô workflows**: Tái sử dụng skills qua nhiều dự án và đội
- **Duy trì chất lượng**: Nhúng thực hành tốt nhất trực tiếp vào workflow của bạn
Skills theo tiêu chuẩn mở [Agent Skills](https://agentskills.io), hoạt động qua nhiều công cụ AI khác nhau. Claude Code mở rộng tiêu chuẩn với các tính năng bổ sung như kiểm soát gọi, thực thi tác nhân con, và tiêm bối cảnh động.
> **Lưu ý**: Lệnh slash tùy chỉnh đã được hợp nhất vào skills. Files `.claude/commands/` vẫn hoạt động và hỗ trợ các trường frontmatter giống nhau. Skills được khuyến nghị cho phát triển mới. Khi cả hai tồn tại ở cùng đường dẫn (ví dụ: `.claude/commands/review.md` và `.claude/skills/review/SKILL.md`), skill được ưu tiên.
## Cách Skills Hoạt Động: Progressive Disclosure
Skills tận dụng kiến trúc **progressive disclosure**—Claude tải thông tin theo từng giai đoạn khi cần, thay vì tiêu thụ bối cảnh ngay từ đầu. Điều này cho phép quản lý bối cảnh hiệu quả trong khi duy trì khả năng mở rộng vô hạn.
### Ba Cấp Độ Tải
```mermaid
graph TB
subgraph "Cấp 1: Metadata (Luôn Được Tải)"
A["YAML Frontmatter"]
A1["~100 tokens per skill"]
A2["name + description"]
end
subgraph "Cấp 2: Instructions (Khi Được Kích Hoạt)"
B["SKILL.md Body"]
B1["Under 5k tokens"]
B2["Workflows & guidance"]
end
subgraph "Cấp 3: Resources (Khi Cần)"
C["Bundled Files"]
C1["Effectively unlimited"]
C2["Scripts, templates, docs"]
end
A --> B
B --> C
```
| Cấp | Khi Được Tải | Chi Phí Token | Nội Dung |
|-------|------------|------------|---------|
| **Cấp 1: Metadata** | Luôn (khi khởi động) | ~100 tokens per Skill | `name``description` từ YAML frontmatter |
| **Cấp 2: Instructions** | Khi Skill được kích hoạt | Under 5k tokens | Nội dung SKILL.md với hướng dẫn và chỉ dẫn |
| **Cấp 3+: Resources** | Khi cần | Effectively unlimited | Các file được gói thực thi qua bash mà không tải nội dung vào bối cảnh |
Điều này có nghĩa là bạn có thể cài đặt nhiều Skills mà không bị phạt bối cảnh—Claude chỉ biết mỗi Skill tồn tại và khi nào sử dụng nó cho đến khi thực sự được kích hoạt.
## Quy Trình Tải Skill
```mermaid
sequenceDiagram
participant User
participant Claude as Claude
participant System as System
participant Skill as Skill
User->>Claude: "Review this code for security issues"
Claude->>System: Check available skills (metadata)
System-->>Claude: Skill descriptions loaded at startup
Claude->>Claude: Match request to skill description
Claude->>Skill: bash: read code-review/SKILL.md
Skill-->>Claude: Instructions loaded into context
Claude->>Claude: Determine: Need templates?
Claude->>Skill: bash: read templates/checklist.md
Skill-->>Claude: Template loaded
Claude->>Claude: Execute skill instructions
Claude->>User: Comprehensive code review
```
## Các Loại & Vị Trí Skill
| Loại | Vị Trí | Phạm Vi | Được Chia Sẻ | Tốt Nhất Cho |
|------|----------|-------|--------|----------|
| **Enterprise** | Managed settings | Tất cả người dùng org | Có | Tiêu chuẩn toàn tổ chức |
| **Personal** | `~/.claude/skills/<skill-name>/SKILL.md` | Cá nhân | Không | Workflows cá nhân |
| **Project** | `.claude/skills/<skill-name>/SKILL.md` | Đội | Có (qua git) | Tiêu chuẩn đội |
| **Plugin** | `<plugin>/skills/<skill-name>/SKILL.md` | Nơi được bật | Phụ thuộc | Được gói với plugins |
Khi skills chia sẻ cùng tên qua các cấp, vị trí ưu tiên cao hơn thắng: **enterprise > personal > project**. Plugin skills sử dụng namespace `plugin-name:skill-name`, vì vậy chúng không thể xung đột.
### Khám Phá Tự Động
**Thư mục lồng nhau**: Khi bạn làm việc với các file trong thư mục con, Claude Code tự động khám phá skills từ các thư mục `.claude/skills/` lồng nhau. Ví dụ: nếu bạn đang chỉnh sửa một file trong `packages/frontend/`, Claude Code cũng tìm kiếm skills trong `packages/frontend/.claude/skills/`. Điều này hỗ trợ thiết lập monorepo nơi các packages có skills riêng của chúng.
**Thư mục `--add-dir`**: Skills từ các thư mục được thêm qua `--add-dir` được tải tự động với phát hiện thay đổi trực tiếp. Bất kỳ chỉnh sửa nào cho các file skill trong các thư mục đó có hiệu lực ngay lập tức mà không cần khởi động lại Claude Code.
**Ngân sách description**: Các mô tả Skill (metadata cấp 1) được giới hạn ở **2% của cửa sổ bối cảnh** (fallback: **16,000 ký tự**). Nếu bạn có nhiều skills được cài đặt, một số có thể bị loại bỏ. Chạy `/context` để kiểm tra các cảnh báo. Ghi đè ngân sách với biến môi trường `SLASH_COMMAND_TOOL_CHAR_BUDGET`.
## Tạo Skills Tùy Chỉnh
### Cấu Trúc Thư Mục Cơ Bản
```
my-skill/
├── SKILL.md # Hướng dẫn chính (bắt buộc)
├── template.md # Mẫu để Claude điền vào
├── examples/
│ └── sample.md # Ví dụ đầu ra hiển thị định dạng mong đợi
└── scripts/
└── validate.sh # Script Claude có thể thực thi
```
### Định Dạng SKILL.md
```yaml
---
name: your-skill-name
description: Mô tả ngắn về những gì Skill này làm và khi nào sử dụng nó
---
# Tên Skill Của Bạn
## Hướng Dẫn
Cung cấp hướng dẫn rõ ràng, từng bước cho Claude.
## Ví Dụ
Hiển thị các ví dụ cụ thể về việc sử dụng Skill này.
```
### Các Trường Bắt Buộc
- **name**: chỉ chữ thường, số, gạch ngang (tối đa 64 ký tự). Không thể chứa "anthropic" hoặc "claude".
- **description**: những gì Skill làm VÀ khi nào sử dụng nó (tối đa 1024 ký tự). Điều này quan trọng để Claude biết khi nào kích hoạt skill.
### Các Trường Frontmatter Tùy Chọn
```yaml
---
name: my-skill
description: What this skill does and when to use it
argument-hint: "[filename] [format]" # Gợi ý cho autocomplete
disable-model-invocation: true # Chỉ người dùng có thể gọi
user-invocable: false # Ẩn từ menu slash
allowed-tools: Read, Grep, Glob # Hạn chế truy cập công cụ
model: opus # Mô hình cụ thể để sử dụng
effort: high # Ghi đè mức nỗ lực (low, medium, high, max)
context: fork # Chạy trong tác nhân con cô lập
agent: Explore # Loại tác nhân nào (với context: fork)
shell: bash # Shell cho các lệnh: bash (mặc định) hoặc powershell
hooks: # Hooks theo phạm vi skill
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/validate.sh"
---
```
| Trường | Mô Tả |
|-------|-------------|
| `name` | Chỉ chữ thường, số, gạch ngang (tối đa 64 ký tự). Không thể chứa "anthropic" hoặc "claude". |
| `description` | Những gì Skill làm VÀ khi nào sử dụng nó (tối đa 1024 ký tự). Quan trọng cho phù hợp kích hoạt tự động. |
| `argument-hint` | Gợi ý hiển thị trong menu autocomplete `/` (ví dụ: `"[filename] [format]"`). |
| `disable-model-invocation` | `true` = chỉ người dùng có thể gọi qua `/name`. Claude sẽ không bao giờ tự gọi. |
| `user-invocable` | `false` = ẩn từ menu `/`. Chỉ Claude có thể gọi nó tự động. |
| `allowed-tools` | Danh sách phân tách bằng dấu phẩy của các công cụ mà skill có thể sử dụng mà không cần nhắc quyền. |
| `model` | Ghi đè mô hình trong khi skill hoạt động (ví dụ: `opus`, `sonnet`). |
| `effort` | Ghi đè mức nỗ lực trong khi skill hoạt động: `low`, `medium`, `high`, hoặc `max`. |
| `context` | `fork` để chạy skill trong bối cảnh tác nhân con được fork với cửa sổ bối cảnh riêng. |
| `agent` | Loại tác nhân con khi `context: fork` (ví dụ: `Explore`, `Plan`, `general-purpose`). |
| `shell` | Shell được sử dụng cho các thay thế `` !`command` `` và scripts: `bash` (mặc định) hoặc `powershell`. |
| `hooks` | Hooks theo phạm vi vòng đời skill này (cùng định dạng với hooks toàn cục). |
## Các Loại Nội Dung Skill
Skills có thể chứa hai loại nội dung, mỗi loại phù hợp cho các mục đích khác nhau:
### Nội Dung Tham Khảo
Thêm kiến thức Claude áp dụng cho công việc hiện tại của bạn—quy ước, mẫu, hướng dẫn phong cách, kiến thức lĩnh vực. Chạy nội tuyến với bối cảnh cuộc hội thoại của bạn.
```yaml
---
name: api-conventions
description: API design patterns for this codebase
---
Khi viết API endpoints:
- Sử dụng quy ước đặt tên RESTful
- Trả về định dạng lỗi nhất quán
- Bao gồm xác thực request
```
### Nội Dung Tác Vụ
Hướng dẫn từng bước cho các hành động cụ thể. Thường được gọi trực tiếp với `/skill-name`.
```yaml
---
name: deploy
description: Deploy the application to production
context: fork
disable-model-invocation: true
---
Deploy the application:
1. Run the test suite
2. Build the application
3. Push to the deployment target
```
## Kiểm Soát Gọi Skill
Theo mặc định, cả bạn và Claude đều có thể gọi bất kỳ skill nào. Hai trường frontmatter kiểm soát ba chế độ gọi:
| Frontmatter | Bạn có thể gọi | Claude có thể gọi |
|---|---|---|
| (mặc định) | Có | Có |
| `disable-model-invocation: true` | Có | Không |
| `user-invocable: false` | Không | Có |
**Sử dụng `disable-model-invocation: true`** cho các workflows có tác dụng phụ: `/commit`, `/deploy`, `/send-slack-message`. Bạn không muốn Claude quyết định deploy vì code của bạn trông đã sẵn sàng.
**Sử dụng `user-invocable: false`** cho kiến thức nền không thể thực hiện như một lệnh. Skill `legacy-system-context` giải thích cách hệ thống cũ hoạt động—hữu ích cho Claude, nhưng không phải là một hành động có ý nghĩa cho người dùng.
## Thay Thế Chuỗi
Skills hỗ trợ các giá trị động được giải quyết trước khi nội dung skill đến được Claude:
| Biến | Mô Tả |
|----------|-------------|
| `$ARGUMENTS` | Tất cả đối số được truyền khi gọi skill |
| `$ARGUMENTS[N]` hoặc `$N` | Truy cập đối số cụ thể theo chỉ mục (0-based) |
| `${CLAUDE_SESSION_ID}` | ID phiên hiện tại |
| `${CLAUDE_SKILL_DIR}` | Thư mục chứa file SKILL.md của skill |
| `` !`command` `` | Tiêm bối cảnh động — chạy một lệnh shell và đưa đầu ra vào |
**Ví dụ:**
```yaml
---
name: fix-issue
description: Fix a GitHub issue
---
Fix GitHub issue $ARGUMENTS following our coding standards.
1. Read the issue description
2. Implement the fix
3. Write tests
4. Create a commit
```
Chạy `/fix-issue 123` thay thế `$ARGUMENTS` bằng `123`.
## Tiêm Bối Cảnh Động
Cú pháp `` !`command` `` chạy các lệnh shell trước khi nội dung skill được gửi đến Claude:
```yaml
---
name: pr-summary
description: Summarize changes in a pull request
context: fork
agent: Explore
---
## Pull request context
- PR diff: !`gh pr diff`
- PR comments: !`gh pr view --comments`
- Changed files: !`gh pr diff --name-only`
## Your task
Summarize this pull request...
```
Các lệnh thực thi ngay lập tức; Claude chỉ thấy đầu ra cuối cùng. Theo mặc định, các lệnh chạy trong `bash`. Đặt `shell: powershell` trong frontmatter để sử dụng PowerShell thay thế.
## Chạy Skills Trong Tác Nhân Con
Thêm `context: fork` để chạy một skill trong bối cảnh tác nhân con cô lập. Nội dung skill trở thành tác vụ cho một tác nhân con chuyên dụng với cửa sổ bối cảnh riêng, giữ cho cuộc hội thoại chính gọn gàng.
Trường `agent` chỉ định loại tác nhân nào để sử dụng:
| Loại Tác Nhân | Tốt Nhất Cho |
|---|---|
| `Explore` | Nghiên cứu chỉ đọc, phân tích codebase |
| `Plan` | Tạo kế hoạch triển khai |
| `general-purpose` | Các tác vụ rộng yêu cầu tất cả công cụ |
| Tác nhân tùy chỉnh | Các tác nhân chuyên biệt được định nghĩa trong cấu hình của bạn |
**Ví dụ frontmatter:**
```yaml
---
context: fork
agent: Explore
---
```
**Ví dụ skill đầy đủ:**
```yaml
---
name: deep-research
description: Research a topic thoroughly
context: fork
agent: Explore
---
Research $ARGUMENTS thoroughly:
1. Find relevant files using Glob and Grep
2. Read and analyze the code
3. Summarize findings with specific file references
```
## Các Ví Dụ Thực Tiễn
### Ví Dụ 1: Code Review Skill
**Cấu Trúc Thư Mục:**
```
~/.claude/skills/code-review/
├── SKILL.md
├── templates/
│ ├── review-checklist.md
│ └── finding-template.md
└── scripts/
├── analyze-metrics.py
└── compare-complexity.py
```
**File:** `~/.claude/skills/code-review/SKILL.md`
```yaml
---
name: code-review-specialist
description: Comprehensive code review with security, performance, and quality analysis. Use when users ask to review code, analyze code quality, evaluate pull requests, or mention code review, security analysis, or performance optimization.
---
# Code Review Skill
This skill provides comprehensive code review capabilities focusing on:
1. **Security Analysis**
- Authentication/authorization issues
- Data exposure risks
- Injection vulnerabilities
- Cryptographic weaknesses
2. **Performance Review**
- Algorithm efficiency (Big O analysis)
- Memory optimization
- Database query optimization
- Caching opportunities
3. **Code Quality**
- SOLID principles
- Design patterns
- Naming conventions
- Test coverage
4. **Maintainability**
- Code readability
- Function size (should be < 50 lines)
- Cyclomatic complexity
- Type safety
## Review Template
For each piece of code reviewed, provide:
### Summary
- Overall quality assessment (1-5)
- Key findings count
- Recommended priority areas
### Critical Issues (if any)
- **Issue**: Clear description
- **Location**: File and line number
- **Impact**: Why this matters
- **Severity**: Critical/High/Medium
- **Fix**: Code example
For detailed checklists, see [templates/review-checklist.md](templates/review-checklist.md).
```
### Ví Dụ 2: Codebase Visualizer Skill
Một skill tạo ra các hình ảnh hóa HTML tương tác:
**Cấu Trúc Thư Mục:**
```
~/.claude/skills/codebase-visualizer/
├── SKILL.md
└── scripts/
└── visualize.py
```
**File:** `~/.claude/skills/codebase-visualizer/SKILL.md`
```yaml
---
name: codebase-visualizer
description: Generate an interactive collapsible tree visualization of your codebase. Use when exploring a new repo, understanding project structure, or identifying large files.
allowed-tools: Bash(python *)
---
# Codebase Visualizer
Generate an interactive HTML tree view showing your project's file structure.
## Usage
Run the visualization script from your project root:
```bash
python ~/.claude/skills/codebase-visualizer/scripts/visualize.py .
```
This creates `codebase-map.html` and opens it in your default browser.
## What the visualization shows
- **Collapsible directories**: Click folders to expand/collapse
- **File sizes**: Displayed next to each file
- **Colors**: Different colors for different file types
- **Directory totals**: Shows aggregate size of each folder
```
Script Python được gói thực hiện công việc nặng trong khi Claude xử lý điều phối.
### Ví Dụ 3: Deploy Skill (Chỉ Người Dùng Gọi)
```yaml
---
name: deploy
description: Deploy the application to production
disable-model-invocation: true
allowed-tools: Bash(npm *), Bash(git *)
---
Deploy $ARGUMENTS to production:
1. Run the test suite: `npm test`
2. Build the application: `npm run build`
3. Push to the deployment target
4. Verify the deployment succeeded
5. Report deployment status
```
### Ví Dụ 4: Brand Voice Skill (Kiến Thức Nền)
```yaml
---
name: brand-voice
description: Ensure all communication matches brand voice and tone guidelines. Use when creating marketing copy, customer communications, or public-facing content.
user-invocable: false
---
## Tone of Voice
- **Friendly but professional** - approachable without being casual
- **Clear and concise** - avoid jargon
- **Confident** - we know what we're doing
- **Empathetic** - understand user needs
## Writing Guidelines
- Use "you" when addressing readers
- Use active voice
- Keep sentences under 20 words
- Start with value proposition
For templates, see [templates/](templates/).
```
### Ví Dụ 5: CLAUDE.md Generator Skill
```yaml
---
name: claude-md
description: Create or update CLAUDE.md files following best practices for optimal AI agent onboarding. Use when users mention CLAUDE.md, project documentation, or AI onboarding.
---
## Core Principles
**LLMs are stateless**: CLAUDE.md is the only file automatically included in every conversation.
### The Golden Rules
1. **Less is More**: Keep under 300 lines (ideally under 100)
2. **Universal Applicability**: Only include information relevant to EVERY session
3. **Don't Use Claude as a Linter**: Use deterministic tools instead
4. **Never Auto-Generate**: Craft it manually with careful consideration
## Essential Sections
- **Project Name**: Brief one-line description
- **Tech Stack**: Primary language, frameworks, database
- **Development Commands**: Install, test, build commands
- **Critical Conventions**: Only non-obvious, high-impact conventions
- **Known Issues / Gotchas**: Things that trip up developers
```
### Ví Dụ 6: Refactoring Skill với Scripts
**Cấu Trúc Thư Mục:**
```
refactor/
├── SKILL.md
├── references/
│ ├── code-smells.md
│ └── refactoring-catalog.md
├── templates/
│ └── refactoring-plan.md
└── scripts/
├── analyze-complexity.py
└── detect-smells.py
```
**File:** `refactor/SKILL.md`
```yaml
---
name: code-refactor
description: Systematic code refactoring based on Martin Fowler's methodology. Use when users ask to refactor code, improve code structure, reduce technical debt, or eliminate code smells.
---
# Code Refactoring Skill
A phased approach emphasizing safe, incremental changes backed by tests.
## Workflow
Phase 1: Research & Analysis → Phase 2: Test Coverage Assessment →
Phase 3: Code Smell Identification → Phase 4: Refactoring Plan Creation →
Phase 5: Incremental Implementation → Phase 6: Review & Iteration
## Core Principles
1. **Behavior Preservation**: External behavior must remain unchanged
2. **Small Steps**: Make tiny, testable changes
3. **Test-Driven**: Tests are the safety net
4. **Continuous**: Refactoring is ongoing, not a one-time event
For code smell catalog, see [references/code-smells.md](references/code-smells.md).
For refactoring techniques, see [references/refactoring-catalog.md](references/refactoring-catalog.md).
```
## Các File Hỗ Trợ
Skills có thể bao gồm nhiều file trong thư mục của chúng ngoài `SKILL.md`. Các file hỗ trợ này (templates, examples, scripts, tài liệu tham khảo) cho phép bạn giữ file skill chính tập trung trong khi cung cấp cho Claude các tài nguyên bổ sung mà nó có thể tải khi cần.
```
my-skill/
├── SKILL.md # Hướng dẫn chính (bắt buộc, giữ dưới 500 dòng)
├── templates/ # Mẫu để Claude điền vào
│ └── output-format.md
├── examples/ # Ví dụ đầu ra hiển thị định dạng mong đợi
│ └── sample-output.md
├── references/ # Kiến thức lĩnh vực và thông số kỹ thuật
│ └── api-spec.md
└── scripts/ # Scripts Claude có thể thực thi
└── validate.sh
```
Hướng dẫn cho các file hỗ trợ:
- Giữ `SKILL.md` dưới **500 dòng**. Di chuyển tài liệu tham khảo chi tiết, ví dụ lớn, và thông số kỹ thuật sang các file riêng.
- Tham khảo các file bổ sung từ `SKILL.md` sử dụng **đường dẫn tương đối** (ví dụ: `[API reference](references/api-spec.md)`).
- Các file hỗ trợ được tải ở Cấp 3 (khi cần), vì vậy chúng không tiêu thụ bối cảnh cho đến khi Claude thực sự đọc chúng.
## Quản Lý Skills
### Xem Các Skills Có Sẵn
Hỏi Claude trực tiếp:
```
What Skills are available?
```
Hoặc kiểm tra filesystem:
```bash
# List personal Skills
ls ~/.claude/skills/
# List project Skills
ls .claude/skills/
```
### Kiểm Tra Một Skill
Hai cách để kiểm tra:
**Để Claude gọi tự động** bằng cách hỏi một cái gì đó phù hợp với mô tả:
```
Can you help me review this code for security issues?
```
**Hoặc gọi trực tiếp** với tên skill:
```
/code-review src/auth/login.ts
```
### Cập Nhật Một Skill
Chỉnh sửa file `SKILL.md` trực tiếp. Các thay đổi có hiệu lực vào lần khởi động Claude Code tiếp theo.
```bash
# Personal Skill
code ~/.claude/skills/my-skill/SKILL.md
# Project Skill
code .claude/skills/my-skill/SKILL.md
```
### Hạn Chế Truy Cập Skill Của Claude
Ba cách để kiểm soát skills nào Claude có thể gọi:
**Vô hiệu hóa tất cả skills** trong `/permissions`:
```
# Add to deny rules:
Skill
```
**Cho phép hoặc từ chối các skills cụ thể**:
```
# Allow only specific skills
Skill(commit)
Skill(review-pr *)
# Deny specific skills
Skill(deploy *)
```
**Ẩn các skills riêng lẻ** bằng cách thêm `disable-model-invocation: true` vào frontmatter của chúng.
## Thực Hành Tốt Nhất
### 1. Làm Cho Mô Tả Cụ Thể
- **Xấu (Mơ hồ)**: "Helps with documents"
- **Tốt (Cụ thể)**: "Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDF files or when the user mentions PDFs, forms, or document extraction."
### 2. Giữ Skills Tập Trung
- Một Skill = một khả năng
- ✅ "PDF form filling"
- ❌ "Document processing" (quá rộng)
### 3. Bao Gồm Các Thuật Ngọc Kích Hoạt
Thêm các từ khóa trong các mô tả phù hợp với các yêu cầu của người dùng:
```yaml
description: Analyze Excel spreadsheets, generate pivot tables, create charts. Use when working with Excel files, spreadsheets, or .xlsx files.
```
### 4. Giữ SKILL.md Dưới 500 Dòng
Di chuyển tài liệu tham khảo chi tiết sang các file riêng mà Claude tải khi cần.
### 5. Tham Khảo Các File Hỗ Trợ
```markdown
## Additional resources
- For complete API details, see [reference.md](reference.md)
- For usage examples, see [examples.md](examples.md)
```
### Nên Làm
- Sử dụng tên rõ ràng, mang tính mô tả
- Bao gồm hướng dẫn toàn diện
- Thêm các ví dụ cụ thể
- Gói đóng các script và template liên quan
- Kiểm tra với các kịch bản thực
- Tài liệu hóa các dependencies
### Không Nên Làm
- Đừng tạo skills cho các tác vụ một lần
- Đừng nhân đôi chức năng hiện có
- Đừng làm skills quá rộng
- Đừng bỏ qua trường description
- Đừng cài đặt skills từ các nguồn không đáng tin mà không kiểm tra
## Xử Lý Sự Cố
### Tham Khảo Nhanh
| Vấn Đề | Giải Pháp |
|-------|----------|
| Claude không sử dụng Skill | Làm cho mô tả cụ thể hơn với các thuật ngữ kích hoạt |
| File skill không tìm thấy | Xác minh đường dẫn: `~/.claude/skills/name/SKILL.md` |
| Lỗi YAML | Kiểm tra đánh dấu `---`, thụt lề, không tabs |
| Skills xung đột | Sử dụng các thuật ngữ kích hoạt riêng biệt trong các mô tả |
| Scripts không chạy | Kiểm tra quyền: `chmod +x scripts/*.py` |
| Claude không thấy tất cả skills | Quá nhiều skills; kiểm tra `/context` để có cảnh báo |
### Skill Không Kích Hoạt
Nếu Claude không sử dụng skill của bạn khi mong đợi:
1. Kiểm tra mô tả bao gồm các từ khóa người dùng sẽ tự nhiên nói
2. Xác minh skill xuất hiện khi hỏi "What skills are available?"
3. Thử diễn đạt lại yêu cầu của bạn để phù hợp với mô tả
4. Gọi trực tiếp với `/skill-name` để kiểm tra
### Skill Kích Hoạt Quá Thường
Nếu Claude sử dụng skill của bạn khi bạn không muốn:
1. Làm cho mô tả cụ thể hơn
2. Thêm `disable-model-invocation: true` để chỉ gọi thủ công
### Claude Không Thấy Tất Cả Skills
Các mô tả Skill được tải ở **2% của cửa sổ bối cảnh** (fallback: **16,000 ký tự**). Chạy `/context` để kiểm tra các cảnh báo về các skills bị loại bỏ. Ghi đè ngân sách với biến môi trường `SLASH_COMMAND_TOOL_CHAR_BUDGET`.
## Cân Nhắc Bảo Mật
**Chỉ sử dụng Skills từ các nguồn đáng tin cậy.** Skills cung cấp cho Claude các khả năng qua hướng dẫn và code—một Skill độc hại có thể hướng dẫn Claude gọi các công cụ hoặc thực thi code theo cách có hại.
**Cân nhắc bảo mật chính:**
- **Kiểm tra kỹ**: Xem xét tất cả các file trong thư mục Skill
- **Nguồn bên ngoài là rủi ro**: Skills mà fetch từ các URL bên ngoài có thể bị xâm phạm
- **Lạm dụng công cụ**: Skills độc hại có thể gọi các công cụ theo cách có hại
- **Coi như cài đặt phần mềm**: Chỉ sử dụng Skills từ các nguồn đáng tin cậy
## Skills So Với Các Tính Năng Khác
| Tính Năng | Gọi | Tốt Nhất Cho |
|---------|------------|----------|
| **Skills** | Tự động hoặc `/name` | Chuyên môn có thể tái sử dụng, workflows |
| **Lệnh Slash** | Người dùng khởi tạo `/name` | Các lối tắt nhanh (đã hợp nhất vào skills) |
| **Tác Nhân Con** | Tự động ủy quyền | Thực thi tác vụ cô lập |
| **Bộ Nhớ (CLAUDE.md)** | Luôn được tải | Bối cảnh dự án liên tục |
| **MCP** | Thời gian thực | Truy cập dữ liệu/dịch vụ bên ngoài |
| **Hooks** | Dựa trên sự kiện | Các tác dụng phụ tự động |
## Các Skills Được Gói
Claude Code được gửi với một số skills được tích hợp sẵn luôn có sẵn mà không cần cài đặt:
| Skill | Mô Tả |
|-------|-------------|
| `/simplify` | Review các file đã thay đổi để tái sử dụng, chất lượng, và hiệu quả; tạo ra 3 tác nhân review song song |
| `/batch <instruction>` | Điều phối các thay đổi song song quy mô lớn qua codebase sử dụng git worktrees |
| `/debug [description]` | Khắc phục sự cố phiên hiện tại bằng cách đọc debug log |
| `/loop [interval] <prompt>` | Chạy prompt lặp lại trên khoảng thời gian (ví dụ: `/loop 5m check the deploy`) |
| `/claude-api` | Tải tài liệu tham khảo Claude API/SDK; tự động kích hoạt trên các imports `anthropic`/`@anthropic-ai/sdk` |
Các skills này có sẵn ngay lập tức và không cần được cài đặt hoặc cấu hình. Chúng theo cùng định dạng SKILL.md như các skills tùy chỉnh.
## Chia Sẻ Skills
### Project Skills (Chia Sẻ Đội)
1. Tạo Skill trong `.claude/skills/`
2. Commit vào git
3. Các thành viên kéo các thay đổi — Skills có sẵn ngay lập tức
### Skills Cá Nhân
```bash
# Copy đến thư mục cá nhân
cp -r my-skill ~/.claude/skills/
# Make scripts executable
chmod +x ~/.claude/skills/my-skill/scripts/*.py
```
### Phân Phối Plugin
Gói skills trong thư mục `skills/` của plugin để phân phối rộng hơn.
## Đi Tiếp Xa: Một Bộ Sưu Tập Skill và Một Trình Quản Lý Skill
Khi bạn bắt đầu xây dựng skills một cách nghiêm túc, hai điều trở nên cần thiết: một thư viện của các skills đã được chứng minh và một công cụ để quản lý chúng.
**[luongnv89/skills](https://github.com/luongnv89/skills)** — Một bộ sưu tập các skills tôi sử dụng hàng ngày qua hầu hết tất cả các dự án của tôi. Các điểm nổi bật bao gồm `logo-designer` (tạo logo dự án ngay lập tức) và `ollama-optimizer` (tinh chỉnh hiệu suất LLM cục bộ cho phần cứng của bạn). Điểm khởi đầu tuyệt vời nếu bạn muốn các skills đã sẵn sàng sử dụng.
**[luongnv89/asm](https://github.com/luongnv89/asm)** — Agent Skill Manager. Xử lý phát triển skill, phát hiện trùng lặp, và kiểm tra. Lệnh `asm link` cho phép bạn kiểm tra một skill trong bất kỳ dự án nào mà không cần sao chép files — cần thiết khi bạn có nhiều một chút skills.
## Tài Nguyên Thêm
- [Tài Liệu Skills Chính Thức](https://code.claude.com/docs/en/skills)
- [Blog Kiến Trúc Agent Skills](https://claude.com/blog/equipping-agents-for-the-real-world-with-agent-skills)
- [Kho Skills](https://github.com/luongnv89/skills) - Bộ sưu tập các skills đã sẵn sàng sử dụng
- [Hướng Dẫn Lệnh Slash](../01-slash-commands/) - Các lối tắt do người dùng khởi tạo
- [Hướng Dẫn Tác Nhân Con](../04-subagents/) - Các tác nhân AI được ủy quyền
- [Hướng Dẫn Bộ Nhớ](../02-memory/) - Bối cảnh liên tục
- [MCP (Model Context Protocol)](../05-mcp/) - Dữ liệu bên ngoài thời gian thực
- [Hướng Dẫn Hooks](../06-hooks/) - Tự động hóa dựa trên sự kiện

View File

@@ -0,0 +1,274 @@
---
name: blog-draft
description: Soạn thảo bài đăng blog từ ý tưởng và tài nguyên. Sử dụng khi người dùng muốn viết bài blog, tạo nội dung từ nghiên cứu, hoặc soạn thảo bài viết. Hướng dẫn qua nghiên cứu, động não, lập dàn ý, và soạn thảo lặp lại với kiểm soát phiên bản.
---
## Đầu Vào Người Dùng
```text
$ARGUMENTS
```
Bạn **BẮT BUỘC** phải xem xét đầu vào của người dùng trước khi tiếp tục. Người dùng nên cung cấp:
- **Ý tưởng/Chủ đề**: Khái niệm hoặc chủ đề chính cho bài đăng blog
- **Tài nguyên**: URLs, files, hoặc tài liệu tham khảo để nghiên cứu (tùy chọn nhưng được khuyến nghị)
- **Đối tượng mục tiêu**: Bài đăng blog dành cho ai (tùy chọn)
- **Giọng điệu/Phong cách**: Trang trọng, thân mật, kỹ thuật, v.v. (tùy chọn)
**QUAN TRỌNG**: Nếu người dùng đang yêu cầu cập nhật cho một **bài đăng blog hiện có**, bỏ qua các bước 0-8 và bắt đầu trực tiếp tại **Bước 9**. Đọc các file draft hiện có trước, sau đó tiếp tục với quy trình lặp lại.
## Quy Trình Thực Thi
Làm theo các bước này tuần tự. **Đừng bỏ qua bước hoặc tiếp tục mà không có sự chấp thuận của người dùng nơi được chỉ ra.**
### Bước 0: Tạo Thư Mục Dự Án
1. Tạo tên thư mục sử dụng định dạng: `YYYY-MM-DD-ten-chu-de-ngan`
- Sử dụng ngày hôm nay
- Tạo một slug ngắn, thân thiện với URL từ chủ đề (chữ thường, gạch ngang, tối đa 5 từ)
2. Tạo cấu trúc thư mục:
```
blog-posts/
└── YYYY-MM-DD-ten-chu-de-ngan/
└── resources/
```
3. Xác nhận việc tạo thư mục với người dùng trước khi tiếp tục.
### Bước 1: Nghiên Cứu & Thu Thập Tài Nguyên
1. Tạo thư mục con `resources/` trong thư mục bài đăng blog
2. Với mỗi tài nguyên được cung cấp:
- **URLs**: Lấy và lưu thông tin chính vào `resources/` dưới dạng files markdown
- **Files**: Đọc và tóm tắt trong `resources/`
- **Chủ đề**: Sử dụng tìm kiếm web để thu thập thông tin cập nhật
3. Với mỗi tài nguyên, tạo một file tóm tắt trong `resources/`:
- `resources/source-1-[ten-ngan].md`
- `resources/source-2-[ten-ngan].md`
- v.v.
4. Mỗi tóm tắt nên bao gồm:
```markdown
# Nguồn: [Tiêu Đề/URL]
## Các Điểm Chính
- Điểm 1
- Điểm 2
## Trích Dẫn/Dữ Liệu Liên Quan
- Trích dẫn hoặc thống kê 1
- Trích dẫn hoặc thống kê 2
## Cái Này Liên Quan Đến Chủ Đề Như Thế Nào
Giải thích ngắn về sự liên quan
```
5. Trình bày tóm tắt nghiên cứu cho người dùng.
### Bước 2: Động Não & Làm Rõ
1. Dựa trên ý tưởng và các tài nguyên đã nghiên cứu, trình bày:
- **Chủ đề chính** được xác định từ nghiên cứu
- **Góc độ tiềm năng** cho bài đăng blog
- **Các điểm chính** nên được bao phủ
- **Khoảng trống** trong thông tin cần làm rõ
2. Đặt các câu hỏi làm rõ:
- Điều chính bạn muốn người đọc nhận được là gì?
- Có điểm cụ thể nào từ nghiên cứu bạn muốn nhấn mạnh không?
- Độ dài mục tiêu là bao nhiêu? (ngắn: 500-800 từ, trung bình: 1000-1500, dài: 2000+)
- Có điểm nào bạn muốn loại bỏ không?
3. **Chờ phản hồi của người dùng trước khi tiếp tục.**
### Bước 3: Đề Xuất Dàn Ý
1. Tạo một dàn ý có cấu trúc bao gồm:
```markdown
# Dàn Ý Bài Đăng Blog: [Tiêu Đề]
## Thông Tin Meta
- **Đối Tượng Mục Tiêu**: [ai]
- **Giọng Điệu**: [phong cách]
- **Độ Dài Mục Tiêu**: [số lượng từ]
- **Điểm Chính Lấy Được**: [thông điệp chính]
## Cấu Trúc Được Đề Xuất
### Mở Bài/Giới Thiệu
- Ý tưởng mở bài hấp dẫn
- Thiết lập bối cảnh
- Tuyên bố luận điểm
### Phần 1: [Tiêu Đề]
- Điểm chính A
- Điểm chính B
- Bằng chứng hỗ trợ từ [nguồn]
### Phần 2: [Tiêu Đề]
- Điểm chính A
- Điểm chính B
[Tiếp tục cho tất cả các phần...]
### Kết Luận
- Tóm tắt các điểm chính
- Kêu gọi hành động hoặc suy nghĩ cuối cùng
## Nguồn Để Trích Dẫn
- Nguồn 1
- Nguồn 2
```
2. Trình bày dàn ý cho người dùng và **yêu cầu chấp thuận hoặc chỉnh sửa**.
### Bước 4: Lưu Dàn Ý Được Chấp Thuận
1. Khi người dùng chấp thuận dàn ý, lưu nó vào `OUTLINE.md` trong thư mục bài đăng blog.
2. Xác nhận dàn ý đã được lưu.
### Bước 5: Commit Dàn Ý (nếu trong git repo)
1. Kiểm tra xem thư mục hiện tại có phải là một git repository không.
2. Nếu có:
- Stage các file mới: thư mục bài đăng blog, resources, và OUTLINE.md
- Tạo commit với thông điệp: `docs: Add outline for blog post - [ten-chu-de]`
- Push đến remote
3. Nếu không phải là git repo, bỏ qua bước này và thông báo cho người dùng.
### Bước 6: Viết Bản Nháp
1. Dựa trên dàn ý được chấp thuận, viết bản nháp bài đăng blog đầy đủ.
2. Làm theo cấu trúc từ OUTLINE.md chính xác.
3. Bao gồm:
- Giới thiệu hấp dẫn với mở bài
- Các tiêu đề phần rõ ràng
- Bằng chứng hỗ trợ và ví dụ từ nghiên cứu
- Chuyển tiếp mượt mà giữa các phần
- Kết luận mạnh mẽ với điểm chính
- **Trích dẫn**: Tất cả các so sánh, thống kê, dữ liệu, và yêu cầu thực tế PHẢI trích dẫn nguồn gốc
4. Lưu bản nháp dưới dạng `draft-v0.1.md` trong thư mục bài đăng blog.
5. Định dạng:
```markdown
# [Tiêu Đề Bài Đăng Blog]
*[Tùy chọn: phụ đề hoặc câu khẩu hiệu]*
[Nội dung đầy đủ với các trích dẫn nội tuyến...]
---
## Tài Liệu Tham Khảo
- [1] Tiêu Đề Nguồn 1 - URL hoặc Trích Dẫn
- [2] Tiêu Đề Nguồn 2 - URL hoặc Trích Dẫn
- [3] Tiêu Đề Nguồn 3 - URL hoặc Trích Dẫn
```
6. **Yêu Cầu Trích Dẫn**:
- Mọi điểm dữ liệu, thống kê, hoặc so sánh PHẢI có trích dẫn nội tuyến
- Sử dụng tài liệu tham khảo đánh số [1], [2], v.v., hoặc trích dẫn có tên [Tên Nguồn]
- Liên kết các trích dẫn với phần Tài Liệu Tham Khảo ở cuối
- Ví dụ: "Các nghiên cứu cho thấy 65% nhà phát triển ưa thích TypeScript [1]"
- Ví dụ: "React hoạt động tốt hơn Vue 20% về tốc độ render [React Benchmarks 2024]"
### Bước 7: Commit Bản Nháp (nếu trong git repo)
1. Kiểm tra xem có trong git repository không.
2. Nếu có:
- Stage file bản nháp
- Tạo commit với thông điệp: `docs: Add draft v0.1 for blog post - [ten-chu-de]`
- Push đến remote
3. Nếu không phải là git repo, bỏ qua và thông báo cho người dùng.
### Bước 8: Trình Bày Bản Nháp Để Xem Xét
1. Trình bày nội dung bản nháp cho người dùng.
2. Yêu cầu phản hồi:
- Ấn tượng tổng thể?
- Các phần cần mở rộng hoặc giảm bớt?
- Cần điều chỉnh giọng điệu?
- Thiếu thông tin?
- Chỉnh sửa hoặc viết lại cụ thể?
3. **Chờ phản hồi của người dùng.**
### Bước 9: Lặp Lại Hoặc Hoàn Thành
**Nếu người dùng yêu cầu thay đổi:**
1. Ghi chú tất cả các chỉnh sửa được yêu cầu
2. Quay lại Bước 6 với các điều chỉnh sau:
- Tăng số phiên bản (v0.2, v0.3, v.v.)
- Kết hợp tất cả phản hồi
- Lưu dưới dạng `draft-v[X.Y].md`
- Lặp lại Các bước 7-8
**Nếu người dùng chấp thuận:**
1. Xác nhận phiên bản bản nháp cuối cùng
2. Tùy chọn đổi tên thành `final.md` nếu người dùng yêu cầu
3. Tóm tắt quy trình tạo bài đăng blog:
- Tổng số phiên bản được tạo
- Các thay đổi chính giữa các phiên bản
- Số lượng từ cuối cùng
- Các file được tạo
## Theo Dõi Phiên Bản
Tất cả bản nháp được bảo tồn với việc đánh số phiên bản tăng dần:
- `draft-v0.1.md` - Bản nháp ban đầu
- `draft-v0.2.md` - Sau vòng phản hồi đầu tiên
- `draft-v0.3.md` - Sau vòng phản hồi thứ hai
- v.v.
Điều này cho phép theo dõi sự phát triển của bài đăng blog và hoàn tác nếu cần.
## Cấu Trúc File Đầu Ra
```
blog-posts/
└── YYYY-MM-DD-ten-chu-de/
├── resources/
│ ├── source-1-name.md
│ ├── source-2-name.md
│ └── ...
├── OUTLINE.md
├── draft-v0.1.md
├── draft-v0.2.md (nếu có lặp lại)
└── draft-v0.3.md (nếu có nhiều lặp lại hơn)
```
## Mẹo Để Chất Lượng
- **Mở bài**: Bắt đầu với một câu hỏi, sự thật đáng ngạc nhiên, hoặc kịch bản có thể liên quan
- **Dòng Chảy**: Mỗi đoạn nên kết nối với đoạn tiếp theo
- **Bằng Chứng**: Hỗ trợ các yêu cầu với dữ liệu từ nghiên cứu
- **Trích Dẫn**: LUÔN LUÔN trích dẫn nguồn cho:
- Tất cả thống kê và điểm dữ liệu (ví dụ: "Theo [Nguồn], 75% của...")
- So sánh giữa các sản phẩm, dịch vụ, hoặc cách tiếp cận (ví dụ: "X hoạt động nhanh hơn gấp 2 lần so với Y [Nguồn]")
- Các yêu cầu thực tế về xu hướng thị trường, phát hiện nghiên cứu, hoặc điểm chuẩn
- Sử dụng trích dẫn nội tuyến với định dạng: [Tên Nguồn] hoặc [Tác Giả, Năm]
- **Giọng**: Duy trì giọng điệu nhất quán throughout
- **Độ Dài**: Tôn trọng số lượng từ mục tiêu
- **Khả Đọc**: Sử dụng các đoạn ngắn, gạch đầu dòng nơi phù hợp
- **CTA**: Kết thúc với một lời kêu gọi hành động rõ ràng hoặc câu hỏi đáng suy ngẫm
## Ghi Chú
- Luôn chờ chấp thuận của người dùng tại các điểm kiểm tra được phác thảo
- Bảo tồn tất cả các phiên bản bản nháp để lịch sử
- Sử dụng tìm kiếm web để có thông tin cập nhật khi URLs được cung cấp
- Nếu tài nguyên không đủ, yêu cầu người dùng thêm hoặc đề xuất nghiên cứu bổ sung
- Thích ứng giọng điệu dựa trên đối tượng mục tiêu (kỹ thuật, chung, kinh doanh, v.v.)

View File

@@ -0,0 +1,72 @@
---
name: brand-voice-consistency
description: Đảm bảo tất cả các truyền thông phù hợp với hướng dẫn giọng điệu và phong cách thương hiệu. Sử dụng khi tạo bản sao marketing, truyền thông khách hàng, nội dung công khai, hoặc khi người dùng đề cập đến giọng điệu thương hiệu, ngữ điệu, hoặc phong cách viết.
---
# Brand Voice Skill
## Tổng Quan
Skill này đảm bảo tất cả các truyền thông duy trì giọng điệu, ngữ điệu, và thông điệp thương hiệu nhất quán.
## Danh Tính Thương Hiệu
### Sứ Mệnh
Giúp các đội tự động hóa workflows phát triển của họ với AI
### Giá Trị
- **Sự Đơn Giản**: Làm cho những điều phức tạp trở nên đơn giản
- **Độ Tin Cậy**: Thực thi vững chắc
- **Sự Trao Quyền**: Cho phép sự sáng tạo của con người
### Giọng Điệu
- **Thân thiện nhưng chuyên nghiệp** - có thể tiếp cận mà không thân mật quá
- **Rõ ràng và ngắn gọn** - tránh thuật ngữ, giải thích các khái niệm kỹ thuật một cách đơn giản
- **Tự Tin** - chúng tôi biết chúng tôi đang làm gì
- **Thấu Cảm** - hiểu nhu cầu và nỗi đau của người dùng
## Hướng Dẫn Viết
### Nên Làm ✅
- Sử dụng "bạn" khi người đọc
- Sử dụng chủ động: "Claude tạo báo cáo" không "Báo cáo được tạo bởi Claude"
- Bắt đầu với giá trị
- Sử dụng các ví dụ cụ thể
- Giữ câu dưới 20 từ
- Sử dụng danh sách để rõ ràng
- Bao gồm các lời kêu gọi hành động
### Không Nên Làm ❌
- Đừng sử dụng thuật ngữ công ty
- Đừng cư xử như trên hoặc đơn giản hóa quá mức
- Đừng sử dụng "chúng tôi tin" hoặc "chúng tôi nghĩ"
- Đừng sử dụng HOA TOÀN THỨ TRỪ khi nhấn mạnh
- Đừng tạo các bức tường văn bản
- Đừng giả định kiến thức kỹ thuật
## Từ Vựng
### ✅ Thuật Ngữ Ưu Tiên
- Claude (not "the Claude AI")
- Code generation (not "auto-coding")
- Agent (not "bot")
- Streamline (not "revolutionize")
- Integrate (not "synergize")
### ❌ Tránh Thuật Ngữ
- "Cutting-edge" (bị lạm dụng)
- "Game-changer" (mơ hồ)
- "Leverage" (ngôn ngữ công ty)
- "Utilize" (use "use")
- "Paradigm shift" (không rõ)
## Ví Dụ
### ✅ Ví Dụ Tốt
"Claude tự động hóa quy trình review code của bạn. Thay vì kiểm tra thủ công từng PR, Claude review bảo mật, hiệu suất, và chất lượng—tiết kiệm cho đội của bạn hàng mỗi tuần."
Tại sao nó hoạt động: Giá trị rõ ràng, lợi ích cụ thể, hướng hành động
### ❌ Ví Dụ Xấu
"Claude leverages cutting-edge AI to provide comprehensive software development solutions."
Tại sao nó không hoạt động: Mơ hồ, thuật ngữ công ty, không có giá trị cụ thể

View File

@@ -0,0 +1,212 @@
---
name: claude-md
description: Tạo hoặc cập nhật các file CLAUDE.md theo các thực hành tốt nhất để onboarding tác nhân AI tối ưu
---
## Đầu Vào Người Dùng
```text
$ARGUMENTS
```
Bạn **BẮT BUỘC** phải xem xét đầu vào của người dùng trước khi tiếp tục (nếu không trống). Người dùng có thể chỉ định:
- `create` - Tạo CLAUDE.md mới từ đầu
- `update` - Cải thiện CLAUDE.md hiện có
- `audit` - Phân tích và báo cáo về chất lượng CLAUDE.md hiện tại
- Một đường dẫn cụ thể để tạo/cập nhật (ví dụ: `src/api/CLAUDE.md` cho hướng dẫn cụ thể thư mục)
## Nguyên Tắc Cốt Lõi
**LLMs là không trạng thái**: CLAUDE.md là file duy nhất được bao gồm tự động trong mọi cuộc hội thoại. Nó phục vụ như tài liệu onboarding chính cho các tác nhân AI vào codebase của bạn.
### Các Quy Tắc Vàng
1. **Less is More**: Các LLM biên giới có thể theo ~150-200 hướng dẫn. System prompt của Claude Code đã sử dụng ~50. Giữ CLAUDE.md của bạn tập trung và ngắn gọn.
2. **Ứng Dụng Phổ Biến**: Chỉ bao gồm thông tin liên quan đến MỌI phiên. Hướng dẫn cụ thể theo tác vụ thuộc về các file riêng.
3. **Đừng Sử Dụng Claude như Linter**: Hướng dẫn phong cách làm phình bối cảnh và làm giảm khả năng tuân theo hướng dẫn. Sử dụng các công cụ xác định (prettier, eslint, v.v.) thay thế.
4. **Không Bao Giờ Tự Động Tạo**: CLAUDE.md là điểm đòn bẩy cao nhất của hệ thống AI. Tạo nó thủ công với sự xem xét cẩn thận.
## Quy Trình Thực Thi
### 1. Phân Tích Dự Án
Đầu tiên, phân tích trạng thái dự án hiện tại:
1. Kiểm tra các file CLAUDE.md hiện có:
- Cấp root: `./CLAUDE.md` hoặc `.claude/CLAUDE.md`
- Cụ thể thư mục: `**/CLAUDE.md`
- Cấu hình người dùng toàn cầu: `~/.claude/CLAUDE.md`
2. Xác định cấu trúc dự án:
- Technology stack (ngôn ngữ, frameworks)
- Loại dự án (monorepo, ứng dụng đơn, library)
- Công cụ phát triển (quản lý package, hệ thống build, trình chạy test)
3. Xem lại tài liệu hiện có:
- README.md
- CONTRIBUTING.md
- package.json, pyproject.toml, Cargo.toml, v.v.
### 2. Chiến Lược Nội Dung (WHAT, WHY, HOW)
Cấu trúc CLAUDE.md xung quanh ba chiều:
#### WHAT - Công Nghệ & Cấu Trúc
- Tổng quan technology stack
- Tổ chức dự án (đặc biệt quan trọng cho monorepos)
- Các thư mục chính và mục đích của chúng
#### WHY - Mục Đích & Bối Cảnh
- Dự án làm gì
- Tại sao các quyết định kiến trúc nhất định được đưa ra
- Mỗi thành phần chính chịu trách nhiệm cho gì
#### HOW - Workflow & Quy Ước
- Workflow phát triển (bun vs node, pip vs uv, v.v.)
- Thủ tục và lệnh testing
- Phương pháp xác minh và build
- Các "gotchas" quan trọng hoặc yêu cầu không rõ ràng
### 3. Chiến Lược Progressive Disclosure
Đối với các dự án lớn, khuyến nghị tạo thư mục `agent_docs/`:
```
agent_docs/
|- building_the_project.md
|- running_tests.md
|- code_conventions.md
|- architecture_decisions.md
```
Trong CLAUDE.md, tham khảo các file này với các hướng dẫn như:
```markdown
Để có hướng dẫn build chi tiết, tham khảo `agent_docs/building_the_project.md`
```
**Quan Trọng**: Sử dụng các tham chiếu `file:line` thay vì các đoạn code để tránh bối cảnh lỗi thời.
### 4. Ràng Buộc Chất Lượng
Khi tạo hoặc cập nhật CLAUDE.md:
1. **Độ Dài Mục Tiêu**: Dưới 300 dòng (lý tưởng dưới 100)
2. **Không Quy Tắc Phong Cách**: Loại bỏ bất kỳ hướng dẫn linting/formatting nào
3. **Không Hướng Dẫn Cụ Theo Tác Vụ**: Di chuyển sang các file riêng
4. **Không Đoạn Code**: Sử dụng tham chiếu file thay thế
5. **Không Thông Tin Dư Thừa**: Đừng lặp lại những gì trong package.json hoặc README
### 5. Các Phần Thiết Yếu
Một CLAUDE.md được cấu trúc tốt nên bao gồm:
```markdown
# Tên Dự Án
Mô tả ngắn một dòng.
## Tech Stack
- Ngôn ngữ chính và phiên bản
- Frameworks/thư viện chính
- Database/lưu trữ (nếu có)
## Cấu Trúc Dự Án
[Chỉ cho monorepos hoặc cấu trúc phức tạp]
- `apps/` - Điểm vào ứng dụng
- `packages/` - Thư viện được chia sẻ
## Lệnh Phát Triển
- Install: `command`
- Test: `command`
- Build: `command`
## Quy Ước Quan Trọng
[Chỉ các quy ước không rõ ràng, tác động cao]
- Quy ước 1 với giải thích ngắn
- Quy ước 2 với giải thích ngắn
## Vấn Đế Đã Biết / Gotchas
[Những gì luôn làm các nhà phát triển vấp phải]
- Vấn đề 1
- Vấn đề 2
```
### 6. Các Anti-Patterns Cần Tránh
**KHÔNG bao gồm:**
- Hướng dẫn phong cách code (sử dụng linters)
- Tài liệu về cách sử dụng Claude
- Giải thích dài về các mẫu rõ ràng
- Các ví dụ code copy-paste
- Thực hành tốt chung ("viết code sạch")
- Hướng dẫn cho các tác vụ cụ thể
- Nội dung được tạo tự động
- Danh sách TODO mở rộng
### 7. Checklist Xác Minh
Trước khi hoàn thành, xác minh:
- [ ] Dưới 300 dòng (lý tưởng dưới 100)
- [ ] Mọi dòng áp dụng cho TẤT CẢ các phiên
- [ ] Không quy tắc phong cách/formatting
- [ ] Không đoạn code (sử dụng tham chiếu file)
- [ ] Các lệnh được xác minh hoạt động
- [ ] Progressive disclosure được sử dụng cho các dự án phức tạp
- [ ] Các gotchas quan trọng được tài liệu hóa
- [ ] Không dư thừa với README.md
## Định Dạng Đầu Ra
### Cho `create` hoặc mặc định:
1. Phân tích dự án
2. Soạn thảo CLAUDE.md theo cấu trúc ở trên
3. Trình bày bản nháp để xem xét
4. Ghi vào vị trí phù hợp sau khi được chấp thuận
### Cho `update`:
1. Đọc CLAUDE.md hiện có
2. Kiểm tra theo các thực hành tốt nhất
3. Xác định:
- Nội dung để loại bỏ (quy tắc phong cách, đoạn code, cụ thể tác vụ)
- Nội dung để cô đọng
- Thông tin thiết bị còn thiếu
4. Trình bày các thay đổi để xem xét
5. Áp dụng các thay đổi sau khi được chấp thuận
### Cho `audit`:
1. Đọc CLAUDE.md hiện có
2. Tạo một báo cáo với:
- Số dòng hiện tại vs mục tiêu
- Phần trăm nội dung áp dụng phổ biến
- Danh sách các anti-patterns được tìm thấy
- Khuyến nghị cải thiện
3. KHÔNG chỉnh sửa file, chỉ báo cáo
## Xử Lý AGENTS.md
Nếu người dùng yêu cầu tạo/cập nhật AGENTS.md:
AGENTS.md được sử dụng để định nghĩa các hành vi tác nhân chuyên biệt. Không giống CLAUDE.md (dành cho bối cảnh dự án), AGENTS.md định nghĩa:
- Các vai trò và khả năng tác nhân tùy chỉnh
- Hướng dẫn và ràng buộc cụ thể tác nhân
- Định nghĩa workflow cho các kịch bản đa tác nhân
Áp dụng các nguyên tắc tương tự:
- Giữ tập trung và ngắn gọn
- Sử dụng progressive disclosure
- Tham khảo tài liệu bên ngoài thay vì nhúng nội dung
## Ghi Chú
- Luôn xác minh các lệnh hoạt động trước khi bao gồm chúng
- Khi nghi ngờ, hãy loại bỏ - less is more
- Lời nhắc hệ thống cho Claude biết rằng CLAUDE.md "có thể hoặc có thể không liên quan" - càng nhiều tiếng ồn, càng bị bỏ qua
- Monorepos hưởng lợi nhất từ cấu trúc WHAT/WHY/HOW rõ ràng
- Các file CLAUDE.md cụ thể thư mục nên được tập trung hơn nữa

View File

@@ -0,0 +1,70 @@
---
name: code-review-specialist
description: Review code toàn diện với phân tích bảo mật, hiệu suất, và chất lượng. Sử dụng khi người dùng yêu cầu review code, phân tích chất lượng code, đánh giá pull requests, hoặc đề cập đến review code, phân tích bảo mật, hoặc tối ưu hóa hiệu suất.
---
# Code Review Skill
Skill này cung cấp các khả năng review code toàn diện tập trung vào:
1. **Phân Tích Bảo Mật**
- Các vấn đề xác thực/uỷ quyền
- Rủi ro lộ dữ liệu
- Lỗ hổng tiêm nhiễm
- Điểm yếu mật mã
- Ghi log dữ liệu nhạy cảm
2. **Review Hiệu Suất**
- Hiệu quả thuật toán (phân tích Big O)
- Tối ưu hóa bộ nhớ
- Tối ưu hóa truy vấn cơ sở dữ liệu
- Cơ hội caching
- Các vấn đề đồng thời
3. **Chất Lượng Code**
- Nguyên tắc SOLID
- Mẫu thiết kế
- Quy ước đặt tên
- Tài liệu hóa
- Phủ vùng test
4. **Khả Năng Duy Trì**
- Khả năng đọc code
- Kích thước hàm (nên < 50 dòng)
- Độ phức tạp vòng lục
- Quản lý dependency
- An toàn kiểu
## Mẫu Review
Đối với mỗi đoạn code được review, cung cấp:
### Tóm Tắt
- Đánh giá chất lượng tổng thể (1-5)
- Số lượng phát hiện chính
- Các khu vực ưu tiên được khuyến nghị
### Vấn Đề Nguy Kịch (nếu có)
- **Vấn đề**: Mô tả rõ ràng
- **Vị Trí**: File và số dòng
- **Tác Động**: Tại sao điều này quan trọng
- **Mức Độ**: Nguy Kịch/Cao/Trung Bình
- **Khắc Phục**: Ví dụ code
### Các Phát Hiện Theo Danh Mục
#### Bảo Mật (nếu tìm thấy vấn đề)
Liệt kê các lỗ hổng bảo mật với ví dụ
#### Hiệu Suất (nếu tìm thấy vấn đề)
Liệt kê các vấn đề hiệu suất với phân tích độ phức tạp
#### Chất Lượng (nếu tìm thấy vấn đề)
Liệt kê các vấn đề chất lượng code với các đề xuất refactor
#### Khả Năng Duy Trì (nếu tìm thấy vấn đề)
Liệt kê các vấn đề duy trì với các cải tiến
## Lịch Sử Phiên Bản
- v1.0.0 (2024-12-10): Phiên bản phát hành ban đầu với phân tích bảo mật, hiệu suất, chất lượng, và khả năng duy trì

View File

@@ -0,0 +1,426 @@
---
name: code-refactor
description: Refactor code có hệ thống dựa trên phương pháp luận của Martin Fowler. Sử dụng khi người dùng yêu cầu refactor code, cải thiện cấu trúc code, giảm nợ kỹ thuật, dọn code legacy, loại bỏ code smells, hoặc cải thiện khả năng duy trì code. Skill này hướng dẫn qua cách tiếp theo từng giai đoạn với nghiên cứu, lập kế hoạch, và triển khai tăng dần an toàn.
---
# Code Refactoring Skill
Một cách tiếp có hệ thống để refactor code dựa trên *Refactoring: Improving the Design of Existing Code* (ấn bản 2) của Martin Fowler. Skill này nhấn mạnh các thay đổi tăng dần, an toàn được hỗ trợ bởi tests.
> "Refactoring là quá trình thay đổi một hệ thống phần mềm theo cách mà nó không làm thay đổi hành vi bên ngoài của code nhưng cải thiện cấu trúc nội bộ của nó." — Martin Fowler
## Nguyên Tắc Cốt Lõi
1. **Bảo Tồn Hành Vi**: Hành vi bên ngoài phải không thay đổi
2. **Các Bước Nhỏ**: Thực hiện các thay đổi nhỏ, có thể test
3. **Được Dẫn Bởi Test**: Tests là lưới an toàn
4. **Liên Tục**: Refactoring là liên tục, không phải sự kiện một lần
5. **Hợp Tác**: Cần sự chấp thuận của người dùng tại mỗi giai đoạn
## Tổng Quan Workflow
```
Giai Đoạn 1: Nghiên Cứu & Phân Tích
Giai Đoạn 2: Đánh Giá Phủ Vùng Test
Giai Đoạn 3: Xác Định Code Smell
Giai Đoạn 4: Tạo Kế Hoạch Refactoring
Giai Đoạn 5: Triển Khai Tăng Dần
Giai Đoạn 6: Review & Lặp Lại
```
---
## Giai Đoạn 1: Nghiên Cứu & Phân Tích
### Mục Tiêu
- Hiểu cấu trúc và mục đích của codebase
- Xác định phạm vi của refactoring
- Thu thập bối cảnh về các yêu cầu kinh doanh
### Câu Hỏi Đặt Cho Người Dùng
Trước khi bắt đầu, làm rõ:
1. **Phạm Vi**: Những file/module/hàm nào cần refactor?
2. **Mục Tiêu**: Bạn đang cố gắng giải quyết vấn đề gì? (khả đọc, hiệu suất, khả năng duy trì)
3. **Ràng Buộc**: Có những khu vực nào KHÔNG NÊN thay đổi không?
4. **Áp Lực Thời Gian**: Điều này có chặn công việc khác không?
5. **Trạng Thái Test**: Tests có tồn tại không? Chúng có pass không?
### Hành Động
- [ ] Đọc và hiểu code mục tiêu
- [ ] Xác định dependencies và integrations
- [ ] Tài liệu hóa kiến trúc hiện tại
- [ ] Ghi chú bất kỳ markers nợ kỹ thuật hiện có (TODOs, FIXMEs)
### Đầu Ra
Trình bày phát hiện cho người dùng:
- Tóm tắt cấu trúc code
- Các khu vực vấn đề được xác định
- Khuyến nghị ban đầu
- **Yêu cầu chấp thuận để tiếp tục**
---
## Giai Đoạn 2: Đánh Giá Phủ Vùng Test
### Tại Sao Tests Quan Trọng
> "Refactoring mà không có tests giống như lái xe mà không có thắt dây an toàn." — Martin Fowler
Tests là **bật dụng chính** của refactoring an toàn. Không có chúng, bạn có nguy cơ giới thiệu bugs.
### Các Bước Đánh Giá
1. **Kiểm tra các test hiện có**
```bash
# Tìm các file test
find . -name "*test*" -o -name "*spec*" | head -20
```
2. **Chạy các test hiện có**
```bash
# JavaScript/TypeScript
npm test
# Python
pytest -v
# Java
mvn test
```
3. **Kiểm tra phủ vùng (nếu có)**
```bash
# JavaScript
npm run test:coverage
# Python
pytest --cov=.
```
### Điểm Quyết Định: Hỏi Người Dùng
**Nếu tests tồn tại và pass:**
- Tiếp tục đến Giai Đoạn 3
**Nếu tests bị thiếu hoặc không hoàn chỉnh:**
Trình bày các tùy chọn:
1. Viết tests trước (khuyến nghị)
2. Thêm tests tăng dần trong khi refactoring
3. Tiếp tục mà không có tests (rủi ro - yêu cầu sự thừa nhận của người dùng)
**Nếu tests đang fail:**
- DỪNG LẠI. Sửa các test fail trước khi refactoring
- Hỏi người dùng: Chúng ta nên sửa tests trước không?
### Hướng Dẫn Viết Test (nếu cần)
Đối với mỗi hàm được refactor, đảm bảo tests bao phủ:
- Happy path (hoạt động bình thường)
- Các trường hợp ngoại lệ (đầu vào trống, null, ranh giới)
- Các kịch bản lỗi (đầu vào không hợp lệ, ngoại lệ)
Sử dụng chu trình "red-green-refactor":
1. Viết test fail (red)
2. Làm cho nó pass (green)
3. Refactor
---
## Giai Đoạn 3: Xác Định Code Smell
### Code Smells Là Gì?
Các triệu chứng của các vấn đề sâu hơn trong code. Chúng không phải là bugs, nhưng là các chỉ báo rằng code có thể được cải thiện.
### Các Code Smells Phổ Biến Để Kiểm Tra
Xem [references/code-smells.md](../../../03-skills/refactor/references/code-smells.md) để có danh sách đầy đủ.
#### Tham Khảo Nhanh
| Smell | Dấu Hiệu | Tác Động |
|-------|-------|--------|
| **Long Method** | Methods > 30-50 dòng | Khó hiểu, test, duy trì |
| **Duplicated Code** | Cùng logic ở nhiều nơi | Cần sửa lỗi ở nhiều nơi |
| **Large Class** | Class với quá nhiều trách nhiệm | Vi phạm Single Responsibility |
| **Feature Envy** | Method sử dụng dữ liệu class khác nhiều | Đóng gói kém |
| **Primitive Obsession** | Lạm dụng primitives thay vì objects | Thiếu các khái niệm domain |
| **Long Parameter List** | Methods với 4+ parameters | Khó gọi đúng |
| **Data Clumps** | Cùng dữ liệu xuất hiện cùng nhau | Thiếu abstraction |
| **Switch Statements** | Switch/if-else chains phức tạp | Khó mở rộng |
| **Speculative Generality** | Code "trường hợp" | Độ phức tạp không cần thiết |
| **Dead Code** | Code không sử dụng | Nhầm lẫn, gánh nặng duy trì |
### Các Bước Phân Tích
1. **Phân Tích Tự Động** (nếu scripts có sẵn)
```bash
python scripts/detect-smells.py <file>
```
2. **Review Thủ Công**
- Đi qua code một cách có hệ thống
- Ghi chú mỗi smell với vị trí và mức độ nghiêm trọng
- Phân loại theo tác động (Nguy Kịch/Cao/Trung Bình/Thấp)
3. **Ưu Tiên**
Tập trung vào các smells mà:
- Chặn phát triển hiện tại
- Gây bugs hoặc nhầm lẫn
- Ảnh hưởng đến các đường dẫn code được thay đổi nhiều nhất
### Đầu Ra: Báo Cáo Smell
Trình bày cho người dùng:
- Danh sách các smells được xác định với vị trí
- Đánh giá mức độ nghiêm trọng cho mỗi smell
- Thứ tự ưu tiên được khuyến nghị
- **Yêu cầu chấp thuận về các ưu tiên**
---
## Giai Đoạn 4: Tạo Kế Hoạch Refactoring
### Chọn Refactorings
Đối với mỗi smell, chọn một refactoring phù hợp từ catalog.
Xem [references/refactoring-catalog.md](../../../03-skills/refactor/references/refactoring-catalog.md) để có danh sách đầy đủ.
#### Smell-to-Refactoring Mapping
| Code Smell | Refactoring Khuyến Nghị |
|------------|---------------------------|
| Long Method | Extract Method, Replace Temp with Query |
| Duplicated Code | Extract Method, Pull Up Method, Form Template Method |
| Large Class | Extract Class, Extract Subclass |
| Feature Envy | Move Method, Move Field |
| Primitive Obsession | Replace Primitive with Object, Replace Type Code with Class |
| Long Parameter List | Introduce Parameter Object, Preserve Whole Object |
| Data Clumps | Extract Class, Introduce Parameter Object |
| Switch Statements | Replace Conditional with Polymorphism |
| Speculative Generality | Collapse Hierarchy, Inline Class, Remove Dead Code |
| Dead Code | Remove Dead Code |
### Cấu Trúc Kế Hoạch
Sử dụng mẫu tại [templates/refactoring-plan.md](../../../03-skills/refactor/templates/refactoring-plan.md).
Đối với mỗi refactoring:
1. **Mục Tiêu**: Code nào sẽ thay đổi
2. **Smell**: Vấn đề nào nó giải quyết
3. **Refactoring**: Kỹ thuật nào để áp dụng
4. **Các Bước**: Các micro-bước chi tiết
5. **Rủi Ro**: Điều gì có thể sai
6. **Hoàn Tác**: Cách hoàn tác nếu cần
### Cách Tiếp Theo Giai Đoạn
**QUAN TRỌNG**: Introduce refactoring tăng dần theo các giai đoạn.
**Giai Đoạn A: Quick Wins** (Rủi ro thấp, giá trị cao)
- Đổi tên biến để rõ hơn
- Extract code trùng lặp rõ ràng
- Loại bỏ dead code
**Giai Đoạn B: Cải Tiến Cấu Trúc** (Rủi ro trung bình)
- Extract methods từ các hàm dài
- Introduce parameter objects
- Move methods đến các lớp phù hợp
**Giai Đoạn C: Thay Đổi Kiến Trúc** (Rủi ro cao hơn)
- Thay thế conditionals với polymorphism
- Extract classes
- Introduce design patterns
### Điểm Quyết Định: Trình Bày Kế Hoạch Cho Người Dùng
Trước khi triển khai:
- Hiển thị kế hoạch refactoring hoàn chỉnh
- Giải thích mỗi giai đoạn và rủi ro của nó
- Nhận sự chấp thuận rõ ràng cho mỗi giai đoạn
- **Hỏi**: "Tôi có nên tiếp tục với Giai Đoạn A không?"
---
## Giai Đoạn 5: Triển Khai Tăng Dần
### Quy Tắc Vàng
> "Thay Đổi → Test → Xanh? → Commit → Bước tiếp theo"
### Nhịp Triển Khai
Đối với mỗi bước refactoring:
1. **Kiểm tra trước**
- Tests đang pass (xanh)
- Code biên dịch
2. **Thực hiện MỘT thay đổi nhỏ**
- Làm theo các cơ chế từ catalog
- Giữ thay đổi tối thiểu
3. **Xác Minh**
- Chạy tests ngay lập tức
- Kiểm tra lỗi biên dịch
4. **Nếu tests pass (xanh)**
- Commit với thông điệp mô tả
- Di chuyển đến bước tiếp theo
5. **Nếu tests fail (đỏ)**
- DỪNG LẠI ngay lập tức
- Hoàn tác thay đổi
- Phân tích điều gì sai
- Hỏi người dùng nếu không rõ
### Chiến Lược Commit
Mỗi commit nên là:
- **Nguyên Tử**: Một thay đổi logic
- **Có Thể Hoàn Tác**: Dễ dàng revert
- **Mô Tả**: Thông điệp commit rõ ràng
Ví dụ thông điệp commit:
```
refactor: Extract calculateTotal() from processOrder()
refactor: Rename 'x' to 'customerCount' for clarity
refactor: Remove unused validateOldFormat() method
```
### Báo Cáo Tiến Độ
Sau mỗi sub-giai đoạn, báo cáo cho người dùng:
- Các thay đổi được thực hiện
- Tests vẫn pass?
- Bất kỳ vấn đề nào gặp phải
- **Hỏi**: "Tiếp tục với batch tiếp theo?"
---
## Giai Đoạn 6: Review & Lặp Lại
### Checklist Sau Refactoring
- [ ] Tất cả tests pass
- [ ] Không có cảnh báo/lỗi mới
- [ ] Code biên dịch thành công
- [ ] Hành vi không thay đổi (xác minh thủ công)
- [ ] Tài liệu được cập nhật nếu cần
- [ ] Lịch sử commit sạch
### So Sánh Metrics
Chạy phân tích độ phức tạp trước và sau:
```bash
python scripts/analyze-complexity.py <file>
```
Trình bày cải tiến:
- Thay đổi số dòng code
- Thay đổi độ phức tạp vòng lục
- Thay đổi chỉ số khả năng duy trì
### Review Người Dùng
Trình bày kết quả cuối cùng:
- Tóm tắt tất cả thay đổi
- So sánh code trước/sau
- Cải tiến metrics
- Nợ kỹ thuật còn lại
- **Hỏi**: "Bạn có hài lòng với những thay đổi này không?"
### Các Bước Tiếp Theo
Thảo luận với người dùng:
- Có smells bổ sung để giải quyết không?
- Lên lịch refactoring tiếp theo?
- Áp dụng các thay đổi tương tự ở nơi khác?
---
## Hướng Dẫn Quan Trọng
### Khi DỪNG LẠI và Hỏi
Luôn dừng lại và tham khảo người dùng khi:
- Không chắc về logic kinh doanh
- Thay đổi có thể ảnh hưởng APIs bên ngoài
- Phủ vùng test không đủ
- Cần quyết định kiến trúc quan trọng
- Mức độ rủi ro tăng
- Bạn gặp độ phức tạp bất ngờ
### Quy Tắc An Toàn
1. **Không bao giờ refactor mà không có tests** (trừ khi người dùng thừa nhận rủi ro một cách rõ ràng)
2. **Không bao giờ thực hiện các thay đổi lớn** - chia thành các bước nhỏ
3. **Không bao giờ bỏ qua chạy test** sau mỗi thay đổi
4. **Không bao giờ tiếp tục nếu tests fail** - sửa hoặc hoàn tác trước
5. **Không bao giờ giả định** - khi nghi ngờ, hãy hỏi
### Những Gì KHÔNG Nên Làm
- Đừng kết hợp refactoring với việc thêm tính năng
- Đừng refactor trong các tình huống khẩn cấp của production
- Đừng refactor code mà bạn không hiểu
- Đừng over-engineer - giữ nó đơn giản
- Đừng refactor tất cả cùng một lúc
---
## Ví Dụ Bắt Đầu Nhanh
### Kịch Bản: Long Method với Duplication
**Trước:**
```javascript
function processOrder(order) {
// 150 dòng code với:
// - Logic xác thực trùng lặp
// - Tính toán nội tuyến
// - Trách nhiệm hỗn hợp
}
```
**Các Bước Refactoring:**
1. **Đảm bảo tests tồn tại** cho processOrder()
2. **Extract** xác thực vào validateOrder()
3. **Test** - nên pass
4. **Extract** tính toán vào calculateOrderTotal()
5. **Test** - nên pass
6. **Extract** thông báo vào notifyCustomer()
7. **Test** - nên pass
8. **Review** - processOrder() giờ điều phối 3 hàm rõ ràng
**Sau:**
```javascript
function processOrder(order) {
validateOrder(order);
const total = calculateOrderTotal(order);
notifyCustomer(order, total);
return { order, total };
}
```
---
## Tài Liệu Tham Khảo
- [Catalog Code Smells](../../../03-skills/refactor/references/code-smells.md) - Danh sách đầy đủ code smells
- [Catalog Refactoring](../../../03-skills/refactor/references/refactoring-catalog.md) - Các kỹ thuật refactoring
- [Mẫu Kế Hoạch Refactoring](../../../03-skills/refactor/templates/refactoring-plan.md) - Mẫu lập kế hoạch
## Scripts
- `scripts/analyze-complexity.py` - Phân tích metrics độ phức tạp code
- `scripts/detect-smells.py` - Phát hiện smell tự động
## Lịch Sử Phiên Bản
- v1.0.0 (2025-01-15): Phiên bản phát hành ban đầu với phương pháp luận Fowler, cách tiếp theo từng giai đoạn, các điểm tham khảo người dùng

1141
vi/04-subagents/README.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,61 @@
---
name: code-reviewer
description: Chuyên gia review code chuyên nghiệp. Sử dụng CHỦ ĐỘNG sau khi viết hoặc sửa đổi code để đảm bảo chất lượng, bảo mật, và khả năng duy trì.
tools: Read, Grep, Glob, Bash
model: inherit
---
# Tác Nhân Code Reviewer / Code Reviewer Agent
Bạn là một reviewer code cao cấp đảm bảo các tiêu chuẩn cao về chất lượng code và bảo mật.
Khi được gọi:
1. Chạy git diff để xem các thay đổi gần đây
2. Tập trung vào các file đã sửa đổi
3. Bắt đầu review ngay lập tức
## Ưu Tiên Review (theo thứ tự)
1. **Vấn Đề Bảo Mật** - Xác thực, ủy quyền, lộ dữ liệu
2. **Vấn Đề Hiệu Suất** - Hoạt động O(n^2), rò rỉ bộ nhớ, truy vấn kém hiệu quả
3. **Chất Lượng Code** - Khả năng đọc, đặt tên, tài liệu hóa
4. **Phủ Vùng Test** - Thiếu tests, các trường hợp ngoại lệ
5. **Mẫu Thiết Kế** - Nguyên tắc SOLID, kiến trúc
## Checklist Review
- Code rõ ràng và dễ đọc
- Hàm và biến được đặt tên tốt
- Không có code trùng lặp
- Xử lý lỗi phù hợp
- Không có secrets hoặc API keys bị lộ
- Xác thực đầu vào được triển khai
- Phủ vùng test tốt
- Các cân nhắc về hiệu suất được giải quyết
## Định Dạng Đầu Ra Review
Đối với mỗi vấn đề:
- **Mức Độ**: Nguy Kịch / Cao / Trung Bình / Thấp
- **Danh Mục**: Bảo Mật / Hiệu Suất / Chất Lượng / Testing / Thiết Kế
- **Vị Trí**: Đường dẫn file và số dòng
- **Mô Tả Vấn Đề**: Điều gì sai và tại sao
- **Khắc Phục Đề Xuất**: Ví dụ code
- **Tác Động**: Cách điều này ảnh hưởng đến hệ thống
Cung cấp feedback được tổ chức theo ưu tiên:
1. Vấn đề nguy kịch (phải sửa)
2. Cảnh báo (nên sửa)
3. Đề xuất (cân nhắc cải thiện)
Bao gồm các ví dụ cụ thể về cách sửa các vấn đề.
## Ví Dụ Review
### Vấn Đề: Vấn Đề Truy Vấn N+1
- **Mức Độ**: Cao
- **Danh Mục**: Hiệu Suất
- **Vị Trí**: src/user-service.ts:45
- **Vấn Đề**: Vòng lặp thực thi truy vấn cơ sở dữ liệu trong mỗi lần lặp
- **Khắc Phục**: Sử dụng JOIN hoặc truy vấn batch
- **Tác Động**: Thời gian phản hồi tăng tuyến tính theo kích thước dữ liệu

View File

@@ -0,0 +1,80 @@
---
name: debugger
description: Chuyên gia debug cho lỗi, thất bại test, và hành vi không mong đợi. Sử dụng CHỦ ĐỘNG khi gặp bất kỳ vấn đề nào.
tools: Read, Edit, Bash, Grep, Glob
model: inherit
---
# Tác Nhân Debugger / Debugger Agent
Bạn là một chuyên gia debug chuyên về phân tích nguyên nhân gốc rễ.
Khi được gọi:
1. Nắm bắt thông báo lỗi và stack trace
2. Xác định các bước tái tạo
3. Cô lập vị trí thất bại
4. Triển khai sửa đổi tối thiểu
5. Xác minh giải pháp hoạt động
## Quy Trình Debug
1. **Phân tích thông báo lỗi và logs**
- Đọc toàn bộ thông báo lỗi
- Kiểm tra stack traces
- Kiểm tra output log gần đây
2. **Kiểm tra các thay đổi code gần đây**
- Chạy git diff để xem các sửa đổi
- Xác định các thay đổi có khả năng gây lỗi
- Review lịch sử commit
3. **Hình thành và kiểm tra các giả thuyết**
- Bắt đầu với nguyên nhân có khả năng nhất
- Thêm logging debug chiến lược
- Kiểm tra trạng thái biến
4. **Cô lập thất bại**
- Thu hẹp đến hàm/dòng cụ thể
- Tạo trường hợp tái tạo tối thiểu
- Xác minh sự cô lập
5. **Triển khai và xác minh sửa đổi**
- Thực hiện các thay đổi tối thiểu cần thiết
- Chạy tests để xác nhận sửa đổi
- Kiểm tra các regressions
## Định Dạng Đầu Ra Debug
Đối với mỗi vấn đề được điều tra:
- **Lỗi**: Thông báo lỗi gốc
- **Nguyên Nhân Gốc**: Giải thích tại sao nó thất bại
- **Bằng Chứng**: Cách bạn xác định nguyên nhân
- **Sửa Đổi**: Các thay đổi code cụ thể được thực hiện
- **Testing**: Cách sửa đổi được xác minh
- **Phòng Ngừa**: Đề xuất để ngăn chặn tái diễn
## Lệnh Debug Phổ Biến
```bash
# Kiểm tra các thay đổi gần đây
git diff HEAD~3
# Tìm kiếm các mẫu lỗi
grep -r "error" --include="*.log"
# Tìm code liên quan
grep -r "functionName" --include="*.ts"
# Chạy test cụ thể
npm test -- --grep "test name"
```
## Checklist Điều Tra
- [ ] Thông báo lỗi được nắm bắt
- [ ] Stack trace được phân tích
- [ ] Các thay đổi gần đây được review
- [ ] Nguyên nhân gốc được xác định
- [ ] Sửa đổi được triển khai
- [ ] Tests pass
- [ ] Không có regressions được giới thiệu

View File

@@ -0,0 +1,98 @@
---
name: documentation-writer
description: Chuyên gia tài liệu kỹ thuật cho API docs, hướng dẫn người dùng, và tài liệu kiến trúc.
tools: Read, Write, Grep
model: inherit
---
# Tác Nhân Documentation Writer / Documentation Writer Agent
Bạn là một technical writer tạo ra tài liệu rõ ràng, toàn diện.
Khi được gọi:
1. Phân tích code hoặc tính năng cần tài liệu hóa
2. Xác định đối tượng mục tiêu
3. Tạo tài liệu theo quy ước dự án
4. Xác minh độ chính xác đối với code thực tế
## Các Loại Tài Liệu
- Tài liệu API với ví dụ
- Hướng dẫn người dùng và tutorials
- Tài liệu kiến trúc
- Các mục changelog
- Cải thiện comment code
## Tiêu Chuẩn Tài Liệu
1. **Độ Rõ Ràng** - Sử dụng ngôn ngữ đơn giản, rõ ràng
2. **Ví Dụ** - Bao gồm các ví dụ code thực tế
3. **Tính Hoàn Chỉnh** - Bao gồm tất cả các tham số và trả về
4. **Cấu Trúc** - Sử dụng format nhất quán
5. **Độ Chính Xác** - Xác minh đối với code thực tế
## Các Phần Tài Liệu
### Đối Với APIs
- Mô tả
- Tham số (với kiểu)
- Trả về (với kiểu)
- Ném ra (các lỗi có thể xảy ra)
- Ví dụ (curl, JavaScript, Python)
- Các endpoint liên quan
### Đối Với Tính Năng
- Tổng quan
- Điều kiện tiên quyết
- Hướng dẫn từng bước
- Kết quả mong đợi
- Xử lý sự cố
- Các chủ đề liên quan
## Định Dạng Đầu Ra
Đối với mỗi tài liệu được tạo:
- **Loại**: API / Hướng Dẫn / Kiến Trúc / Changelog
- **File**: Đường dẫn file tài liệu
- **Các Phần**: Danh sách các phần được bao gồm
- **Ví Dụ**: Số lượng ví dụ code được bao gồm
## Ví Dụ Tài Liệu API
```markdown
## GET /api/users/:id
Truy xuất người dùng bằng định danh duy nhất của họ.
### Tham Số
| Tên | Kiểu | Bắt Buộc | Mô Tả |
|------|------|----------|-------------|
| id | string | Có | Định danh duy nhất của người dùng |
### Phản Hồi
```json
{
"id": "abc123",
"name": "John Doe",
"email": "john@example.com"
}
```
### Lỗi
| Mã | Mô Tả |
|------|-------------|
| 404 | Không tìm thấy người dùng |
| 401 | Chưa được ủy quyền |
### Ví Dụ
```bash
curl -X GET https://api.example.com/api/users/abc123 \
-H "Authorization: Bearer <token>"
```
```

View File

@@ -0,0 +1,78 @@
---
name: implementation-agent
description: Chuyên gia triển khai full-stack cho phát triển tính năng. Có toàn quyền truy cập công cụ cho triển khai end-to-end.
tools: Read, Write, Edit, Bash, Grep, Glob
model: inherit
---
# Tác Nhân Implementation / Implementation Agent
Bạn là một nhà phát triển cao cấp triển khai các tính năng từ thông số kỹ thuật.
Tác nhân này có đầy đủ các khả năng:
- Đọc thông số kỹ thuật và code hiện có
- Viết file code mới
- Chỉnh sửa file hiện có
- Chạy các lệnh build
- Tìm kiếm codebase
- Tìm file khớp với mẫu
## Quy Trình Triển Khai
Khi được gọi:
1. Hiểu rõ các yêu cầu
2. Phân tích các mẫu codebase hiện có
3. Lập kế hoạch cách tiếp cận triển khai
4. Triển khai tăng dần
5. Test trong khi đi
6. Dọn dẹp và refactor
## Hướng Dẫn Triển Khai
### Chất Lượng Code
- Theo các quy ước dự án hiện có
- Viết code tự tài liệu hóa
- Chỉ thêm comments ở nơi logic phức tạp
- Giữ các hàm nhỏ và tập trung
- Sử dụng tên biến có ý nghĩa
### Tổ Chức File
- Đặt file theo cấu trúc dự án
- Nhóm chức năng liên quan
- Theo các quy ước đặt tên
- Tránh các thư mục lồng nhau quá sâu
### Xử Lý Lỗi
- Xử lý tất cả các trường hợp lỗi
- Cung cấp thông báo lỗi có ý nghĩa
- Ghi nhật ký lỗi phù hợp
- Fail một cách êm đẹp
### Testing
- Viết tests cho chức năng mới
- Đảm bảo các tests hiện có pass
- Bao gồm các trường hợp ngoại lệ
- Bao gồm integration tests cho APIs
## Định Dạng Đầu Ra
Đối với mỗi nhiệm vụ triển khai:
- **Files Được Tạo**: Danh sách file mới
- **Files Được Sửa Đổi**: Danh sách file đã thay đổi
- **Tests Được Thêm**: Đường dẫn file test
- **Trạng Thái Build**: Pass/Fail
- **Ghi Chú**: Bất kỳ cân nhắc quan trọng nào
## Checklist Triển Khai
Trước khi đánh dấu hoàn thành:
- [ ] Code theo các quy ước dự án
- [ ] Tất cả tests pass
- [ ] Build thành công
- [ ] Không có lỗi linting
- [ ] Các trường hợp ngoại lệ được xử lý
- [ ] Xử lý lỗi được triển khai

View File

@@ -0,0 +1,75 @@
---
name: secure-reviewer
description: Chuyên gia review code tập trung vào bảo mật với quyền hạn tối thiểu. Quyền truy cập read-only đảm bảo các kiểm tra bảo mật an toàn.
tools: Read, Grep
model: inherit
---
# Code Reviewer Bảo Mật / Secure Code Reviewer
Bạn là một chuyên gia bảo mật tập trung độc quyền vào việc xác định các lỗ hổng.
Tác nhân này có quyền hạn tối thiểu theo thiết kế:
- Có thể đọc file để phân tích
- Có thể tìm kiếm mẫu
- Không thể thực thi code
- Không thể sửa đổi file
- Không thể chạy tests
Điều này đảm bảo reviewer không thể vô tình làm hỏng bất cứ điều gì trong quá trình kiểm tra bảo mật.
## Tập Trung Review Bảo Mật
1. **Vấn Đề Xác Thực**
- Chính sách mật khẩu yếu
- Thiếu xác thực đa yếu tố
- Các lỗi quản lý phiên
2. **Vấn Đề Ủy Quyền**
- Kiểm soát truy cập bị phá vỡ
- Leo thang đặc quyền
- Thiếu các kiểm tra vai trò
3. **Lộ Dữ Liệu**
- Dữ liệu nhạy cảm trong logs
- Lưu trữ không được mã hóa
- Lộ API key
- Xử lý PII (thông tin nhận dạng cá nhân)
4. **Lỗ Hổng Tiêm Nhiễu**
- SQL injection
- Command injection
- XSS (Cross-Site Scripting)
- LDAP injection
5. **Vấn Đề Cấu Hình**
- Chế độ debug trong production
- Thông tin xác thực mặc định
- Các mặc định không an toàn
## Các Mẫu Để Tìm Kiếm
```bash
# Secrets được hardcode
grep -r "password\s*=" --include="*.js" --include="*.ts"
grep -r "api_key\s*=" --include="*.py"
grep -r "SECRET" --include="*.env*"
# Rủi ro SQL injection
grep -r "query.*\$" --include="*.js"
grep -r "execute.*%" --include="*.py"
# Rủi ro command injection
grep -r "exec(" --include="*.js"
grep -r "os.system" --include="*.py"
```
## Định Dạng Đầu Ra
Đối với mỗi lỗ hổng:
- **Mức Độ**: Nguy Kịch / Cao / Trung Bình / Thấp
- **Loại**: Danh mục OWASP
- **Vị Trí**: Đường dẫn file và số dòng
- **Mô Tả**: Lỗ hổng là gì
- **Rủi Ro**: Tác động tiềm năng nếu bị khai thác
- **Khắc Phục**: Cách sửa nó

View File

@@ -0,0 +1,74 @@
---
name: test-engineer
description: Chuyên gia tự động hóa test để viết các tests toàn diện. Sử dụng CHỦ ĐỘNG khi các tính năng mới được triển khai hoặc code được sửa đổi.
tools: Read, Write, Bash, Grep
model: inherit
---
# Tác Nhân Test Engineer / Test Engineer Agent
Bạn là một kỹ sư test chuyên gia chuyên về phủ vùng test toàn diện.
Khi được gọi:
1. Phân tích code cần test
2. Xác định các đường dẫn quan trọng và trường hợp ngoại lệ
3. Viết tests theo các quy ước dự án
4. Chạy tests để xác minh chúng pass
## Chiến Lược Testing
1. **Unit Tests** - Các hàm/method riêng lẻ tách biệt
2. **Integration Tests** - Tương tác thành phần
3. **End-to-End Tests** - Các quy trình hoàn chỉnh
4. **Trường Hợp Ngoại Lệ** - Điều kiện biên, giá trị null, bộ sưu tập rỗng
5. **Kịch Bản Lỗi** - Xử lý thất bại, đầu vào không hợp lệ
## Yêu Cầu Test
- Sử dụng framework test hiện có của dự án (Jest, pytest, v.v.)
- Bao gồm setup/teardown cho mỗi test
- Mock các dependencies bên ngoài
- Tài liệu hóa mục đích test với mô tả rõ ràng
- Bao gồm các khẳng định hiệu suất khi liên quan
## Yêu Cầu Phủ Vùng
- Tối thiểu 80% phủ vùng code
- 100% cho các đường dẫn quan trọng (xác thực, thanh toán, xử lý dữ liệu)
- Báo cáo các khu vực thiếu phủ vùng
## Định Dạng Đầu Ra Test
Đối với mỗi file test được tạo:
- **File**: Đường dẫn file test
- **Tests**: Số lượng trường hợp test
- **Phủ Vùng**: Cải thiện phủ vùng ước tính
- **Đường Dẫn Quan Trọng**: Các đường dẫn quan trọng được bao phủ
## Ví Dụ Cấu Trúc Test
```javascript
describe('Tính Năng: Xác Thực Người Dùng', () => {
beforeEach(() => {
// Setup
});
afterEach(() => {
// Cleanup
});
it('nên xác thực thông tin hợp lệ', async () => {
// Arrange (Sắp xếp)
// Act (Thực hiện)
// Assert (Khẳng định)
});
it('nên từ chối thông tin không hợp lệ', async () => {
// Test trường hợp lỗi
});
it('nên xử lý trường hợp ngoại lệ: mật khẩu rỗng', async () => {
// Test trường hợp ngoại lệ
});
});
```

1112
vi/05-mcp/README.md Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["@modelcontextprotocol/server-database"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost/mydb"
}
}
}
}

View File

@@ -0,0 +1,8 @@
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
}
}
}

11
vi/05-mcp/github-mcp.json Normal file
View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}

29
vi/05-mcp/multi-mcp.json Normal file
View File

@@ -0,0 +1,29 @@
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"database": {
"command": "npx",
"args": ["@modelcontextprotocol/server-database"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
},
"slack": {
"command": "npx",
"args": ["@modelcontextprotocol/server-slack"],
"env": {
"SLACK_TOKEN": "${SLACK_TOKEN}"
}
},
"filesystem": {
"command": "npx",
"args": ["@modelcontextprotocol/server-filesystem", "/home/user/projects"]
}
}
}

828
vi/06-hooks/README.md Normal file
View File

@@ -0,0 +1,828 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Hooks / Hooks
Hooks là các script tự động thực thi để phản hồi các sự kiện cụ thể trong các phiên Claude Code. Chúng cho phép tự động hóa, xác thực, quản lý quyền, và workflows tùy chỉnh.
## Tổng Quan / Overview
Hooks là các hành động tự động (lệnh shell, HTTP webhooks, prompts LLM, hoặc đánh giá subagent) thực thi tự động khi các sự kiện cụ thể xảy ra trong Claude Code. Chúng nhận đầu vào JSON và giao tiếp kết quả qua exit codes và đầu ra JSON.
**Tính năng chính:**
- Tự động hóa dựa trên sự kiện
- Đầu vào/ra dựa trên JSON
- Hỗ trợ cho các loại hook command, prompt, HTTP, và agent
- Khớp mẫu cho các hooks cụ thể theo công cụ
## Cấu Hình / Configuration
Hooks được cấu hình trong các file settings với cấu trúc cụ thể:
- `~/.claude/settings.json` - Cài đặt người dùng (tất cả projects)
- `.claude/settings.json` - Cài đặt project (có thể chia sẻ, được commit)
- `.claude/settings.local.json` - Cài đặt project local (không được commit)
- Managed policy - Cài đặt toàn tổ chức
- Plugin `hooks/hooks.json` - Hooks scoped plugin
- Skill/Agent frontmatter - Hooks vòng đời component
### Cấu Trúc Cấu Hình Cơ Bản / Basic Configuration Structure
```json
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "your-command-here",
"timeout": 60
}
]
}
]
}
}
```
**Các trường chính:**
| Trường | Mô Tả | Ví Dụ |
|-------|-------------|---------|
| `matcher` | Mẫu để khớp tên công cụ (phân biệt hoa/thường) | `"Write"`, `"Edit\|Write"`, `"*"` |
| `hooks` | Mảng định nghĩa hook | `[{ "type": "command", ... }]` |
| `type` | Loại hook: `"command"` (bash), `"prompt"` (LLM), `"http"` (webhook), hoặc `"agent"` (subagent) | `"command"` |
| `command` | Lệnh shell để thực thi | `"$CLAUDE_PROJECT_DIR/.claude/hooks/format.sh"` |
| `timeout` | Timeout tùy chọn tính bằng giây (mặc định 60) | `30` |
| `once` | Nếu `true`, chạy hook chỉ một lần mỗi phiên | `true` |
### Các Mẫu Matcher / Matcher Patterns
| Mẫu | Mô Tả | Ví Dụ |
|---------|-------------|---------|
| Chuỗi chính xác | Khớp công cụ cụ thể | `"Write"` |
| Mẫu regex | Khớp nhiều công cụ | `"Edit\|Write"` |
| Wildcard | Khớp tất cả công cụ | `"*"` hoặc `""` |
| Công cụ MCP | Mẫu server và công cụ | `"mcp__memory__.*"` |
## Các Loại Hook / Hook Types
Claude Code hỗ trợ bốn loại hook:
### Command Hooks / Hooks Lệnh
Loại hook mặc định. Thực thi một lệnh shell và giao tiếp qua JSON stdin/stdout và exit codes.
```json
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate.py\"",
"timeout": 60
}
```
### HTTP Hooks / Hooks HTTP
> Thêm vào v2.1.63.
Các endpoints webhook từ xa nhận cùng đầu vào JSON như command hooks. HTTP hooks POST JSON đến URL và nhận phản hồi JSON. HTTP hooks được định tuyến qua sandbox khi sandboxing được bật. Nội suy biến môi trường trong URLs yêu cầu danh sách `allowedEnvVars` rõ ràng để bảo mật.
```json
{
"hooks": {
"PostToolUse": [{
"type": "http",
"url": "https://my-webhook.example.com/hook",
"matcher": "Write"
}]
}
}
```
**Các thuộc tính chính:**
- `"type": "http"` -- xác định đây là một HTTP hook
- `"url"` -- URL endpoint webhook
- Được định tuyến qua sandbox khi sandbox được bật
- Yêu cầu danh sách `allowedEnvVars` rõ ràng cho bất kỳ nội suy biến môi trường nào trong URL
### Prompt Hooks / Hooks Prompt
Prompts được đánh giá bởi LLM nơi nội dung hook là một prompt mà Claude đánh giá. Chủ yếu được sử dụng với các sự kiện `Stop``SubagentStop` để kiểm tra hoàn thành tác vụ thông minh.
```json
{
"type": "prompt",
"prompt": "Evaluate if Claude completed all requested tasks.",
"timeout": 30
}
```
LLM đánh giá prompt và trả về một quyết định có cấu trúc (xem [Prompt-Based Hooks](#hooks-dựa-trên-prompt--prompt-based-hooks) để biết chi tiết).
### Agent Hooks / Hooks Agent
Hooks xác thực dựa trên subagent mà spawn một agent chuyên dụng để đánh giá điều kiện hoặc thực hiện các kiểm tra phức tạp. Khác với prompt hooks (đánh giá LLM một turn), agent hooks có thể sử dụng các công cụ và thực hiện suy luận đa bước.
```json
{
"type": "agent",
"prompt": "Verify the code changes follow our architecture guidelines. Check the relevant design docs and compare.",
"timeout": 120
}
```
**Các thuộc tính chính:**
- `"type": "agent"` -- xác định đây là một agent hook
- `"prompt"` -- mô tả nhiệm vụ cho subagent
- Agent có thể sử dụng các công cụ (Read, Grep, Bash, v.v.) để thực hiện đánh giá của nó
- Trả về một quyết định có cấu trúc tương tự như prompt hooks
## Các Sự Kiện Hook / Hook Events
Claude Code hỗ trợ **25 sự kiện hook**:
| Sự Kiện | Khi Được Kích Hoạt | Matcher Input | Có Chặn | Sử Dụng Phổ Biến |
|-------|---------------|---------------|-----------|------------|
| **SessionStart** | Phiên bắt đầu/tiếp tục/xóa/dồn | startup/resume/clear/compact | Không | Thiết lập môi trường |
| **InstructionsLoaded** | Sau khi CLAUDE.md hoặc file rules được tải | (none) | Không | Sửa đổi/bộ lọc hướng dẫn |
| **UserPromptSubmit** | Người dùng gửi prompt | (none) | Có | Xác thực prompts |
| **PreToolUse** | Trước khi thực thi công cụ | Tên công cụ | Có (allow/deny/ask) | Xác thực, sửa đổi đầu vào |
| **PermissionRequest** | Hộp thoại quyền được hiển thị | Tên công cụ | Có | Tự động phê duyệt/từ chối |
| **PostToolUse** | Sau khi công cụ thành công | Tên công cụ | Không | Thêm ngữ cảnh, feedback |
| **PostToolUseFailure** | Thực thi công cụ thất bại | Tên công cụ | Không | Xử lý lỗi, logging |
| **Notification** | Thông báo được gửi | Loại thông báo | Không | Thông báo tùy chỉnh |
| **SubagentStart** | Subagent được spawn | Tên loại agent | Không | Thiết lập subagent |
| **SubagentStop** | Subagent hoàn thành | Tên loại agent | Có | Xác thực subagent |
| **Stop** | Claude hoàn thành phản hồi | (none) | Có | Kiểm tra hoàn thành tác vụ |
| **StopFailure** | Lỗi API kết thúc turn | (none) | Không | Phục hồi lỗi, logging |
| **TeammateIdle** | Đồng nghiệp nhóm agent rảnh | (none) | Có | Phối hợp đồng nghiệp |
| **TaskCompleted** | Nhiệm vụ được đánh dấu hoàn thành | (none) | Có | Hành động sau tác vụ |
| **TaskCreated** | Nhiệm vụ được tạo qua TaskCreate | (none) | Không | Theo dõi nhiệm vụ, logging |
| **ConfigChange** | File config thay đổi | (none) | Có (trừ policy) | Phản hồi cập nhật config |
| **CwdChanged** | Thư mục làm việc thay đổi | (none) | Không | Thiết lập cụ thể thư mục |
| **FileChanged** | File được watch thay đổi | (none) | Không | Giám sát file, rebuild |
| **PreCompact** | Trước khi dồn ngữ cảnh | manual/auto | Không | Hành động pre-dồn |
| **PostCompact** | Sau khi dồn hoàn thành | (none) | Không | Hành động post-dồn |
| **WorktreeCreate** | Worktree đang được tạo | (none) | Có (trả về path) | Khởi tạo worktree |
| **WorktreeRemove** | Worktree đang được xóa | (none) | Không | Dọn dẹp worktree |
| **Elicitation** | MCP server yêu cầu đầu vào người dùng | (none) | Có | Xác thực đầu vào |
| **ElicitationResult** | Người dùng phản hồi elicitation | (none) | Có | Xử lý phản hồi |
| **SessionEnd** | Phiên kết thúc | (none) | Không | Dọn dẹp, logging cuối |
### PreToolUse
Chạy sau khi Claude tạo tham số công cụ và trước khi xử lý. Sử dụng điều này để xác thực hoặc sửa đổi đầu vào công cụ.
**Cấu Hình:**
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py"
}
]
}
]
}
}
```
**Các matcher phổ biến:** `Task`, `Bash`, `Glob`, `Grep`, `Read`, `Edit`, `Write`, `WebFetch`, `WebSearch`
**Điều khiển đầu ra:**
- `permissionDecision`: `"allow"`, `"deny"`, hoặc `"ask"`
- `permissionDecisionReason`: Giải thích cho quyết định
- `updatedInput`: Các tham số đầu vào công cụ đã sửa đổi
### PostToolUse
Chạy ngay sau khi công cụ hoàn thành. Sử dụng để xác minh, logging, hoặc cung cấp ngữ cảnh trở lại Claude.
**Cấu Hình:**
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/security-scan.py"
}
]
}
]
}
}
```
**Điều khiển đầu ra:**
- Quyết định `"block"` nhắc Claude với feedback
- `additionalContext`: Ngữ cảnh được thêm vào cho Claude
### UserPromptSubmit
Chạy khi người dùng gửi prompt, trước khi Claude xử lý nó.
**Cấu Hình:**
```json
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-prompt.py"
}
]
}
]
}
}
```
**Điều khiển đầu ra:**
- `decision`: `"block"` để ngăn chặn xử lý
- `reason`: Giải thích nếu bị chặn
- `additionalContext`: Ngữ cảnh được thêm vào prompt
### Stop và SubagentStop / Stop and SubagentStop
Chạy khi Claude hoàn thành phản hồi (Stop) hoặc một subagent hoàn thành (SubagentStop). Hỗ trợ đánh giá dựa trên prompt để kiểm tra hoàn thành tác vụ thông minh.
**Trường đầu vào thêm:** Cả hai hooks `Stop``SubagentStop` nhận một trường `last_assistant_message` trong đầu vào JSON của chúng, chứa thông báo cuối cùng từ Claude hoặc subagent trước khi dừng. Điều này hữu ích để đánh giá hoàn thành tác vụ.
**Cấu Hình:**
```json
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Evaluate if Claude completed all requested tasks.",
"timeout": 30
}
]
}
]
}
}
```
### SubagentStart
Chạy khi một subagent bắt đầu thực thi. Matcher input là tên loại agent, cho phép hooks nhắm đến các loại subagent cụ thể.
**Cấu Hình:**
```json
{
"hooks": {
"SubagentStart": [
{
"matcher": "code-review",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/subagent-init.sh"
}
]
}
]
}
}
```
### SessionStart
Chạy khi phiên bắt đầu hoặc tiếp tục. Có thể persist các biến môi trường.
**Matchers:** `startup`, `resume`, `clear`, `compact`
**Tính năng đặc biệt:** Sử dụng `CLAUDE_ENV_FILE` để persist các biến môi trường (cũng có sẵn trong các hooks `CwdChanged``FileChanged`):
```bash
#!/bin/bash
if [ -n "$CLAUDE_ENV_FILE" ]; then
echo 'export NODE_ENV=development' >> "$CLAUDE_ENV_FILE"
fi
exit 0
```
### SessionEnd
Chạy khi phiên kết thúc để thực hiện dọn dẹp hoặc logging cuối cùng. Không thể chấm dứt sự kết thúc.
**Các giá trị trường reason:**
- `clear` - Người dùng xóa phiên
- `logout` - Người dùng đăng xuất
- `prompt_input_exit` - Người dùng thoát qua đầu vào prompt
- `other` - Lý do khác
**Cấu Hình:**
```json
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-cleanup.sh\""
}
]
}
]
}
}
```
### Sự Kiện Notification / Notification Event
Các matcher được cập nhật cho các sự kiện thông báo:
- `permission_prompt` - Thông báo yêu cầu quyền
- `idle_prompt` - Thông báo trạng thái rảnh
- `auth_success` - Xác thực thành công
- `elicitation_dialog` - Hộp thoại được hiển thị cho người dùng
## Hooks Scoped Component / Component-Scoped Hooks
Hooks có thể được gắn vào các component cụ thể (skills, agents, commands) trong frontmatter của chúng:
**Trong SKILL.md, agent.md, hoặc command.md:**
```yaml
---
name: secure-operations
description: Perform operations with security checks
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/check.sh"
once: true # Chỉ chạy một lần mỗi phiên
---
```
**Các sự kiện được hỗ trợ cho component hooks:** `PreToolUse`, `PostToolUse`, `Stop`
Điều này cho phép định nghĩa hooks trực tiếp trong component sử dụng chúng, giữ code liên quan cùng nhau.
### Hooks trong Frontmatter Subagent / Hooks in Subagent Frontmatter
Khi một hook `Stop` được định nghĩa trong frontmatter của một subagent, nó tự động được chuyển đổi thành một hook `SubagentStop` scoped cho subagent đó. Điều này đảm bảo rằng hook stop chỉ kích hoạt khi subagent cụ thể đó hoàn thành, thay vì khi phiên chính dừng.
```yaml
---
name: code-review-agent
description: Automated code review subagent
hooks:
Stop:
- hooks:
- type: prompt
prompt: "Verify the code review is thorough and complete."
# Hook Stop ở trên tự chuyển thành SubagentStop cho subagent này
---
```
## Sự Kiện PermissionRequest / PermissionRequest Event
Xử lý các yêu cầu quyền với định dạng đầu ra tùy chỉnh:
```json
{
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
"decision": {
"behavior": "allow|deny",
"updatedInput": {},
"message": "Custom message",
"interrupt": false
}
}
}
```
## Đầu Vào Và Đầu Ra Hook / Hook Input and Output
### Đầu Vào JSON (qua stdin) / JSON Input (via stdin)
Tất cả hooks nhận đầu vào JSON qua stdin:
```json
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/current/working/directory",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.js",
"content": "..."
},
"tool_use_id": "toolu_01ABC123...",
"agent_id": "agent-abc123",
"agent_type": "main",
"worktree": "/path/to/worktree"
}
```
**Các trường phổ biến:**
| Trường | Mô Tả |
|-------|-------------|
| `session_id` | Định danh phiên duy nhất |
| `transcript_path` | Đường dẫn đến file transcript hội thoại |
| `cwd` | Thư mục làm việc hiện tại |
| `hook_event_name` | Tên của sự kiện kích hoạt hook |
| `agent_id` | Định danh của agent chạy hook này |
| `agent_type` | Loại agent (`"main"`, tên loại subagent, v.v.) |
| `worktree` | Đường dẫn đến git worktree, nếu agent chạy trong một |
### Exit Codes
| Exit Code | Ý Nghĩa | Hành Vi |
|-----------|---------|----------|
| **0** | Thành công | Tiếp tục, phân tích cú pháp JSON stdout |
| **2** | Lỗi chặn | Chặn thao tác, stderr được hiển thị như lỗi |
| **Khác** | Lỗi không chặn | Tiếp tục, stderr được hiển thị trong chế độ verbose |
### Đầu Ra JSON (stdout, exit code 0) / JSON Output (stdout, exit code 0)
```json
{
"continue": true,
"stopReason": "Optional message if stopping",
"suppressOutput": false,
"systemMessage": "Optional warning message",
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "File is in allowed directory",
"updatedInput": {
"file_path": "/modified/path.js"
}
}
}
```
## Các Biến Môi Trường / Environment Variables
| Biến | Khả Dụng | Mô Tả |
|----------|-------------|-------------|
| `CLAUDE_PROJECT_DIR` | Tất cả hooks | Đường dẫn tuyệt đối đến thư mục gốc project |
| `CLAUDE_ENV_FILE` | SessionStart, CwdChanged, FileChanged | Đường dẫn file để persist env vars |
| `CLAUDE_CODE_REMOTE` | Tất cả hooks | `"true"` nếu chạy trong môi trường từ xa |
| `${CLAUDE_PLUGIN_ROOT}` | Hooks plugin | Đường dẫn đến thư mục plugin |
| `${CLAUDE_PLUGIN_DATA}` | Hooks plugin | Đường dẫn đến thư mục dữ liệu plugin |
| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | Hooks SessionEnd | Timeout có thể cấu hình tính bằng mili giây cho hooks SessionEnd (ghi đè mặc định) |
## Hooks Dựa Trên Prompt / Prompt-Based Hooks
Đối với các sự kiện `Stop``SubagentStop`, bạn có thể sử dụng đánh giá dựa trên LLM:
```json
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Review if all tasks are complete. Return your decision.",
"timeout": 30
}
]
}
]
}
}
```
**Schema Phản Hồi LLM:**
```json
{
"decision": "approve",
"reason": "All tasks completed successfully",
"continue": false,
"stopReason": "Task complete"
}
```
## Ví Dụ / Examples
### Ví Dụ 1: Trình Xác Thực Lệnh Bash (PreToolUse) / Example 1: Bash Command Validator
**File:** `.claude/hooks/validate-bash.py`
```python
#!/usr/bin/env python3
import json
import sys
import re
BLOCKED_PATTERNS = [
(r"\brm\s+-rf\s+/", "Blocking dangerous rm -rf / command"),
(r"\bsudo\s+rm", "Blocking sudo rm command"),
]
def main():
input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name", "")
if tool_name != "Bash":
sys.exit(0)
command = input_data.get("tool_input", {}).get("command", "")
for pattern, message in BLOCKED_PATTERNS:
if re.search(pattern, command):
print(message, file=sys.stderr)
sys.exit(2) # Exit 2 = blocking error
sys.exit(0)
if __name__ == "__main__":
main()
```
### Ví Dụ 2: Bộ Quét Bảo Mật (PostToolUse) / Example 2: Security Scanner
**File:** `.claude/hooks/security-scan.py`
```python
#!/usr/bin/env python3
import json
import sys
import re
SECRET_PATTERNS = [
(r"password\s*=\s*['\"][^'\"]+['\"]", "Potential hardcoded password"),
(r"api[_-]?key\s*=\s*['\"][^'\"]+['\"]", "Potential hardcoded API key"),
]
def main():
input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name", "")
if tool_name not in ["Write", "Edit"]:
sys.exit(0)
tool_input = input_data.get("tool_input", {})
content = tool_input.get("content", "") or tool_input.get("new_string", "")
file_path = tool_input.get("file_path", "")
warnings = []
for pattern, message in SECRET_PATTERNS:
if re.search(pattern, content, re.IGNORECASE):
warnings.append(message)
if warnings:
output = {
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": f"Security warnings for {file_path}: " + "; ".join(warnings)
}
}
print(json.dumps(output))
sys.exit(0)
if __name__ == "__main__":
main()
```
### Ví Dụ 3: Tự Động Format Code (PostToolUse) / Example 3: Auto-Format Code
**File:** `.claude/hooks/format-code.sh`
```bash
#!/bin/bash
# Đọc JSON từ stdin
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('tool_name', ''))")
FILE_PATH=$(echo "$INPUT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('tool_input', {}).get('file_path', ''))")
if [ "$TOOL_NAME" != "Write" ] && [ "$TOOL_NAME" != "Edit" ]; then
exit 0
fi
# Format dựa trên phần mở rộng file
case "$FILE_PATH" in
*.js|*.jsx|*.ts|*.tsx|*.json)
command -v prettier &>/dev/null && prettier --write "$FILE_PATH" 2>/dev/null
;;
*.py)
command -v black &>/dev/null && black "$FILE_PATH" 2>/dev/null
;;
*.go)
command -v gofmt &>/dev/null && gofmt -w "$FILE_PATH" 2>/dev/null
;;
esac
exit 0
```
### Ví Dụ 4: Trình Xác Thực Prompt (UserPromptSubmit) / Example 4: Prompt Validator
**File:** `.claude/hooks/validate-prompt.py`
```python
#!/usr/bin/env python3
import json
import sys
import re
BLOCKED_PATTERNS = [
(r"delete\s+(all\s+)?database", "Dangerous: database deletion"),
(r"rm\s+-rf\s+/", "Dangerous: root deletion"),
]
def main():
input_data = json.load(sys.stdin)
prompt = input_data.get("user_prompt", "") or input_data.get("prompt", "")
for pattern, message in BLOCKED_PATTERNS:
if re.search(pattern, prompt, re.IGNORECASE):
output = {
"decision": "block",
"reason": f"Blocked: {message}"
}
print(json.dumps(output))
sys.exit(0)
sys.exit(0)
if __name__ == "__main__":
main()
```
### Ví Dụ 5: Stop Hook Thông Minh (Dựa Trên Prompt) / Example 5: Intelligent Stop Hook
```json
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Review if Claude completed all requested tasks. Check: 1) Were all files created/modified? 2) Were there unresolved errors? If incomplete, explain what's missing.",
"timeout": 30
}
]
}
]
}
}
```
## Hooks Plugin / Plugin Hooks
Plugins có thể bao gồm hooks trong file `hooks/hooks.json` của chúng:
**File:** `plugins/hooks/hooks.json`
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PLUGIN_ROOT}/scripts/validate.sh"
}
]
}
]
}
}
```
**Các Biến Môi Trường Trong Hooks Plugin:**
- `${CLAUDE_PLUGIN_ROOT}` - Đường dẫn đến thư mục plugin
- `${CLAUDE_PLUGIN_DATA}` - Đường dẫn đến thư mục dữ liệu plugin
Điều này cho phép các plugins bao gồm các hook xác thực và tự động hóa tùy chỉnh.
## Hooks Công Cụ MCP / MCP Tool Hooks
Các công cụ MCP theo mẫu `mcp__<server>__<tool>`:
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__memory__.*",
"hooks": [
{
"type": "command",
"command": "echo '{\"systemMessage\": \"Memory operation logged\"}'"
}
]
}
]
}
}
```
## Cân Nhắc Bảo Mật / Security Considerations
### Tuyên Bố Từ Chối Trách Nhiệm / Disclaimer
**SỬ DỤNG VỚI RỦI RO RIÊNG CỦA BẠN**: Hooks thực thi các lệnh shell tùy ý. Bạn chịu trách nhiệm duy nhất cho:
- Các lệnh bạn cấu hình
- Quyền truy cập/sửa đổi file
- Mất dữ liệu hoặc hư hại hệ thống tiềm ẩn
- Testing hooks trong môi trường an toàn trước khi sử dụng production
### Ghi Chú Bảo Mật / Security Notes
- **Cần tin cậy workspace:** Các output commands hook `statusLine``fileSuggestion` bây giờ yêu cầu chấp nhận tin cậy workspace trước khi chúng có hiệu lực.
- **HTTP hooks và biến môi trường:** HTTP hooks yêu cầu danh sách `allowedEnvVars` rõ ràng để sử dụng nội suy biến môi trường trong URLs. Điều này ngăn chặn lộ vô ý các biến môi trường nhạy cảm đến các endpoints từ xa.
- **Phân cấp settings được quản lý:** Cài đặt `disableAllHooks` bây giờ tôn trọng phân cấp settings được quản lý, nghĩa là settings cấp tổ chức có thể thực thi vô hiệu hóa hook mà người dùng cá nhân không thể ghi đè.
### Thực Hành Tốt Nhất / Best Practices
| Nên | Không Nên |
|-----|-------|
| Xác thực và vệ sinh tất cả đầu vào | Tin tưởng dữ liệu đầu vào mù quáng |
| Trích dẫn biến shell: `"$VAR"` | Sử dụng không trích dẫn: `$VAR` |
| Chặn đường dẫn path traversal (`..`) | Cho phép các đường dẫn tùy ý |
| Sử dụng đường dẫn tuyệt đối với `$CLAUDE_PROJECT_DIR` | Hardcode các đường dẫn |
| Bỏ qua các file nhạy cảm (`.env`, `.git/`, keys) | Xử lý tất cả các files |
| Test hooks trong cô lập trước | Triển khai hooks chưa được test |
| Sử dụng `allowedEnvVars` rõ ràng cho HTTP hooks | Lộ tất cả env vars cho webhooks |
## Gỡ Lỗi / Debugging
### Kích Hoạt Chế Độ Debug / Enable Debug Mode
Chạy Claude với cờ debug để xem logs chi tiết hook:
```bash
claude --debug
```
### Chế Độ Verbose / Verbose Mode
Sử dụng `Ctrl+O` trong Claude Code để kích hoạt chế độ verbose và xem tiến độ thực thi hook.
### Test Hooks Độc Lập / Test Hooks Independently
```bash
# Test với đầu vào JSON mẫu
echo '{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}' | python3 .claude/hooks/validate-bash.py
# Kiểm tra exit code
echo $?
```
## Cài Đặt / Installation
### Bước 1: Tạo Thư Mục Hooks
```bash
mkdir -p ~/.claude/hooks
```
### Bước 2: Sao Chép Hooks Ví Dụ
```bash
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
```
### Bước 3: Cấu Hình Trong Settings
Chỉnh sửa `~/.claude/settings.json` hoặc `.claude/settings.json` với cấu hình hook được hiển thị ở trên.
## Các Khái Niệm Liên Quan / Related Concepts
- **[Checkpoints và Rewind](../08-checkpoints/)** - Lưu và khôi phục trạng thái hội thoại
- **[Slash Commands](../01-slash-commands/)** - Tạo các lệnh slash tùy chỉnh
- **[Skills](../03-skills/)** - Các khả năng tự động có thể tái sử dụng
- **[Subagents](../04-subagents/)** - Thực thi nhiệm vụ được ủy quyền
- **[Plugins](../07-plugins/)** - Các gói mở rộng được đóng gói
- **[Tính Năng Nâng Cao](../09-advanced-features/)** - Khám phá các khả năng nâng cao của Claude Code
## Tài Nguyên Thêm / Additional Resources
- **[Tài Liệu Hooks Chính Thức](https://code.claude.com/docs/en/hooks)** - Tham chiếu hooks hoàn chỉnh
- **[CLI Reference](https://code.claude.com/docs/en/cli-reference)** - Tài liệu giao diện dòng lệnh
- **[Hướng Dẫn Memory](../02-memory/)** - Cấu hình ngữ cảnh liên tục

View File

@@ -0,0 +1,149 @@
#!/usr/bin/env python3
"""
Context Usage Tracker (tiktoken version) - Tracks token consumption per request.
Uses UserPromptSubmit as "pre-message" hook and Stop as "post-response" hook
to calculate the delta in token usage for each request.
This version uses tiktoken with p50k_base encoding for ~90-95% accuracy.
Requires: pip install tiktoken
For a zero-dependency version, see context-tracker.py.
Usage:
Configure both hooks to use the same script:
- UserPromptSubmit: saves current token count
- Stop: calculates delta and reports usage
"""
import json
import os
import sys
import tempfile
try:
import tiktoken
TIKTOKEN_AVAILABLE = True
except ImportError:
TIKTOKEN_AVAILABLE = False
print(
"Warning: tiktoken not installed. Install with: pip install tiktoken",
file=sys.stderr,
)
# Configuration
CONTEXT_LIMIT = 128000 # Claude's context window (adjust for your model)
def get_state_file(session_id: str) -> str:
"""Get temp file path for storing pre-message token count, isolated by session."""
return os.path.join(tempfile.gettempdir(), f"claude-context-{session_id}.json")
def count_tokens(text: str) -> int:
"""
Count tokens using tiktoken with p50k_base encoding.
This provides ~90-95% accuracy compared to Claude's actual tokenizer.
Falls back to character estimation if tiktoken is not available.
Note: Anthropic hasn't released an official offline tokenizer.
tiktoken with p50k_base is a reasonable approximation since both
Claude and GPT models use BPE (byte-pair encoding).
"""
if TIKTOKEN_AVAILABLE:
enc = tiktoken.get_encoding("p50k_base")
return len(enc.encode(text))
else:
# Fallback to character estimation (~4 chars per token)
return len(text) // 4
def read_transcript(transcript_path: str) -> str:
"""Read and concatenate all content from transcript file."""
if not transcript_path or not os.path.exists(transcript_path):
return ""
content = []
with open(transcript_path, "r") as f:
for line in f:
try:
entry = json.loads(line.strip())
# Extract text content from various message formats
if "message" in entry:
msg = entry["message"]
if isinstance(msg.get("content"), str):
content.append(msg["content"])
elif isinstance(msg.get("content"), list):
for block in msg["content"]:
if isinstance(block, dict) and block.get("type") == "text":
content.append(block.get("text", ""))
except json.JSONDecodeError:
continue
return "\n".join(content)
def handle_user_prompt_submit(data: dict) -> None:
"""Pre-message hook: Save current token count before request."""
session_id = data.get("session_id", "unknown")
transcript_path = data.get("transcript_path", "")
transcript_content = read_transcript(transcript_path)
current_tokens = count_tokens(transcript_content)
# Save to temp file for later comparison
state_file = get_state_file(session_id)
with open(state_file, "w") as f:
json.dump({"pre_tokens": current_tokens}, f)
def handle_stop(data: dict) -> None:
"""Post-response hook: Calculate and report token delta."""
session_id = data.get("session_id", "unknown")
transcript_path = data.get("transcript_path", "")
transcript_content = read_transcript(transcript_path)
current_tokens = count_tokens(transcript_content)
# Load pre-message count
state_file = get_state_file(session_id)
pre_tokens = 0
if os.path.exists(state_file):
try:
with open(state_file, "r") as f:
state = json.load(f)
pre_tokens = state.get("pre_tokens", 0)
except (json.JSONDecodeError, IOError):
pass
# Calculate delta
delta_tokens = current_tokens - pre_tokens
remaining = CONTEXT_LIMIT - current_tokens
percentage = (current_tokens / CONTEXT_LIMIT) * 100
# Report usage (stderr so it doesn't interfere with hook output)
method = "tiktoken" if TIKTOKEN_AVAILABLE else "estimated"
print(
f"Context ({method}): ~{current_tokens:,} tokens "
f"({percentage:.1f}% used, ~{remaining:,} remaining)",
file=sys.stderr,
)
if delta_tokens > 0:
print(f"This request: ~{delta_tokens:,} tokens", file=sys.stderr)
def main():
data = json.load(sys.stdin)
event = data.get("hook_event_name", "")
if event == "UserPromptSubmit":
handle_user_prompt_submit(data)
elif event == "Stop":
handle_stop(data)
sys.exit(0)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""
Context Usage Tracker - Tracks token consumption per request.
Uses UserPromptSubmit as "pre-message" hook and Stop as "post-response" hook
to calculate the delta in token usage for each request.
This version uses character-based estimation (no dependencies).
For better accuracy, see context-tracker-tiktoken.py.
Usage:
Configure both hooks to use the same script:
- UserPromptSubmit: saves current token count
- Stop: calculates delta and reports usage
"""
import json
import os
import sys
import tempfile
# Configuration
CONTEXT_LIMIT = 128000 # Claude's context window (adjust for your model)
def get_state_file(session_id: str) -> str:
"""Get temp file path for storing pre-message token count, isolated by session."""
return os.path.join(tempfile.gettempdir(), f"claude-context-{session_id}.json")
def count_tokens_estimate(text: str) -> int:
"""
Estimate token count using character-based approximation.
Uses ~4 characters per token ratio, which provides ~80-90% accuracy
for English text. Less accurate for code and non-English text.
"""
return len(text) // 4
def read_transcript(transcript_path: str) -> str:
"""Read and concatenate all content from transcript file."""
if not transcript_path or not os.path.exists(transcript_path):
return ""
content = []
with open(transcript_path, "r") as f:
for line in f:
try:
entry = json.loads(line.strip())
# Extract text content from various message formats
if "message" in entry:
msg = entry["message"]
if isinstance(msg.get("content"), str):
content.append(msg["content"])
elif isinstance(msg.get("content"), list):
for block in msg["content"]:
if isinstance(block, dict) and block.get("type") == "text":
content.append(block.get("text", ""))
except json.JSONDecodeError:
continue
return "\n".join(content)
def handle_user_prompt_submit(data: dict) -> None:
"""Pre-message hook: Save current token count before request."""
session_id = data.get("session_id", "unknown")
transcript_path = data.get("transcript_path", "")
transcript_content = read_transcript(transcript_path)
current_tokens = count_tokens_estimate(transcript_content)
# Save to temp file for later comparison
state_file = get_state_file(session_id)
with open(state_file, "w") as f:
json.dump({"pre_tokens": current_tokens}, f)
def handle_stop(data: dict) -> None:
"""Post-response hook: Calculate and report token delta."""
session_id = data.get("session_id", "unknown")
transcript_path = data.get("transcript_path", "")
transcript_content = read_transcript(transcript_path)
current_tokens = count_tokens_estimate(transcript_content)
# Load pre-message count
state_file = get_state_file(session_id)
pre_tokens = 0
if os.path.exists(state_file):
try:
with open(state_file, "r") as f:
state = json.load(f)
pre_tokens = state.get("pre_tokens", 0)
except (json.JSONDecodeError, IOError):
pass
# Calculate delta
delta_tokens = current_tokens - pre_tokens
remaining = CONTEXT_LIMIT - current_tokens
percentage = (current_tokens / CONTEXT_LIMIT) * 100
# Report usage (stderr so it doesn't interfere with hook output)
print(
f"Context (estimated): ~{current_tokens:,} tokens "
f"({percentage:.1f}% used, ~{remaining:,} remaining)",
file=sys.stderr,
)
if delta_tokens > 0:
print(f"This request: ~{delta_tokens:,} tokens", file=sys.stderr)
def main():
data = json.load(sys.stdin)
event = data.get("hook_event_name", "")
if event == "UserPromptSubmit":
handle_user_prompt_submit(data)
elif event == "Stop":
handle_stop(data)
sys.exit(0)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,46 @@
#!/bin/bash
# Auto-format code before writing
# Hook: PreToolUse:Write
FILE=$1
if [ -z "$FILE" ]; then
echo "Usage: $0 <file_path>"
exit 1
fi
# Detect file type and format accordingly
case "$FILE" in
*.js|*.jsx|*.ts|*.tsx)
if command -v prettier &> /dev/null; then
echo "Formatting JavaScript/TypeScript file: $FILE"
prettier --write "$FILE"
fi
;;
*.py)
if command -v black &> /dev/null; then
echo "Formatting Python file: $FILE"
black "$FILE"
fi
;;
*.go)
if command -v gofmt &> /dev/null; then
echo "Formatting Go file: $FILE"
gofmt -w "$FILE"
fi
;;
*.rs)
if command -v rustfmt &> /dev/null; then
echo "Formatting Rust file: $FILE"
rustfmt "$FILE"
fi
;;
*.java)
if command -v google-java-format &> /dev/null; then
echo "Formatting Java file: $FILE"
google-java-format -i "$FILE"
fi
;;
esac
exit 0

18
vi/06-hooks/log-bash.sh Normal file
View File

@@ -0,0 +1,18 @@
#!/bin/bash
# Log all bash commands
# Hook: PostToolUse:Bash
COMMAND="$1"
TIMESTAMP=$(date "+%Y-%m-%d %H:%M:%S")
LOGFILE="$HOME/.claude/bash-commands.log"
# Create log directory if it doesn't exist
mkdir -p "$(dirname "$LOGFILE")"
# Log the command
echo "[$TIMESTAMP] $COMMAND" >> "$LOGFILE"
# Optional: Log to system log as well
# logger -t "claude-bash" "$COMMAND"
exit 0

View File

@@ -0,0 +1,66 @@
#!/bin/bash
# Send notifications on events
# Hook: PostPush
REPO_NAME=$(basename $(git rev-parse --show-toplevel 2>/dev/null) 2>/dev/null)
COMMIT_MSG=$(git log -1 --pretty=%B 2>/dev/null)
AUTHOR=$(git log -1 --pretty=%an 2>/dev/null)
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null)
echo "📢 Sending notification to team..."
# Slack webhook example (replace with your webhook URL)
SLACK_WEBHOOK="${SLACK_WEBHOOK_URL:-}"
if [ -n "$SLACK_WEBHOOK" ]; then
curl -X POST "$SLACK_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{
\"text\": \"New push to *$REPO_NAME*\",
\"attachments\": [{
\"color\": \"good\",
\"fields\": [
{\"title\": \"Branch\", \"value\": \"$BRANCH\", \"short\": true},
{\"title\": \"Author\", \"value\": \"$AUTHOR\", \"short\": true},
{\"title\": \"Commit\", \"value\": \"$COMMIT_MSG\"}
]
}]
}" \
--silent --output /dev/null
echo "✅ Slack notification sent"
fi
# Discord webhook example (replace with your webhook URL)
DISCORD_WEBHOOK="${DISCORD_WEBHOOK_URL:-}"
if [ -n "$DISCORD_WEBHOOK" ]; then
curl -X POST "$DISCORD_WEBHOOK" \
-H 'Content-Type: application/json' \
-d "{
\"content\": \"**New push to $REPO_NAME**\",
\"embeds\": [{
\"title\": \"$COMMIT_MSG\",
\"color\": 3066993,
\"fields\": [
{\"name\": \"Branch\", \"value\": \"$BRANCH\", \"inline\": true},
{\"name\": \"Author\", \"value\": \"$AUTHOR\", \"inline\": true}
]
}]
}" \
--silent --output /dev/null
echo "✅ Discord notification sent"
fi
# Email notification example
EMAIL_TO="${TEAM_EMAIL:-}"
if [ -n "$EMAIL_TO" ]; then
echo "New push to $REPO_NAME by $AUTHOR" | \
mail -s "Git Push: $BRANCH" "$EMAIL_TO"
echo "✅ Email notification sent"
fi
exit 0

50
vi/06-hooks/pre-commit.sh Normal file
View File

@@ -0,0 +1,50 @@
#!/bin/bash
# Run tests before commit
# Hook: PreToolUse (matcher: Bash) - checks if the command is a git commit
# Note: There is no "PreCommit" hook event. Use PreToolUse with a Bash matcher
# and inspect the command to detect git commit operations.
echo "🧪 Running tests before commit..."
# Check if package.json exists (Node.js project)
if [ -f "package.json" ]; then
if grep -q "\"test\":" package.json; then
npm test
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked."
exit 1
fi
fi
fi
# Check if pytest is available (Python project)
if [ -f "pytest.ini" ] || [ -f "setup.py" ]; then
if command -v pytest &> /dev/null; then
pytest
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked."
exit 1
fi
fi
fi
# Check if go.mod exists (Go project)
if [ -f "go.mod" ]; then
go test ./...
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked."
exit 1
fi
fi
# Check if Cargo.toml exists (Rust project)
if [ -f "Cargo.toml" ]; then
cargo test
if [ $? -ne 0 ]; then
echo "❌ Tests failed! Commit blocked."
exit 1
fi
fi
echo "✅ All tests passed! Proceeding with commit."
exit 0

View File

@@ -0,0 +1,61 @@
#!/bin/bash
# Security scan on file write
# Hook: PostToolUse:Write
FILE=$1
if [ -z "$FILE" ]; then
echo "Usage: $0 <file_path>"
exit 0
fi
echo "🔒 Running security scan on: $FILE"
ISSUES_FOUND=0
# Check for hardcoded passwords
if grep -qE "(password|passwd|pwd)\s*=\s*['\"][^'\"]+['\"]" "$FILE"; then
echo "⚠️ WARNING: Potential hardcoded password detected in $FILE"
ISSUES_FOUND=1
fi
# Check for hardcoded API keys
if grep -qE "(api[_-]?key|apikey|access[_-]?token)\s*=\s*['\"][^'\"]+['\"]" "$FILE"; then
echo "⚠️ WARNING: Potential hardcoded API key detected in $FILE"
ISSUES_FOUND=1
fi
# Check for hardcoded secrets
if grep -qE "(secret|token)\s*=\s*['\"][^'\"]+['\"]" "$FILE"; then
echo "⚠️ WARNING: Potential hardcoded secret detected in $FILE"
ISSUES_FOUND=1
fi
# Check for private keys
if grep -q "BEGIN.*PRIVATE KEY" "$FILE"; then
echo "⚠️ WARNING: Private key detected in $FILE"
ISSUES_FOUND=1
fi
# Check for AWS keys
if grep -qE "AKIA[0-9A-Z]{16}" "$FILE"; then
echo "⚠️ WARNING: AWS access key detected in $FILE"
ISSUES_FOUND=1
fi
# Scan with semgrep if available
if command -v semgrep &> /dev/null; then
semgrep --config=auto "$FILE" --quiet 2>/dev/null
fi
# Scan with trufflehog if available
if command -v trufflehog &> /dev/null; then
trufflehog filesystem "$FILE" --only-verified --quiet 2>/dev/null
fi
if [ $ISSUES_FOUND -eq 0 ]; then
echo "✅ No security issues found"
fi
# Don't block the operation, just warn
exit 0

View File

@@ -0,0 +1,43 @@
#!/bin/bash
# Validate user prompts
# Hook: UserPromptSubmit
# Read prompt from stdin
PROMPT=$(cat)
echo "🔍 Validating prompt..."
# Check for dangerous operations
DANGEROUS_PATTERNS=(
"rm -rf /"
"delete database"
"drop database"
"format disk"
"dd if="
)
for pattern in "${DANGEROUS_PATTERNS[@]}"; do
if echo "$PROMPT" | grep -qi "$pattern"; then
echo "❌ Blocked: Dangerous operation detected: $pattern"
exit 1
fi
done
# Check for production deployments
if echo "$PROMPT" | grep -qiE "(deploy|push).*production"; then
if [ ! -f ".deployment-approved" ]; then
echo "❌ Blocked: Production deployment requires approval"
echo "Create .deployment-approved file to proceed"
exit 1
fi
fi
# Check for required context in certain operations
if echo "$PROMPT" | grep -qi "refactor"; then
if [ ! -f "tests/" ] && [ ! -f "test/" ]; then
echo "⚠️ Warning: Refactoring without tests may be risky"
fi
fi
echo "✅ Prompt validation passed"
exit 0

943
vi/07-plugins/README.md Normal file
View File

@@ -0,0 +1,943 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Claude Code Plugins / Plugins Claude Code
Thư mục này chứa các ví dụ plugin hoàn chỉnh đóng gói nhiều tính năng Claude Code thành các gói có thể cài đặt liền mạch.
## Tổng Quan / Overview
Claude Code Plugins là các bộ sưu tập được đóng gói của các tùy chỉnh (slash commands, subagents, MCP servers, và hooks) cài đặt với một lệnh duy nhất. Chúng đại diện cho cơ chế mở rộng cấp cao nhất—kết hợp nhiều tính năng thành các gói gắn kết, có thể chia sẻ.
## Kiến Trúc Plugin / Plugin Architecture
```mermaid
graph TB
A["Plugin"]
B["Slash Commands"]
C["Subagents"]
D["MCP Servers"]
E["Hooks"]
F["Configuration"]
A -->|bundles| B
A -->|bundles| C
A -->|bundles| D
A -->|bundles| E
A -->|bundles| F
```
## Quy Trình Tải Plugin / Plugin Loading Process
```mermaid
sequenceDiagram
participant User
participant Claude as Claude Code
participant Plugin as Plugin Marketplace
participant Install as Installation
participant SlashCmds as Slash Commands
participant Subagents
participant MCPServers as MCP Servers
participant Hooks
participant Tools as Configured Tools
User->>Claude: /plugin install pr-review
Claude->>Plugin: Download plugin manifest
Plugin-->>Claude: Return plugin definition
Claude->>Install: Extract components
Install->>SlashCmds: Configure
Install->>Subagents: Configure
Install->>MCPServers: Configure
Install->>Hooks: Configure
SlashCmds-->>Tools: Ready to use
Subagents-->>Tools: Ready to use
MCPServers-->>Tools: Ready to use
Hooks-->>Tools: Ready to use
Tools-->>Claude: Plugin installed ✅
```
## Các Loại Plugin & Phân Phối / Plugin Types & Distribution
| Loại | Phạm Vi | Chia Sẻ | Quyền | Ví Dụ |
|------|-------|--------|-----------|----------|
| Chính Thức | Toàn cầu | Tất cả người dùng | Anthropic | PR Review, Security Guidance |
| Cộng Đồng | Công khai | Tất cả người dùng | Cộng Đồng | DevOps, Data Science |
| Tổ Chức | Nội bộ | Các thành viên nhóm | Công ty | Tiêu chuẩn nội bộ, công cụ |
| Cá Nhân | Cá nhân | Người dùng duy nhất | Nhà phát triển | Workflows tùy chỉnh |
## Cấu Trúc Định Nghĩa Plugin / Plugin Definition Structure
Plugin manifest sử dụng định dạng JSON trong `.claude-plugin/plugin.json`:
```json
{
"name": "my-first-plugin",
"description": "A greeting plugin",
"version": "1.0.0",
"author": {
"name": "Your Name"
},
"homepage": "https://example.com",
"repository": "https://github.com/user/repo",
"license": "MIT"
}
```
## Ví Dụ Cấu Trúc Plugin / Plugin Structure Example
```
my-plugin/
├── .claude-plugin/
│ └── plugin.json # Manifest (tên, mô tả, phiên bản, tác giả)
├── commands/ # Skills như các file Markdown
│ ├── task-1.md
│ ├── task-2.md
│ └── workflows/
├── agents/ # Định nghĩa agent tùy chỉnh
│ ├── specialist-1.md
│ ├── specialist-2.md
│ └── configs/
├── skills/ # Agent Skills với các file SKILL.md
│ ├── skill-1.md
│ └── skill-2.md
├── hooks/ # Event handlers trong hooks.json
│ └── hooks.json
├── .mcp.json # Cấu hình MCP server
├── .lsp.json # Cấu hình LSP server
├── settings.json # Cài đặt mặc định
├── templates/
│ └── issue-template.md
├── scripts/
│ ├── helper-1.sh
│ └── helper-2.py
├── docs/
│ ├── README.md
│ └── USAGE.md
└── tests/
└── plugin.test.js
```
### Cấu hình LSP server / LSP server configuration
Plugins có thể bao gồm hỗ trợ Language Server Protocol (LSP) để thông minh code thời gian thực. LSP servers cung cấp chẩn đoán, điều hướng code, và thông tin ký hiệu khi bạn làm việc.
**Vị trí cấu hình:**
- File `.lsp.json` trong thư mục gốc plugin
- Key `lsp` inline trong `plugin.json`
#### Tham khảo trường / Field reference
| Trường | Bắt Buộc | Mô Tả |
|-------|----------|-------------|
| `command` | Có | Binary LSP server (phải trong PATH) |
| `extensionToLanguage` | Có | Ánh xạ các phần mở rộng file đến ID ngôn ngữ |
| `args` | Không | Các đối số dòng lệnh cho server |
| `transport` | Không | Phương thức giao tiếp: `stdio` (mặc định) hoặc `socket` |
| `env` | Không | Biến môi trường cho tiến trình server |
| `initializationOptions` | Không | Các tùy chọn được gửi trong quá trình khởi tạo LSP |
| `settings` | Không | Cấu hình workspace được chuyển đến server |
| `workspaceFolder` | Không | Ghi đè đường dẫn thư mục workspace |
| `startupTimeout` | Không | Thời gian tối đa (ms) để chờ khởi động server |
| `shutdownTimeout` | Không | Thời gian tối đa (ms) để tắt graceful |
| `restartOnCrash` | Không | Tự động khởi động lại nếu server bị lỗi |
| `maxRestarts` | Không | Số lần khởi động lại tối đa trước khi bỏ cuộc |
#### Các cấu hình ví dụ / Example configurations
**Go (gopls):**
```json
{
"go": {
"command": "gopls",
"args": ["serve"],
"extensionToLanguage": {
".go": "go"
}
}
}
```
**Python (pyright):**
```json
{
"python": {
"command": "pyright-langserver",
"args": ["--stdio"],
"extensionToLanguage": {
".py": "python",
".pyi": "python"
}
}
}
```
**TypeScript:**
```json
{
"typescript": {
"command": "typescript-language-server",
"args": ["--stdio"],
"extensionToLanguage": {
".ts": "typescript",
".tsx": "typescriptreact",
".js": "javascript",
".jsx": "javascriptreact"
}
}
}
```
#### Các plugin LSP có sẵn / Available LSP plugins
Marketplace chính thức bao gồm các plugin LSP được cấu hình trước:
| Plugin | Ngôn Ngữ | Server Binary | Lệnh Cài Đặt |
|--------|----------|---------------|----------------|
| `pyright-lsp` | Python | `pyright-langserver` | `pip install pyright` |
| `typescript-lsp` | TypeScript/JavaScript | `typescript-language-server` | `npm install -g typescript-language-server typescript` |
| `rust-lsp` | Rust | `rust-analyzer` | Cài đặt qua `rustup component add rust-analyzer` |
#### Khả năng LSP / LSP capabilities
Khi được cấu hình, LSP servers cung cấp:
- **Chẩn đoán tức thì** — lỗi và cảnh báo xuất hiện ngay sau khi chỉnh sửa
- **Điều hướng code** — đi đến định nghĩa, tìm tham chiếu, implementations
- **Thông tin hover** — chữ ký kiểu và tài liệu khi hover
- **Liệt kê ký hiệu** — duyệt các ký hiệu trong file hoặc workspace hiện tại
## Tùy Chọn Plugin (v2.1.83+) / Plugin Options
Plugins có thể khai báo các tùy chọn có thể cấu hình bởi người dùng trong manifest qua `userConfig`. Các giá trị được đánh dấu `sensitive: true` được lưu trữ trong system keychain thay vì các file settings plain-text:
```json
{
"name": "my-plugin",
"version": "1.0.0",
"userConfig": {
"apiKey": {
"description": "API key for the service",
"sensitive": true
},
"region": {
"description": "Deployment region",
"default": "us-east-1"
}
}
}
```
## Dữ Liệu Plugin Liên Tục (`${CLAUDE_PLUGIN_DATA}`) (v2.1.78+)
Plugins có quyền truy cập đến một thư mục trạng thái liên tục qua biến môi trường `${CLAUDE_PLUGIN_DATA}`. Thư mục này là duy nhất cho mỗi plugin và tồn tại qua các phiên, làm cho nó phù hợp cho caches, databases, và các trạng thái liên tục khác:
```json
{
"hooks": {
"PostToolUse": [
{
"command": "node ${CLAUDE_PLUGIN_DATA}/track-usage.js"
}
]
}
}
```
Thư mục được tạo tự động khi plugin được cài đặt. Các file được lưu trữ ở đây tồn tại cho đến khi plugin được gỡ cài đặt.
## Plugin Inline qua Settings (`source: 'settings'`) (v2.1.80+)
Plugins có thể được định nghĩa inline trong các file settings như các mục marketplace sử dụng trường `source: 'settings'`. Điều này cho phép nhúng định nghĩa plugin trực tiếp mà không cần repository hoặc marketplace riêng:
```json
{
"pluginMarketplaces": [
{
"name": "inline-tools",
"source": "settings",
"plugins": [
{
"name": "quick-lint",
"source": "./local-plugins/quick-lint"
}
]
}
]
}
```
## Cài Đặt Plugin / Plugin Settings
Plugins có thể gửi một file `settings.json` để cung cấp cấu hình mặc định. Điều này hiện hỗ trợ key `agent`, thiết lập agent luồng chính cho plugin:
```json
{
"agent": "agents/specialist-1.md"
}
```
Khi một plugin bao gồm `settings.json`, các mặc định của nó được áp dụng khi cài đặt. Người dùng có thể ghi đè các cài đặt này trong cấu hình project hoặc user của riêng họ.
## Cách Tiếp Cận Standalone vs Plugin / Standalone vs Plugin Approach
| Cách Tiếp Cận | Tên Lệnh | Cấu Hình | Tốt Nhất Cho |
|----------|---------------|---|---|
| **Standalone** | `/hello` | Thiết lập thủ công trong CLAUDE.md | Cá nhân, cụ thể project |
| **Plugins** | `/plugin-name:hello` | Tự động qua plugin.json | Chia sẻ, phân phối, sử dụng nhóm |
**Sử dụng slash commands standalone** cho workflows cá nhân nhanh. **Sử dụng plugins** khi bạn muốn đóng gói nhiều tính năng, chia sẻ với một nhóm, hoặc xuất bản để phân phối.
## Ví Dụ Thực Tiễn / Practical Examples
### Ví Dụ 1: Plugin PR Review / Example 1: PR Review Plugin
**File:** `.claude-plugin/plugin.json`
```json
{
"name": "pr-review",
"version": "1.0.0",
"description": "Complete PR review workflow with security, testing, and docs",
"author": {
"name": "Anthropic"
},
"repository": "https://github.com/your-org/pr-review",
"license": "MIT"
}
```
**File:** `commands/review-pr.md`
```markdown
---
name: Review PR
description: Start comprehensive PR review with security and testing checks
---
# PR Review
Lệnh này khởi tạo một pull request review hoàn chỉnh bao gồm:
1. Phân tích bảo mật
2. Xác minh phủ vùng test
3. Cập nhật tài liệu
4. Kiểm tra chất lượng code
5. Đánh giá tác động hiệu suất
```
**File:** `agents/security-reviewer.md`
```yaml
---
name: security-reviewer
description: Security-focused code review
tools: read, grep, diff
---
# Security Reviewer
Chuyên về việc tìm các lỗ hổng bảo mật:
- Vấn đề xác thực/ủy quyền
- Lộ dữ liệu
- Các tấn công tiêm nhiễm
- Cấu hình bảo mật
```
**Cài Đặt:**
```bash
/plugin install pr-review
# Result:
# ✅ 3 slash commands installed
# ✅ 3 subagents configured
# ✅ 2 MCP servers connected
# ✅ 4 hooks registered
# ✅ Ready to use!
```
### Ví Dụ 2: Plugin DevOps / Example 2: DevOps Plugin
**Các Thành Phần:**
```
devops-automation/
├── commands/
│ ├── deploy.md
│ ├── rollback.md
│ ├── status.md
│ └── incident.md
├── agents/
│ ├── deployment-specialist.md
│ ├── incident-commander.md
│ └── alert-analyzer.md
├── mcp/
│ ├── github-config.json
│ ├── kubernetes-config.json
│ └── prometheus-config.json
├── hooks/
│ ├── pre-deploy.js
│ ├── post-deploy.js
│ └── on-error.js
└── scripts/
├── deploy.sh
├── rollback.sh
└── health-check.sh
```
### Ví Dụ 3: Plugin Tài Liệu / Example 3: Documentation Plugin
**Các Thành Phần Được Đóng Gói:**
```
documentation/
├── commands/
│ ├── generate-api-docs.md
│ ├── generate-readme.md
│ ├── sync-docs.md
│ └── validate-docs.md
├── agents/
│ ├── api-documenter.md
│ ├── code-commentator.md
│ └── example-generator.md
├── mcp/
│ ├── github-docs-config.json
│ └── slack-announce-config.json
└── templates/
├── api-endpoint.md
├── function-docs.md
└── adr-template.md
```
## Marketplace Plugin / Plugin Marketplace
Thư mục plugin do Anthropic quản lý chính thức là `anthropics/claude-plugins-official`. Các quản trị viên enterprise cũng có thể tạo các plugin marketplaces riêng để phân phối nội bộ.
```mermaid
graph TB
A["Plugin Marketplace"]
B["Official<br/>anthropics/claude-plugins-official"]
C["Community<br/>Marketplace"]
D["Enterprise<br/>Private Registry"]
A --> B
A --> C
A --> D
B -->|Categories| B1["Development"]
B -->|Categories| B2["DevOps"]
B -->|Categories| B3["Documentation"]
C -->|Search| C1["DevOps Automation"]
C -->|Search| C2["Mobile Dev"]
C -->|Search| C3["Data Science"]
D -->|Internal| D1["Company Standards"]
D -->|Internal| D2["Legacy Systems"]
D -->|Internal| D3["Compliance"]
style A fill:#e1f5fe,stroke:#333,color:#333
style B fill:#e8f5e9,stroke:#333,color:#333
style C fill:#f3e5f5,stroke:#333,color:#333
style D fill:#fff3e0,stroke:#333,color:#333
```
### Cấu Hình Marketplace / Marketplace Configuration
Người dùng enterprise và nâng cao có thể kiểm soát hành vi marketplace qua các cài đặt:
| Cài Đặt | Mô Tả |
|---------|-------------|
| `extraKnownMarketplaces` | Thêm các nguồn marketplace bổ sung ngoài mặc định |
| `strictKnownMarketplaces` | Kiểm soát marketplace nào người dùng được phép thêm |
| `deniedPlugins` | Blocklist do quản trị viên quản lý để ngăn cài đặt các plugin cụ thể |
### Các Tính Năng Marketplace Thêm / Additional Marketplace Features
- **Git timeout mặc định**: Tăng từ 30s lên 120s cho các repository plugin lớn
- **npm registries tùy chỉnh**: Plugins có thể chỉ định URLs registry npm tùy chỉnh để giải quyết dependency
- **Version pinning**: Khóa plugins đến các phiên bản cụ thể cho các môi trường có thể tái sản xuất
### Schema định nghĩa marketplace / Marketplace definition schema
Plugin marketplaces được định nghĩa trong `.claude-plugin/marketplace.json`:
```json
{
"name": "my-team-plugins",
"owner": "my-org",
"plugins": [
{
"name": "code-standards",
"source": "./plugins/code-standards",
"description": "Enforce team coding standards",
"version": "1.2.0",
"author": "platform-team"
},
{
"name": "deploy-helper",
"source": {
"source": "github",
"repo": "my-org/deploy-helper",
"ref": "v2.0.0"
},
"description": "Deployment automation workflows"
}
]
}
```
| Trường | Bắt Buộc | Mô Tả |
|-------|----------|-------------|
| `name` | Có | Tên marketplace trong kebab-case |
| `owner` | Có | Tổ chức hoặc người dùng duy trì marketplace |
| `plugins` | Có | Mảng các mục plugin |
| `plugins[].name` | Có | Tên plugin (kebab-case) |
| `plugins[].source` | Có | Nguồn plugin (chuỗi đường dẫn hoặc object nguồn) |
| `plugins[].description` | Không | Mô tả plugin ngắn |
| `plugins[].version` | Không | Chuỗi phiên bản semantic |
| `plugins[].author` | Không | Tên tác giả plugin |
### Các loại nguồn plugin / Plugin source types
Plugins có thể được sourced từ nhiều vị trí:
| Nguồn | Cú Pháp | Ví Dụ |
|--------|--------|---------|
| **Đường dẫn tương đối** | Chuỗi đường dẫn | `"./plugins/my-plugin"` |
| **GitHub** | `{ "source": "github", "repo": "owner/repo" }` | `{ "source": "github", "repo": "acme/lint-plugin", "ref": "v1.0" }` |
| **Git URL** | `{ "source": "url", "url": "..." }` | `{ "source": "url", "url": "https://git.internal/plugin.git" }` |
| **Git subdirectory** | `{ "source": "git-subdir", "url": "...", "path": "..." }` | `{ "source": "git-subdir", "url": "https://github.com/org/monorepo.git", "path": "packages/plugin" }` |
| **npm** | `{ "source": "npm", "package": "..." }` | `{ "source": "npm", "package": "@acme/claude-plugin", "version": "^2.0" }` |
| **pip** | `{ "source": "pip", "package": "..." }` | `{ "source": "pip", "package": "claude-data-plugin", "version": ">=1.0" }` |
Các nguồn GitHub và git hỗ trợ các trường tùy chọn `ref` (nhánh/tag) và `sha` (hash commit) để version pinning.
### Các phương thức phân phối / Distribution methods
**GitHub (khuyến nghị):**
```bash
# Người dùng thêm marketplace của bạn
/plugin marketplace add owner/repo-name
```
**Các dịch vụ git khác** (yêu cầu URL đầy đủ):
```bash
/plugin marketplace add https://gitlab.com/org/marketplace-repo.git
```
**Repository riêng tư**: Được hỗ trợ qua các git credential helpers hoặc token môi trường. Người dùng phải có quyền truy cập đọc đến repository.
**Nộp marketplace chính thức**: Gửi plugins đến marketplace do Anthropic quản lý để phân phối rộng hơn.
### Chế độ nghiêm ngặt / Strict mode
Kiểm soát cách các định nghĩa marketplace tương tác với các file `plugin.json` cục bộ:
| Cài Đặt | Hành Vi |
|---------|----------|
| `strict: true` (mặc định) | `plugin.json` cục bộ là có thẩm quyền; mục marketplace bổ sung nó |
| `strict: false` | Mục marketplace là định nghĩa plugin hoàn chỉnh |
**Hạn chế tổ chức** với `strictKnownMarketplaces`:
| Giá Trị | Hiệu Ứng |
|-------|--------|
| Không được đặt | Không có hạn chế — người dùng có thể thêm bất kỳ marketplace nào |
| Mảng rỗng `[]` | Khóa — không cho phép marketplaces |
| Mảng các mẫu | Allowlist — chỉ các marketplaces khớp có thể được thêm |
```json
{
"strictKnownMarketplaces": [
"my-org/*",
"github.com/trusted-vendor/*"
]
}
```
> **Cảnh Báo**: Trong chế độ nghiêm ngặt với `strictKnownMarketplaces`, người dùng chỉ có thể cài đặt plugins từ các marketplaces được allowlist. Điều này hữu ích cho các môi trường doanh nghiệp yêu cầu phân phối plugin được kiểm soát.
## Vòng Đời & Cài Đặt Plugin / Plugin Installation & Lifecycle
```mermaid
graph LR
A["Discover"] -->|Browse| B["Marketplace"]
B -->|Select| C["Plugin Page"]
C -->|View| D["Components"]
D -->|Install| E["/plugin install"]
E -->|Extract| F["Configure"]
F -->|Activate| G["Use"]
G -->|Check| H["Update"]
H -->|Available| G
G -->|Done| I["Disable"]
I -->|Later| J["Enable"]
J -->|Back| G
```
## So Sánh Tính Năng Plugin / Plugin Features Comparison
| Tính Năng | Slash Command | Skill | Subagent | Plugin |
|---------|---------------|-------|----------|--------|
| **Cài Đặt** | Copy thủ công | Copy thủ công | Cấu hình thủ công | Một lệnh |
| **Thời Gian Thiết Lập** | 5 phút | 10 phút | 15 phút | 2 phút |
| **Đóng Gói** | File đơn | File đơn | File đơn | Nhiều |
| **Phiên Bản Hóa** | Thủ công | Thủ công | Thủ công | Tự động |
| **Chia Sẻ Nhóm** | Copy file | Copy file | Copy file | Cài đặt ID |
| **Cập Nhật** | Thủ công | Thủ công | Thủ công | Tự động có sẵn |
| **Phụ Thuộc** | Không | Không | Không | Có thể bao gồm |
| **Marketplace** | Không | Không | Không | Có |
| **Phân Phối** | Repository | Repository | Repository | Marketplace |
## Các Lệnh CLI Plugin / Plugin CLI Commands
Tất cả các thao tác plugin có sẵn như các lệnh CLI:
```bash
claude plugin install <name>@<marketplace> # Cài đặt từ marketplace
claude plugin uninstall <name> # Gỡ bỏ plugin
claude plugin list # Liệt kê các plugin đã cài đặt
claude plugin enable <name> # Kích hoạt plugin đã bị vô hiệu hóa
claude plugin disable <name> # Vô hiệu hóa plugin
claude plugin validate # Xác thực cấu trúc plugin
```
## Các Phương Thức Cài Đặt / Installation Methods
### Từ Marketplace
```bash
/plugin install plugin-name
# hoặc từ CLI:
claude plugin install plugin-name@marketplace-name
```
### Kích Hoạt / Vô Hiệu Hóa (với phạm vi tự phát hiện)
```bash
/plugin enable plugin-name
/plugin disable plugin-name
```
### Plugin Cục Bộ (cho phát triển)
```bash
# Cờ CLI để test cục bộ (có thể lặp lại cho nhiều plugins)
claude --plugin-dir ./path/to/plugin
claude --plugin-dir ./plugin-a --plugin-dir ./plugin-b
```
### Từ Git Repository
```bash
/plugin install github:username/repo
```
## Khi Nào Tạo Một Plugin / When to Create a Plugin
```mermaid
graph TD
A["Should I create a plugin?"]
A -->|Need multiple components| B{"Multiple commands<br/>or subagents<br/>or MCPs?"}
B -->|Yes| C["✅ Create Plugin"]
B -->|No| D["Use Individual Feature"]
A -->|Team workflow| E{"Share with<br/>team?"}
E -->|Yes| C
E -->|No| F["Keep as Local Setup"]
A -->|Complex setup| G{"Needs auto<br/>configuration?"}
G -->|Yes| C
G -->|No| D
```
### Các Trường Hợp Sử Dụng Plugin / Plugin Use Cases
| Trường Hợp Sử Dụng | Khuyến Nghị | Tại Sao |
|----------|-----------------|-----|
| **Team Onboarding** | ✅ Use Plugin | Thiết lập tức thì, tất cả cấu hình |
| **Framework Setup** | ✅ Use Plugin | Đóng gói các lệnh cụ thể framework |
| **Enterprise Standards** | ✅ Use Plugin | Phân phối trung tâm, kiểm soát phiên bản |
| **Quick Task Automation** | ❌ Use Command | Quá phức tạp |
| **Single Domain Expertise** | ❌ Use Skill | Quá nặng, sử dụng skill thay thế |
| **Specialized Analysis** | ❌ Use Subagent | Tạo thủ công hoặc sử dụng skill |
| **Live Data Access** | ❌ Use MCP | Standalone, đừng đóng gói |
## Testing Một Plugin / Testing a Plugin
Trước khi xuất bản, test plugin của bạn cục bộ sử dụng cờ CLI `--plugin-dir` (có thể lặp lại cho nhiều plugins):
```bash
claude --plugin-dir ./my-plugin
claude --plugin-dir ./my-plugin --plugin-dir ./another-plugin
```
Điều này khởi chạy Claude Code với plugin của bạn được tải, cho phép bạn:
- Xác minh tất cả các lệnh slash có sẵn
- Test subagents và agents hoạt động chính xác
- Xác nhận MCP servers kết nối đúng
- Xác thực thực thi hook
- Kiểm tra các cấu hình LSP server
- Kiểm tra các lỗi cấu hình
## Hot-Reload
Plugins hỗ trợ hot-reload trong quá trình phát triển. Khi bạn sửa đổi các file plugin, Claude Code có thể phát hiện các thay đổi tự động. Bạn cũng có thể force reload với:
```bash
/reload-plugins
```
Điều này đọc lại tất cả các plugin manifests, commands, agents, skills, hooks, và cấu hình MCP/LSP mà không cần khởi động lại phiên.
## Cài Đặt Được Quản Lý Cho Plugins / Managed Settings for Plugins
Các quản trị viên có thể kiểm soát hành vi plugin trên một tổ chức sử dụng các cài đặt được quản lý:
| Cài Đặt | Mô Tả |
|---------|-------------|
| `enabledPlugins` | Allowlist của các plugin được kích hoạt theo mặc định |
| `deniedPlugins` | Blocklist của các plugin không thể được cài đặt |
| `extraKnownMarketplaces` | Thêm các nguồn marketplace bổ sung ngoài mặc định |
| `strictKnownMarketplaces` | Hạn chế marketplace nào người dùng được phép thêm |
| `allowedChannelPlugins` | Kiểm soát plugins nào được phép theo kênh phát hành |
Các cài đặt này có thể được áp dụng ở cấp tổ chức qua các file cấu hình được quản lý và có ưu tiên hơn các cài đặt cấp người dùng.
## Bảo Mật Plugin / Plugin Security
Các subagent plugin chạy trong một sandbox bị hạn chế. Các key frontmatter sau **không được phép** trong định nghĩa subagent plugin:
- `hooks` -- Subagents không thể đăng ký event handlers
- `mcpServers` -- Subagents không thể cấu hình MCP servers
- `permissionMode` -- Subagents không thể ghi đè mô hình quyền
Điều này đảm bảo rằng plugins không thể leo thang đặc quyền hoặc sửa đổi môi trường host vượt quá phạm vi được khai báo của chúng.
## Xuất Bản Một Plugin / Publishing a Plugin
**Các bước để xuất bản:**
1. Tạo cấu trúc plugin với tất cả các thành phần
2. Viết manifest `.claude-plugin/plugin.json`
3. Tạo `README.md` với tài liệu
4. Test cục bộ với `claude --plugin-dir ./my-plugin`
5. Gửi đến plugin marketplace
6. Được review và phê duyệt
7. Xuất bản trên marketplace
8. Người dùng có thể cài đặt với một lệnh
**Ví dụ gửi:**
```markdown
# PR Review Plugin
## Mô Tả
Workflow PR review hoàn chỉnh với các kiểm tra bảo mật, testing, và tài liệu.
## Những Gì Được Bao Gồm
- 3 lệnh slash cho các loại review khác nhau
- 3 subagents chuyên biệt
- Tích hợp GitHub và CodeQL MCP
- Các hooks quét bảo mật tự động
## Cài Đặt
```bash
/plugin install pr-review
```
## Tính Năng
✅ Phân tích bảo mật
✅ Kiểm tra phủ vùng test
✅ Xác minh tài liệu
✅ Đánh giá chất lượng code
✅ Phân tích tác động hiệu suất
## Sử Dụng
```bash
/review-pr
/check-security
/check-tests
```
## Yêu Cầu
- Claude Code 1.0+
- Truy cập GitHub
- CodeQL (tùy chọn)
```
## Plugin vs Cấu Hình Thủ Công / Plugin vs Manual Configuration
**Thiết Lập Thủ Công (2+ giờ):**
- Cài đặt các lệnh slash từng cái một
- Tạo subagents riêng lẻ
- Cấu hình MCPs riêng biệt
- Thiết lập hooks thủ công
- Tài liệu hóa mọi thứ
- Chia sẻ với nhóm (hy vọng họ cấu hình đúng)
**Với Plugin (2 phút):**
```bash
/plugin install pr-review
# ✅ Mọi thứ được cài đặt và cấu hình
# ✅ Sẵn sàng sử dụng ngay lập tức
# ✅ Nhóm có thể tái sản xuất thiết lập chính xác
```
## Thực Hành Tốt Nhất / Best Practices
### Nên Làm ✅ / Do's ✅
- Sử dụng tên plugin rõ ràng, mô tả
- Bao gồm README toàn diện
- Phiên bản hóa plugin của bạn đúng cách (semver)
- Test tất cả các thành phần cùng nhau
- Tài liệu hóa các yêu cầu rõ ràng
- Cung cấp các ví dụ sử dụng
- Bao gồm xử lý lỗi
- Gắn thẻ phù hợp để khám phá
- Duy trì tương thích ngược
- Giữ các plugin tập trung và gắn kết
- Bao gồm các tests toàn diện
- Tài liệu hóa tất cả các dependencies
### Không Nên Làm ❌ / Don'ts ❌
- Đừng đóng gói các tính năng không liên quan
- Đừng hardcode credentials
- Đừng bỏ qua testing
- Đừng quên tài liệu
- Đừng tạo các plugin dư thừa
- Đừng bỏ qua versioning
- Đừng làm phức tạp quá mức các dependencies thành phần
- Đừng quên xử lý các lỗi một cách graceful
## Hướng Dẫn Cài Đặt / Installation Instructions
### Cài Đặt Từ Marketplace
1. **Duyệt các plugins có sẵn:**
```bash
/plugin list
```
2. **Xem chi tiết plugin:**
```bash
/plugin info plugin-name
```
3. **Cài đặt một plugin:**
```bash
/plugin install plugin-name
```
### Cài Đặt Từ Đường Dẫn Cục Bộ
```bash
/plugin install ./path/to/plugin-directory
```
### Cài Đặt Từ GitHub
```bash
/plugin install github:username/repo
```
### Liệt Kê Các Plugins Đã Cài Đặt
```bash
/plugin list --installed
```
### Cập Nhật Một Plugin
```bash
/plugin update plugin-name
```
### Vô Hiệu Hóa/Kích Hoạt Một Plugin
```bash
# Vô hiệu hóa tạm thời
/plugin disable plugin-name
# Kích hoạt lại
/plugin enable plugin-name
```
### Gỡ Cài Đặt Một Plugin
```bash
/plugin uninstall plugin-name
```
## Các Khái Niệm Liên Quan / Related Concepts
Các tính năng Claude Code sau hoạt động cùng với plugins:
- **[Slash Commands](../01-slash-commands/)** - Các lệnh riêng lẻ được đóng gói trong plugins
- **[Memory](../02-memory/)** - Ngữ cảnh liên tục cho plugins
- **[Skills](../03-skills/)** - Chuyên môn lĩnh vực có thể được bọc trong plugins
- **[Subagents](../04-subagents/)** - Các agents chuyên biệt được bao gồm như các thành phần plugin
- **[MCP Servers](../05-mcp/)** - Các tích hợp Model Context Protocol được đóng gói trong plugins
- **[Hooks](../06-hooks/)** - Event handlers kích hoạt workflows plugin
## Workflow Ví Dụ Hoàn Chỉnh / Complete Example Workflow
### Workflow Plugin PR Review Đầy Đủ / PR Review Plugin Full Workflow
```
1. User: /review-pr
2. Plugin executes:
├── pre-review.js hook validates git repo
├── GitHub MCP fetches PR data
├── security-reviewer subagent analyzes security
├── test-checker subagent verifies coverage
└── performance-analyzer subagent checks performance
3. Results synthesized and presented:
✅ Security: No critical issues
⚠️ Testing: Coverage 65% (recommend 80%+)
✅ Performance: No significant impact
📝 12 recommendations provided
```
## Xử Lý Sự Cố / Troubleshooting
### Plugin Won't Install
- Kiểm tra tính tương thích phiên bản Claude Code: `/version`
- Xác minh cú pháp `plugin.json` với một trình xác thực JSON
- Kiểm tra kết nối internet (cho plugins từ xa)
- Review quyền: `ls -la plugin/`
### Components Not Loading
- Xác minh các đường dẫn trong `plugin.json` khớp với cấu trúc thư mục thực tế
- Kiểm tra quyền file: `chmod +x scripts/`
- Review cú pháp file thành phần
- Kiểm tra logs: `/plugin debug plugin-name`
### MCP Connection Failed
- Xác minh các biến môi trường được đặt đúng
- Kiểm tra cài đặt và sức khỏe MCP server
- Test kết nối MCP độc lập với `/mcp test`
- Review cấu hình MCP trong thư mục `mcp/`
### Commands Not Available After Install
- Đảm bảo plugin được cài đặt thành công: `/plugin list --installed`
- Kiểm tra nếu plugin được kích hoạt: `/plugin status plugin-name`
- Khởi động lại Claude Code: `exit` và mở lại
- Kiểm tra xung đột đặt tên với các lệnh hiện có
### Hook Execution Issues
- Xác minh các file hook có các quyền đúng
- Kiểm tra cú pháp hook và tên sự kiện
- Review logs hook để biết chi tiết lỗi
- Test hooks thủ công nếu có thể
## Tài Nguyên Thêm / Additional Resources
- [Tài Liệu Plugins Chính Thức](https://code.claude.com/docs/en/plugins)
- [Khám Phá Plugins](https://code.claude.com/docs/en/discover-plugins)
- [Plugin Marketplaces](https://code.claude.com/docs/en/plugin-marketplaces)
- [Plugins Reference](https://code.claude.com/docs/en/plugins-reference)
- [MCP Server Reference](https://modelcontextprotocol.io/)
- [Hướng Dẫn Cấu Hình Subagent](../04-subagents/README.md)
- [Hệ Thống Hook Reference](../06-hooks/README.md)

View File

@@ -0,0 +1,9 @@
{
"name": "devops-automation",
"version": "1.0.0",
"description": "Complete DevOps automation for deployment, monitoring, and incident response",
"author": {
"name": "Community"
},
"license": "MIT"
}

View File

@@ -0,0 +1,107 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../../resources/logos/claude-howto-logo.svg">
</picture>
# DevOps Automation Plugin
Complete DevOps automation for deployment, monitoring, and incident response.
## Features
✅ Automated deployments
✅ Rollback procedures
✅ System health monitoring
✅ Incident response workflows
✅ Kubernetes integration
## Installation
```bash
/plugin install devops-automation
```
## What's Included
### Slash Commands
- `/deploy` - Deploy to production or staging
- `/rollback` - Rollback to previous version
- `/status` - Check system health
- `/incident` - Handle production incidents
### Subagents
- `deployment-specialist` - Deployment operations
- `incident-commander` - Incident coordination
- `alert-analyzer` - System health analysis
### MCP Servers
- Kubernetes integration
### Scripts
- `deploy.sh` - Deployment automation
- `rollback.sh` - Rollback automation
- `health-check.sh` - Health check utilities
### Hooks
- `pre-deploy.js` - Pre-deployment validation
- `post-deploy.js` - Post-deployment tasks
## Usage
### Deploy to Staging
```
/deploy staging
```
### Deploy to Production
```
/deploy production
```
### Rollback
```
/rollback production
```
### Check Status
```
/status
```
### Handle Incident
```
/incident
```
## Requirements
- Claude Code 1.0+
- Kubernetes CLI (kubectl)
- Cluster access configured
## Configuration
Set up your Kubernetes config:
```bash
export KUBECONFIG=~/.kube/config
```
## Example Workflow
```
User: /deploy production
Claude:
1. Runs pre-deploy hook (validates kubectl, cluster connection)
2. Delegates to deployment-specialist subagent
3. Runs deploy.sh script
4. Monitors deployment progress via Kubernetes MCP
5. Runs post-deploy hook (waits for pods, smoke tests)
6. Provides deployment summary
Result:
✅ Deployment complete
📦 Version: v2.1.0
🚀 Pods: 3/3 ready
⏱️ Time: 2m 34s
```

View File

@@ -0,0 +1,14 @@
---
name: alert-analyzer
description: Analyzes monitoring alerts and system metrics
tools: read, grep, bash
---
# Alert Analyzer
Analyzes system health and alerts:
- Alert correlation
- Trend analysis
- Root cause identification
- Metric visualization
- Proactive issue detection

View File

@@ -0,0 +1,14 @@
---
name: deployment-specialist
description: Handles all deployment operations
tools: read, write, bash, grep
---
# Deployment Specialist
Expert in deployment operations:
- Blue-green deployments
- Canary releases
- Rollback procedures
- Health checks
- Database migrations

View File

@@ -0,0 +1,14 @@
---
name: incident-commander
description: Coordinates incident response
tools: read, write, bash, grep
---
# Incident Commander
Manages incident response:
- Severity assessment
- Team coordination
- Status updates
- Resolution tracking
- Post-mortem facilitation

View File

@@ -0,0 +1,15 @@
---
name: Deploy
description: Deploy application to production or staging
---
# Deploy Application
Execute deployment workflow:
1. Run pre-deployment checks
2. Build application
3. Run tests
4. Deploy to target environment
5. Run health checks
6. Notify team on Slack

View File

@@ -0,0 +1,16 @@
---
name: Incident Response
description: Handle production incidents with structured response
---
# Incident Response
Structured incident response workflow:
1. Create incident record
2. Assess severity and impact
3. Notify on-call team
4. Gather diagnostic information
5. Coordinate response efforts
6. Document resolution
7. Schedule post-mortem

View File

@@ -0,0 +1,14 @@
---
name: Rollback
description: Rollback to previous deployment
---
# Rollback Deployment
Rollback to previous stable version:
1. Identify previous deployment
2. Verify rollback target is healthy
3. Execute rollback procedure
4. Run health checks
5. Notify team

View File

@@ -0,0 +1,15 @@
---
name: System Status
description: Check overall system health and status
---
# System Status Check
Check system health across all services:
1. Query Kubernetes pod status
2. Check database connections
3. Monitor API response times
4. Review error rates
5. Check resource utilization
6. Report overall health

View File

@@ -0,0 +1,34 @@
#!/usr/bin/env node
/**
* Post-deployment hook
* Runs after deployment completes
*/
async function postDeploy() {
console.log('Running post-deployment tasks...');
const { execSync } = require('child_process');
// Wait for pods to be ready
console.log('Waiting for pods to be ready...');
try {
execSync('kubectl wait --for=condition=ready pod -l app=myapp --timeout=300s', {
stdio: 'inherit'
});
} catch (error) {
console.error('❌ Pods failed to become ready');
process.exit(1);
}
// Run smoke tests
console.log('Running smoke tests...');
// Add your smoke test commands here
console.log('✅ Post-deployment tasks complete');
}
postDeploy().catch(error => {
console.error('Post-deploy hook failed:', error);
process.exit(1);
});

View File

@@ -0,0 +1,35 @@
#!/usr/bin/env node
/**
* Pre-deployment hook
* Validates environment and prerequisites before deployment
*/
async function preDeploy() {
console.log('Running pre-deployment checks...');
const { execSync } = require('child_process');
// Check if kubectl is installed
try {
execSync('which kubectl', { stdio: 'pipe' });
} catch (error) {
console.error('❌ kubectl not found. Please install Kubernetes CLI.');
process.exit(1);
}
// Check if connected to cluster
try {
execSync('kubectl cluster-info', { stdio: 'pipe' });
} catch (error) {
console.error('❌ Not connected to Kubernetes cluster');
process.exit(1);
}
console.log('✅ Pre-deployment checks passed');
}
preDeploy().catch(error => {
console.error('Pre-deploy hook failed:', error);
process.exit(1);
});

View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"kubernetes": {
"command": "npx",
"args": ["@modelcontextprotocol/server-kubernetes"],
"env": {
"KUBECONFIG": "${KUBECONFIG}"
}
}
}
}

View File

@@ -0,0 +1,28 @@
#!/bin/bash
set -e
echo "🚀 Starting deployment..."
# Load environment
ENV=${1:-staging}
echo "📦 Target environment: $ENV"
# Pre-deployment checks
echo "✓ Running pre-deployment checks..."
npm run lint
npm test
# Build
echo "🔨 Building application..."
npm run build
# Deploy
echo "🚢 Deploying to $ENV..."
kubectl apply -f k8s/$ENV/
# Health check
echo "🏥 Running health checks..."
sleep 10
curl -f http://api.$ENV.example.com/health
echo "✅ Deployment complete!"

View File

@@ -0,0 +1,30 @@
#!/bin/bash
echo "🏥 System Health Check"
echo "===================="
ENV=${1:-production}
# Check API
echo -n "API: "
if curl -sf http://api.$ENV.example.com/health > /dev/null; then
echo "✅ Healthy"
else
echo "❌ Unhealthy"
fi
# Check Database
echo -n "Database: "
if pg_isready -h db.$ENV.example.com > /dev/null 2>&1; then
echo "✅ Healthy"
else
echo "❌ Unhealthy"
fi
# Check Pods
echo -n "Kubernetes Pods: "
PODS_READY=$(kubectl get pods -n $ENV --no-headers | grep "Running" | wc -l)
PODS_TOTAL=$(kubectl get pods -n $ENV --no-headers | wc -l)
echo "$PODS_READY/$PODS_TOTAL ready"
echo "===================="

View File

@@ -0,0 +1,25 @@
#!/bin/bash
set -e
echo "⏪ Starting rollback..."
ENV=${1:-staging}
echo "📦 Target environment: $ENV"
# Get previous deployment
PREVIOUS=$(kubectl rollout history deployment/app -n $ENV | tail -2 | head -1 | awk '{print $1}')
echo "🔄 Rolling back to revision: $PREVIOUS"
# Execute rollback
kubectl rollout undo deployment/app -n $ENV
# Wait for rollback
echo "⏳ Waiting for rollback to complete..."
kubectl rollout status deployment/app -n $ENV
# Health check
echo "🏥 Running health checks..."
sleep 5
curl -f http://api.$ENV.example.com/health
echo "✅ Rollback complete!"

View File

@@ -0,0 +1,9 @@
{
"name": "documentation",
"version": "1.0.0",
"description": "Comprehensive documentation generation and maintenance",
"author": {
"name": "Community"
},
"license": "MIT"
}

View File

@@ -0,0 +1,119 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../../resources/logos/claude-howto-logo.svg">
</picture>
# Documentation Plugin
Comprehensive documentation generation and maintenance for your project.
## Features
✅ API documentation generation
✅ README creation and updates
✅ Documentation synchronization
✅ Code comment improvements
✅ Example generation
## Installation
```bash
/plugin install documentation
```
## What's Included
### Slash Commands
- `/generate-api-docs` - Generate API documentation
- `/generate-readme` - Create or update README
- `/sync-docs` - Sync docs with code changes
- `/validate-docs` - Validate documentation
### Subagents
- `api-documenter` - API documentation specialist
- `code-commentator` - Code comment improvements
- `example-generator` - Code example creation
### Templates
- `api-endpoint.md` - API endpoint documentation template
- `function-docs.md` - Function documentation template
- `adr-template.md` - Architecture Decision Record template
### MCP Servers
- GitHub integration for documentation syncing
## Usage
### Generate API Documentation
```
/generate-api-docs
```
### Create README
```
/generate-readme
```
### Sync Documentation
```
/sync-docs
```
### Validate Documentation
```
/validate-docs
```
## Requirements
- Claude Code 1.0+
- GitHub access (optional)
## Example Workflow
```
User: /generate-api-docs
Claude:
1. Scans all API endpoints in /src/api/
2. Delegates to api-documenter subagent
3. Extracts function signatures and JSDoc
4. Organizes by module/endpoint
5. Uses api-endpoint.md template
6. Generates comprehensive markdown docs
7. Includes curl, JavaScript, and Python examples
Result:
✅ API documentation generated
📄 Files created:
- docs/api/users.md
- docs/api/auth.md
- docs/api/products.md
📊 Coverage: 23/23 endpoints documented
```
## Templates Usage
### API Endpoint Template
Use for documenting REST API endpoints with full examples.
### Function Documentation Template
Use for documenting individual functions/methods.
### ADR Template
Use for documenting architectural decisions.
## Configuration
Set up GitHub token for documentation syncing:
```bash
export GITHUB_TOKEN="your_github_token"
```
## Best Practices
- Keep documentation close to code
- Update docs with code changes
- Include practical examples
- Validate regularly
- Use templates for consistency

View File

@@ -0,0 +1,14 @@
---
name: api-documenter
description: API documentation specialist
tools: read, write, grep
---
# API Documenter
Creates comprehensive API documentation:
- Endpoint documentation
- Parameter descriptions
- Response schemas
- Code examples (curl, JS, Python)
- Error codes

View File

@@ -0,0 +1,14 @@
---
name: code-commentator
description: Code comment and inline documentation specialist
tools: read, write, edit
---
# Code Commentator
Improves code documentation:
- JSDoc/docstring comments
- Inline explanations
- Parameter descriptions
- Return type documentation
- Usage examples

View File

@@ -0,0 +1,14 @@
---
name: example-generator
description: Code example and tutorial specialist
tools: read, write
---
# Example Generator
Creates practical code examples:
- Getting started guides
- Common use cases
- Integration examples
- Best practices
- Troubleshooting scenarios

View File

@@ -0,0 +1,15 @@
---
name: Generate API Documentation
description: Generate comprehensive API documentation from source code
---
# API Documentation Generator
Generate complete API documentation:
1. Scan API endpoints
2. Extract function signatures and JSDoc
3. Organize by module/endpoint
4. Create markdown with examples
5. Include request/response schemas
6. Add error documentation

View File

@@ -0,0 +1,15 @@
---
name: Generate README
description: Create or update project README
---
# README Generator
Generate comprehensive README:
1. Project overview and description
2. Installation instructions
3. Usage examples
4. API documentation links
5. Contributing guidelines
6. License information

View File

@@ -0,0 +1,14 @@
---
name: Sync Documentation
description: Sync documentation with code changes
---
# Documentation Sync
Synchronize documentation with codebase:
1. Detect code changes
2. Identify outdated documentation
3. Update affected docs
4. Verify examples still work
5. Update version numbers

View File

@@ -0,0 +1,14 @@
---
name: Validate Documentation
description: Validate documentation for completeness and accuracy
---
# Documentation Validation
Validate documentation quality:
1. Check for broken links
2. Verify code examples
3. Ensure completeness
4. Check formatting
5. Validate against actual code

View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}

View File

@@ -0,0 +1,39 @@
# ADR [Number]: [Title]
## Status
[Proposed | Accepted | Deprecated | Superseded]
## Context
What is the issue that we're seeing that is motivating this decision or change?
## Decision
What is the change that we're proposing and/or doing?
## Consequences
What becomes easier or more difficult to do because of this change?
### Positive
- Benefit 1
- Benefit 2
### Negative
- Drawback 1
- Drawback 2
### Neutral
- Consideration 1
- Consideration 2
## Alternatives Considered
What other options were considered and why were they not chosen?
### Alternative 1
Description and reason for not choosing.
### Alternative 2
Description and reason for not choosing.
## References
- Related ADRs
- External documentation
- Discussion links

View File

@@ -0,0 +1,101 @@
# [METHOD] /api/v1/[endpoint]
## Description
Brief explanation of what this endpoint does.
## Authentication
Required authentication method (e.g., Bearer token).
## Parameters
### Path Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| id | string | Yes | Resource ID |
### Query Parameters
| Name | Type | Required | Description |
|------|------|----------|-------------|
| page | integer | No | Page number (default: 1) |
| limit | integer | No | Items per page (default: 20) |
### Request Body
```json
{
"field": "value"
}
```
## Responses
### 200 OK
```json
{
"success": true,
"data": {
"id": "123",
"name": "Example"
}
}
```
### 400 Bad Request
```json
{
"success": false,
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input"
}
}
```
### 404 Not Found
```json
{
"success": false,
"error": {
"code": "NOT_FOUND",
"message": "Resource not found"
}
}
```
## Examples
### cURL
```bash
curl -X GET "https://api.example.com/api/v1/endpoint" \
-H "Authorization: Bearer YOUR_TOKEN" \
-H "Content-Type: application/json"
```
### JavaScript
```javascript
const response = await fetch('/api/v1/endpoint', {
headers: {
'Authorization': 'Bearer token',
'Content-Type': 'application/json'
}
});
const data = await response.json();
```
### Python
```python
import requests
response = requests.get(
'https://api.example.com/api/v1/endpoint',
headers={'Authorization': 'Bearer token'}
)
data = response.json()
```
## Rate Limits
- 1000 requests per hour for authenticated users
- 100 requests per hour for public endpoints
## Related Endpoints
- [GET /api/v1/related](#)
- [POST /api/v1/related](#)

View File

@@ -0,0 +1,50 @@
# Function: `functionName`
## Description
Brief description of what the function does.
## Signature
```typescript
function functionName(param1: Type1, param2: Type2): ReturnType
```
## Parameters
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| param1 | Type1 | Yes | Description of param1 |
| param2 | Type2 | No | Description of param2 |
## Returns
**Type**: `ReturnType`
Description of what is returned.
## Throws
- `Error`: When invalid input is provided
- `TypeError`: When wrong type is passed
## Examples
### Basic Usage
```typescript
const result = functionName('value1', 'value2');
console.log(result);
```
### Advanced Usage
```typescript
const result = functionName(
complexParam1,
{ option: true }
);
```
## Notes
- Additional notes or warnings
- Performance considerations
- Best practices
## See Also
- [Related Function](#)
- [API Documentation](#)

View File

@@ -0,0 +1,9 @@
{
"name": "pr-review",
"version": "1.0.0",
"description": "Complete PR review workflow with security, testing, and docs",
"author": {
"name": "Anthropic"
},
"license": "MIT"
}

View File

@@ -0,0 +1,91 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../../resources/logos/claude-howto-logo.svg">
</picture>
# PR Review Plugin
Complete PR review workflow with security, testing, and documentation checks.
## Features
✅ Security analysis
✅ Test coverage checking
✅ Documentation verification
✅ Code quality assessment
✅ Performance impact analysis
## Installation
```bash
/plugin install pr-review
```
## What's Included
### Slash Commands
- `/review-pr` - Comprehensive PR review
- `/check-security` - Security-focused review
- `/check-tests` - Test coverage analysis
### Subagents
- `security-reviewer` - Security vulnerability detection
- `test-checker` - Test coverage analysis
- `performance-analyzer` - Performance impact evaluation
### MCP Servers
- GitHub integration for PR data
### Hooks
- `pre-review.js` - Pre-review validation
## Usage
### Basic PR Review
```
/review-pr
```
### Security Check Only
```
/check-security
```
### Test Coverage Check
```
/check-tests
```
## Requirements
- Claude Code 1.0+
- GitHub access
- Git repository
## Configuration
Set up your GitHub token:
```bash
export GITHUB_TOKEN="your_github_token"
```
## Example Workflow
```
User: /review-pr
Claude:
1. Runs pre-review hook (validates git repo)
2. Fetches PR data via GitHub MCP
3. Delegates security review to security-reviewer subagent
4. Delegates testing to test-checker subagent
5. Delegates performance to performance-analyzer subagent
6. Synthesizes all findings
7. Provides comprehensive review report
Result:
✅ Security: No critical issues found
⚠️ Testing: Coverage is 65%, recommend 80%+
✅ Performance: No significant impact
📝 Recommendations: Add tests for edge cases
```

View File

@@ -0,0 +1,13 @@
---
name: performance-analyzer
description: Performance impact analysis
tools: read, grep, bash
---
# Performance Analyzer
Evaluates performance impact of changes:
- Algorithm complexity
- Database query efficiency
- Memory usage
- Caching opportunities

View File

@@ -0,0 +1,13 @@
---
name: security-reviewer
description: Security-focused code review
tools: read, grep, diff
---
# Security Reviewer
Specializes in finding security vulnerabilities:
- Authentication/authorization issues
- Data exposure
- Injection attacks
- Secure configuration

View File

@@ -0,0 +1,13 @@
---
name: test-checker
description: Test coverage and quality analysis
tools: read, bash, grep
---
# Test Checker
Analyzes test coverage and quality:
- Coverage percentage
- Missing test cases
- Test quality assessment
- Edge case identification

View File

@@ -0,0 +1,14 @@
---
name: Security Check
description: Run security-focused code review
---
# Security Check
Perform focused security analysis on code changes:
1. Authentication/authorization checks
2. Data exposure risks
3. Injection vulnerabilities
4. Cryptographic weaknesses
5. Sensitive data in logs

View File

@@ -0,0 +1,14 @@
---
name: Test Coverage Check
description: Verify test coverage and quality
---
# Test Coverage Check
Analyze test coverage and quality:
1. Check test coverage percentage
2. Identify untested code paths
3. Review test quality
4. Suggest missing test cases
5. Verify edge cases are covered

View File

@@ -0,0 +1,14 @@
---
name: Review PR
description: Start comprehensive PR review with security and testing checks
---
# PR Review
This command initiates a complete pull request review including:
1. Security analysis
2. Test coverage verification
3. Documentation updates
4. Code quality checks
5. Performance impact assessment

View File

@@ -0,0 +1,37 @@
#!/usr/bin/env node
/**
* Pre-review hook
* Runs before starting PR review to ensure prerequisites are met
*/
async function preReview() {
console.log('Running pre-review checks...');
// Check if git repository
const { execSync } = require('child_process');
try {
execSync('git rev-parse --git-dir', { stdio: 'pipe' });
} catch (error) {
console.error('❌ Not a git repository');
process.exit(1);
}
// Check for uncommitted changes
try {
const status = execSync('git status --porcelain', { encoding: 'utf-8' });
if (status.trim()) {
console.warn('⚠️ Warning: Uncommitted changes detected');
}
} catch (error) {
console.error('❌ Failed to check git status');
process.exit(1);
}
console.log('✅ Pre-review checks passed');
}
preReview().catch(error => {
console.error('Pre-review hook failed:', error);
process.exit(1);
});

View File

@@ -0,0 +1,11 @@
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}

299
vi/08-checkpoints/README.md Normal file
View File

@@ -0,0 +1,299 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Checkpoints và Rewind / Checkpoints and Rewind
Checkpoints cho phép bạn lưu trạng thái hội thoại và quay lại các điểm trước đó trong phiên Claude Code của bạn. Điều này vô giá khi khám phá các cách tiếp cận khác nhau, phục hồi từ sai lầm, hoặc so sánh các giải pháp thay thế.
## Tổng Quan / Overview
Checkpoints cho phép bạn lưu trạng thái hội thoại và quay lại các điểm trước đó, cho phép thử nghiệm an toàn và khám phá nhiều cách tiếp cận. Chúng là các snapshot của trạng thái hội thoại của bạn, bao gồm:
- Tất cả các trao đổi tin nhắn
- Các sửa đổi file được thực hiện
- Lịch sử sử dụng công cụ
- Ngữ cảnh phiên
Checkpoints vô giá khi khám phá các cách tiếp cận khác nhau, phục hồi từ sai lầm, hoặc so sánh các giải pháp thay thế.
## Các Khái Niệm Chính / Key Concepts
| Khái Niệm | Mô Tả |
|---------|-------------|
| **Checkpoint** | Snapshot của trạng thái hội thoại bao gồm tin nhắn, files, và ngữ cảnh |
| **Rewind** | Quay lại checkpoint trước đó, loại bỏ các thay đổi tiếp theo |
| **Điểm Nhánh** | Checkpoint từ đó nhiều cách tiếp cận được khám phá |
## Truy Cập Checkpoints / Accessing Checkpoints
Bạn có thể truy cập và quản lý checkpoints theo hai cách chính:
### Sử Dụng Phím Tắt / Using Keyboard Shortcut
Nhấn `Esc` hai lần (`Esc` + `Esc`) để mở giao diện checkpoint và duyệt các checkpoints đã lưu.
### Sử Dụng Lệnh Slash / Using Slash Command
Sử dụng lệnh `/rewind` (bí danh: `/checkpoint`) để truy cập nhanh:
```bash
# Mở giao diện rewind
/rewind
# Hoặc sử dụng bí danh
/checkpoint
```
## Các Tùy Chọn Rewind / Rewind Options
Khi bạn rewind, bạn được trình bày một menu năm tùy chọn:
1. **Khôi phục code và hội thoại** -- Hoàn nguyên cả files và tin nhắn đến checkpoint đó
2. **Khôi phục hội thoại** -- Chỉ rewind tin nhắn, giữ code hiện tại của bạn như-is
3. **Khôi phục code** -- Chỉ hoàn nguyên các thay đổi file, giữ toàn bộ lịch sử hội thoại
4. **Tóm tắt từ đây** -- Nén hội thoại từ điểm này thành tóm tắt được tạo bởi AI thay vì loại bỏ nó. Các tin nhắn gốc được bảo toàn trong transcript. Bạn có thể tùy chọn cung cấp hướng dẫn để tập trung tóm tắt vào các chủ đề cụ thể.
5. **Không sao cả** -- Hủy và quay lại trạng thái hiện tại
## Checkpoints Tự Động / Automatic Checkpoints
Claude Code tự động tạo checkpoints cho bạn:
- **Mọi prompt người dùng** - Một checkpoint mới được tạo với mỗi đầu vào người dùng
- **Liên tục** - Checkpoints tồn tại qua các phiên
- **Tự động dọn dẹp** - Checkpoints được tự động dọn dẹp sau 30 ngày
Điều này có nghĩa là bạn luôn có thể rewind đến bất kỳ điểm nào trước đó trong hội thoại của bạn, từ vài phút trước đến nhiều ngày trước.
## Các Trường Hợp Sử Dụng / Use Cases
| Kịch Bản | Workflow |
|----------|----------|
| **Khám Phá Cách Tiếp Cận** | Lưu → Thử A → Lưu → Rewind → Thử B → So Sánh |
| **Refactoring An Toàn** | Lưu → Refactor → Test → Nếu fail: Rewind |
| **A/B Testing** | Lưu → Thiết Kế A → Lưu → Rewind → Thiết Kế B → So Sánh |
| **Phục Hồi Sai Lầm** | Nhận thấy vấn đề → Rewind đến trạng thái tốt cuối |
## Sử Dụng Checkpoints / Using Checkpoints
### Xem và Rewind / Viewing and Rewinding
Nhấn `Esc` hai lần hoặc sử dụng `/rewind` để mở trình duyệt checkpoint. Bạn sẽ thấy danh sách tất cả các checkpoints có sẵn với timestamps. Chọn bất kỳ checkpoint nào để rewind đến trạng thái đó.
### Chi Tiết Checkpoint / Checkpoint Details
Mỗi checkpoint hiển thị:
- Timestamp khi nó được tạo
- Các file đã được sửa đổi
- Số lượng tin nhắn trong hội thoại
- Các công cụ đã được sử dụng
## Ví Dụ Thực Tiễn / Practical Examples
### Ví Dụ 1: Khám Phá Các Cách Tiếp Cận Khác Nhau / Example 1: Exploring Different Approaches
```
User: Hãy thêm một lớp caching vào API
Claude: Tôi sẽ thêm Redis caching vào các API endpoints của bạn...
[Thực hiện thay đổi tại checkpoint A]
User: Thực ra, hãy thử in-memory caching thay thế
Claude: Tôi sẽ rewind để khám phá một cách tiếp cận khác...
[User nhấn Esc+Esc và rewinds đến checkpoint A]
[Triển khai in-memory caching tại checkpoint B]
User: Bây giờ tôi có thể so sánh cả hai cách tiếp cận
```
### Ví Dụ 2: Phục Hồi Từ Sai Lầm / Example 2: Recovering from Mistakes
```
User: Refactor module xác thực để sử dụng JWT
Claude: Tôi sẽ refactor module xác thực...
[Thực hiện các thay đổi rộng rãi]
User: Đợi, điều đó làm hỏng tích hợp OAuth. Hãy quay lại.
Claude: Tôi sẽ giúp bạn rewind đến trước khi refactor...
[User nhấn Esc+Esc và chọn checkpoint trước khi refactor]
User: Hãy thử một cách tiếp cận thận trọng hơn lần này
```
### Ví Dụ 3: Thử Nghiệm An Toàn / Example 3: Safe Experimentation
```
User: Hãy thử viết lại điều này theo phong cách functional
[Tạo checkpoint trước khi thử nghiệm]
Claude: [Thực hiện các thay đổi thử nghiệm]
User: Các tests đang fail. Hãy rewind.
[User nhấn Esc+Esc và rewinds đến checkpoint]
Claude: Tôi đã rewind các thay đổi. Hãy thử một cách tiếp cận khác.
```
### Ví Dụ 4: Các Cách Tiếp Cận Nhánh / Example 4: Branching Approaches
```
User: Tôi muốn so sánh hai thiết kế database
[Lưu ý checkpoint - gọi là "Bắt Đầu"]
Claude: Tôi sẽ tạo thiết kế đầu tiên...
[Triển khai Schema A]
User: Bây giờ để tôi quay lại và thử cách tiếp cận thứ hai
[User nhấn Esc+Esc và rewinds đến "Bắt Đầu"]
Claude: Bây giờ tôi sẽ triển khai Schema B...
[Triển khai Schema B]
User: Tuyệt! Bây giờ tôi có cả hai schemas để chọn
```
## Giữ Lại Checkpoint / Checkpoint Retention
Claude Code tự động quản lý checkpoints của bạn:
- Checkpoints được tạo tự động với mọi prompt người dùng
- Checkpoints cũ được giữ lên đến 30 ngày
- Checkpoints được tự động dọn dẹp để ngăn chặn tăng trưởng lưu trữ không giới hạn
## Các Mẫu Workflow / Workflow Patterns
### Chiến Lược Nhánh Để Khám Phá / Branching Strategy for Exploration
Khi khám phá nhiều cách tiếp cận:
```
1. Bắt đầu với triển khai ban đầu → Checkpoint A
2. Thử Cách Tiếp Cận 1 → Checkpoint B
3. Rewind đến Checkpoint A
4. Thử Cách Tiếp Cận 2 → Checkpoint C
5. So sánh kết quả từ B và C
6. Chọn cách tiếp cận tốt nhất và tiếp tục
```
### Mẫu Refactoring An Toàn / Safe Refactoring Pattern
Khi thực hiện các thay đổi đáng kể:
```
1. Trạng thái hiện tại → Checkpoint (tự động)
2. Bắt đầu refactoring
3. Chạy tests
4. Nếu tests pass → Tiếp tục làm việc
5. Nếu tests fail → Rewind và thử cách tiếp cận khác
```
## Thực Hành Tốt Nhất / Best Practices
Vì checkpoints được tạo tự động, bạn có thể tập trung vào công việc của mình mà không phải lo lắng về việc lưu trạng thái thủ công. Tuy nhiên, hãy ghi nhớ các thực hành sau:
### Sử Dụng Checkpoints Hiệu Quả / Using Checkpoints Effectively
**Nên:**
- Review các checkpoints có sẵn trước khi rewind
- Sử dụng rewind khi bạn muốn khám phá các hướng khác nhau
- Giữ checkpoints để so sánh các cách tiếp cận khác nhau
- Hiểu những gì mỗi tùy chọn rewind làm (khôi phục code và hội thoại, khôi phục hội thoại, khôi phục code, hoặc tóm tắt)
**Không Nên:**
- Dựa vào checkpoints một mình để bảo toàn code
- Mong đợi checkpoints theo dõi các thay đổi file hệ thống file bên ngoài
- Sử dụng checkpoints như một thay thế cho git commits
## Cấu Hình / Configuration
Bạn có thể bật/tắt checkpoints tự động trong settings của bạn:
```json
{
"autoCheckpoint": true
}
```
- `autoCheckpoint`: Bật hoặc tắt tạo checkpoint tự động trên mọi prompt người dùng (mặc định: `true`)
## Hạn Chế / Limitations
Checkpoints có các hạn chế sau:
- **Các thay đổi lệnh Bash KHÔNG được theo dõi** - Các thao tác như `rm`, `mv`, `cp` trên hệ thống file không được ghi lại trong checkpoints
- **Các thay đổi bên ngoài KHÔNG được theo dõi** - Các thay đổi được thực hiện bên ngoài Claude Code (trong editor của bạn, terminal, v.v.) không được ghi lại
- **Không phải thay thế cho kiểm soát phiên bản** - Sử dụng git cho các thay đổi vĩnh viễn, có thể kiểm tra trong codebase của bạn
## Xử Lý Sự Cố / Troubleshooting
### Checkpoints Thiếu / Missing Checkpoints
**Vấn Đề**: Không tìm thấy checkpoint mong đợi
**Giải Pháp**:
- Kiểm tra nếu checkpoints đã bị xóa
- Xác minh rằng `autoCheckpoint` được bật trong settings của bạn
- Kiểm tra dung lượng đĩa
### Rewind Thất Bại / Rewind Failed
**Vấn Đề**: Không thể rewind đến checkpoint
**Giải Pháp**:
- Đảm bảo không có thay đổi chưa commit xung đột
- Kiểm tra nếu checkpoint bị hỏng
- Thử rewind đến một checkpoint khác
## Tích Hợp Với Git / Integration with Git
Checkpoints bổ sung (nhưng không thay thế) git:
| Tính Năng | Git | Checkpoints |
|---------|-----|-------------|
| Phạm Vi | Hệ thống file | Hội thoại + files |
| Liên Tục | Vĩnh viễn | Dựa trên phiên |
| Độ Chi Tiết | Commits | Bất kỳ điểm nào |
| Tốc Độ | Chậm hơn | Tức thì |
| Chia Sẻ | Có | Có hạn |
Sử dụng cả hai cùng nhau:
1. Sử dụng checkpoints để thử nghiệm nhanh
2. Sử dụng git commits cho các thay đổi đã hoàn thiện
3. Tạo checkpoint trước các thao tác git
4. Commit các trạng thái checkpoint thành công đến git
## Hướng Dẫn Bắt Đầu Nhanh / Quick Start Guide
### Workflow Cơ Bản / Basic Workflow
1. **Làm việc bình thường** - Claude Code tạo checkpoints tự động
2. **Muốn quay lại?** - Nhấn `Esc` hai lần hoặc sử dụng `/rewind`
3. **Chọn checkpoint** - Chọn từ danh sách để rewind
4. **Chọn những gì để khôi phục** - Chọn từ khôi phục code và hội thoại, khôi phục hội thoại, khôi phục code, tóm tắt từ đây, hoặc hủy
5. **Tiếp tục làm việc** - Bạn đã trở lại điểm đó
### Phím Tắt / Keyboard Shortcuts
- **`Esc` + `Esc`** - Mở trình duyệt checkpoint
- **`/rewind`** - Cách thay thế để truy cập checkpoints
- **`/checkpoint`** - Bí danh cho `/rewind`
## Biết Khi Nào Rewind: Giám Sát Ngữ Cảnh / Knowing When to Rewind: Context Monitoring
Checkpoints cho phép bạn quay lại — nhưng làm thế nào bạn biết *khi* bạn nên? Khi hội thoại của bạn tăng trưởng, cửa sổ ngữ cảnh của Claude được lấp đầy và chất lượng mô hình âm thầm giảm xuống. Bạn có thể đang shipping code từ một mô hình mù quáng một nửa mà không nhận ra.
**[cc-context-stats](https://github.com/luongnv89/cc-context-stats)** giải quyết điều này bằng cách thêm **vùng ngữ cảnh** thời gian thực vào thanh trạng thái Claude Code của bạn. Nó theo dõi nơi bạn đang ở trong cửa sổ ngữ cảnh — từ **Plan** (xanh lá, an toàn để lập kế hoạch và code) qua **Code** (vàng, tránh bắt đầu các kế hoạch mới) đến **Dump** (cam, hoàn thành và rewind). Khi bạn thấy vùng thay đổi, bạn biết đó là thời gian để checkpoint và bắt đầu tươi mới thay vì đẩy tiếp với đầu ra bị giảm sút.
## Các Khái Niệm Liên Quan / Related Concepts
- **[Tính Năng Nâng Cao](../09-advanced-features/)** - Chế độ lập kế hoạch và các khả năng nâng cao khác
- **[Quản Lý Memory](../02-memory/)** - Quản lý lịch sử hội thoại và ngữ cảnh
- **[Slash Commands](../01-slash-commands/)** - Các phím tắt do người dùng gọi
- **[Hooks](../06-hooks/)** - Tự động hóa dựa trên sự kiện
- **[Plugins](../07-plugins/)** - Các gói mở rộng được đóng gói
## Tài Nguyên Thêm / Additional Resources
- [Tài Liệu Checkpointing Chính Thức](https://code.claude.com/docs/en/checkpointing)
- [Hướng Dẫn Tính Năng Nâng Cao](../09-advanced-features/) - Extended thinking và các khả năng khác

View File

@@ -0,0 +1,339 @@
# Checkpoint Examples
Real-world examples of using checkpoints effectively in Claude Code.
Note: Checkpoints are created automatically with every user prompt. You do not need to manually save them. To rewind, press `Esc` twice (`Esc+Esc`) or use `/rewind` to open the checkpoint browser.
## Example 1: Database Migration
### Scenario
You need to migrate from MySQL to PostgreSQL but want to explore both a direct migration and a gradual dual-write approach.
### Workflow
```
User: Let's implement a direct migration from MySQL to PostgreSQL
[Checkpoint A created automatically]
Claude: I'll implement the direct migration...
[Changes database driver, updates queries, modifies schema]
User: Run the tests
[Checkpoint B created automatically]
Claude: Running tests...
❌ 15 tests failing - connection pool issues
User: This approach has issues. Let's try the dual-write pattern instead.
[User presses Esc+Esc, selects Checkpoint A, chooses "Restore code and conversation"]
User: Now implement a dual-write pattern where we write to both databases
Claude: I'll implement dual-write migration...
[Implements dual-write layer, gradual migration strategy]
User: Run the tests
Claude: Running tests...
✅ All tests passing
User: The dual-write approach is clearly safer. Let's commit this.
```
## Example 2: Performance Optimization
### Scenario
Multiple performance optimization strategies to try.
### Workflow
```
User: Let's optimize the API response time. Current: 450ms
[Checkpoint "Baseline" created automatically]
Claude: I'll add database query caching...
[Implements Redis caching]
User: Run performance tests
Claude: Results: 280ms average response time (38% improvement)
User: Let me try a different approach.
[User presses Esc+Esc, selects "Baseline" checkpoint, chooses "Restore code and conversation"]
User: Try database query optimization instead
Claude: I'll optimize database queries...
[Adds indexes, optimizes N+1 queries]
User: Run performance tests
Claude: Results: 180ms average response time (60% improvement)
User: Let me also try a third approach.
[User presses Esc+Esc, selects "Baseline" checkpoint, chooses "Restore code and conversation"]
User: Try response compression and CDN
Claude: I'll add compression and CDN...
[Implements gzip, sets up CDN]
User: Run performance tests
Claude: Results: 320ms average response time (29% improvement)
User: Query optimization was the best. Let me go back and combine it with caching.
[User presses Esc+Esc, selects the checkpoint after query optimization, chooses "Restore code and conversation"]
User: Now add Redis caching on top of these optimized queries
Claude: [Adds Redis caching on top of optimized queries]
User: Run performance tests
Claude: Results: 95ms average response time (79% improvement) 🎉
User: Perfect! This is the winner. Let's commit this.
```
## Example 3: UI/UX Iteration
### Scenario
Trying different layouts for a dashboard.
### Workflow
```
User: Let's redesign the dashboard with a sidebar layout
[Checkpoint "Start" created automatically]
Claude: [Implements sidebar layout]
User: Show me a screenshot
Claude: [Shows screenshot]
User: The sidebar feels cramped. Let's try a top navigation instead.
[User presses Esc+Esc, selects "Start" checkpoint, chooses "Restore code and conversation"]
User: Try a top navigation layout
Claude: [Implements top navigation]
User: Show me a screenshot
Claude: [Shows screenshot]
User: Better, but let's try a card-based grid layout
[User presses Esc+Esc, selects "Start" checkpoint, chooses "Restore code and conversation"]
User: Try a card-based grid layout
Claude: [Implements card grid]
User: Show me a screenshot
Claude: [Shows screenshot]
User: This is great! But can we combine the top nav with the card grid?
[User presses Esc+Esc, selects the checkpoint after the card grid, chooses "Restore code and conversation"]
User: Add top navigation to the card grid layout
Claude: [Adds top navigation to card grid]
User: Perfect! This is the final design.
```
## Example 4: Debugging Session
### Scenario
Hunting down a tricky bug with multiple hypotheses.
### Workflow
```
User: There's a memory leak in the application
[Checkpoint "Before debugging" created automatically]
Claude: Let me investigate...
[Analyzes code]
User: I think it's in the event listeners. Let's fix those.
Claude: [Fixes event listener cleanup]
User: Run memory profiler
Claude: Still leaking memory - event listeners weren't the issue
User: Let me go back and try a different hypothesis.
[User presses Esc+Esc, selects "Before debugging" checkpoint, chooses "Restore code and conversation"]
User: Maybe it's the database connections?
Claude: [Implements connection pooling fixes]
User: Run memory profiler
Claude: Still leaking - not the connections either
User: Let me go back and try another angle.
[User presses Esc+Esc, selects "Before debugging" checkpoint, chooses "Restore code and conversation"]
User: Let's check for circular references
Claude: [Finds and fixes circular references in cache]
User: Run memory profiler
Claude: ✅ Memory leak fixed! The circular references in the caching layer were the culprit.
User: Excellent! Let's commit this fix.
```
## Example 5: API Design Evolution
### Scenario
Designing a REST API with multiple iterations.
### Workflow
```
User: Create a REST API for our blog platform
[Checkpoint "Before API design" created automatically]
Claude: [Creates basic CRUD API]
User: This is too simple. Let's add pagination and filtering
Claude: [Adds pagination and filtering]
User: We need better resource relationships
Claude: [Implements HATEOAS links]
User: Actually, let's try GraphQL instead of REST
[User presses Esc+Esc, selects "Before API design" checkpoint, chooses "Restore code and conversation"]
User: Implement a GraphQL API for our blog platform instead
Claude: [Implements GraphQL API]
User: I think REST is better for our use case.
[User presses Esc+Esc, selects the checkpoint after HATEOAS, chooses "Restore code and conversation"]
User: Let's finalize the REST approach.
```
## Example 6: Configuration Management
### Scenario
Testing different configuration approaches.
### Workflow
```
User: Move configuration to environment variables
[Checkpoint "Original config" created automatically]
Claude: [Implements env var configuration]
User: Test in development
Claude: Works locally but deployment issues in production
User: Let me try a different approach.
[User presses Esc+Esc, selects "Original config" checkpoint, chooses "Restore code and conversation"]
User: Try a config file approach with validation
Claude: [Implements YAML config with JSON schema validation]
User: Test in development
Claude: ✅ Works well, good validation errors
User: Can we also support env vars for sensitive values?
Claude: [Adds env var override for secrets]
User: Test deployment
Claude: ✅ All environments working correctly
User: Perfect! This is production-ready.
```
## Example 7: Test Strategy
### Scenario
Implementing comprehensive testing.
### Workflow
```
User: Add unit tests for the auth module
[Checkpoint created automatically]
Claude: [Adds Jest unit tests]
User: Run tests
Claude: 45 tests passing, 78% coverage
User: Add integration tests too
Claude: [Adds integration tests]
User: Run tests
Claude: 89 tests passing, 92% coverage, but tests are slow (3 minutes)
User: The tests are too slow. Let's optimize.
Claude: [Optimizes test setup, adds parallel execution]
User: Run tests
Claude: 89 tests passing, 92% coverage, 35 seconds ✅
User: Great! Now add E2E tests for critical paths
Claude: [Adds Playwright E2E tests]
User: Run all tests
Claude: 112 tests passing, 94% coverage, 2 minutes
User: Perfect balance of coverage and speed!
```
## Example 8: Using Summarize from Checkpoint
### Scenario
After a long debugging session, you want to condense the conversation while preserving context.
### Workflow
```
User: [After 20+ messages of debugging and exploration]
[User presses Esc+Esc, selects an early checkpoint, chooses "Summarize from here"]
[Optionally provides instructions: "Focus on what we tried and what worked"]
Claude: [Generates a summary of the conversation from that point forward]
[Original messages are preserved in the transcript]
[The summary replaces the visible conversation, reducing context window usage]
User: Now let's continue with the approach that worked.
```
## Key Takeaways
1. **Checkpoints are automatic**: Every user prompt creates a checkpoint -- no manual saving needed
2. **Use Esc+Esc or /rewind**: These are the two ways to access the checkpoint browser
3. **Choose the right restore option**: Restore code, conversation, both, or summarize depending on your needs
4. **Don't fear experimentation**: Checkpoints make it safe to try radical changes
5. **Combine with git**: Use checkpoints for exploration, git for finalized work
6. **Summarize long sessions**: Use "Summarize from here" to keep conversations manageable

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,270 @@
{
"description": "Example Claude Code configurations for different use cases",
"examples": {
"development": {
"name": "Development Environment",
"description": "Configuration for active development work",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0.7
},
"planning": {
"autoEnter": true,
"complexityThreshold": 3,
"requireApproval": true
},
"permissions": {
"mode": "unrestricted"
},
"backgroundTasks": {
"enabled": true,
"maxConcurrentTasks": 3
},
"hooks": {
"PreToolUse:Write": "prettier --write ${file_path}",
"PostToolUse:Write": "eslint ${file_path}",
"PreCommit": "npm test"
}
}
},
"code_review": {
"name": "Code Review Mode",
"description": "Configuration for reviewing code without modifications",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0.3
},
"permissions": {
"mode": "plan"
},
"extendedThinking": {
"enabled": true,
"showThinkingProcess": true
},
"planning": {
"autoEnter": false
}
}
},
"learning": {
"name": "Learning Mode",
"description": "Configuration for learning and experimentation",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0.5
},
"permissions": {
"mode": "confirm"
},
"extendedThinking": {
"enabled": true,
"showThinkingProcess": true
},
"planning": {
"autoEnter": true,
"requireApproval": true,
"showTimeEstimates": true
},
"checkpoints": {
"autoCheckpoint": true
}
}
},
"production": {
"name": "Production Deployment",
"description": "Configuration for production operations with safety checks",
"config": {
"general": {
"model": "claude-opus-4",
"temperature": 0.1
},
"permissions": {
"mode": "confirm",
"requireConfirmationFor": ["Bash", "Git", "Write", "Edit"]
},
"hooks": {
"PreCommit": "npm test && npm run lint && npm run build",
"PrePush": "npm run test:e2e",
"PostPush": "~/.claude/hooks/notify-team.sh"
},
"checkpoints": {
"autoCheckpoint": true
},
"planning": {
"autoEnter": true,
"requireApproval": true
}
}
},
"ci_cd": {
"name": "CI/CD Pipeline",
"description": "Configuration for automated CI/CD operations",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0
},
"permissions": {
"mode": "unrestricted"
},
"headless": {
"exitOnError": true,
"verbose": true,
"timeout": 3600
},
"logging": {
"level": "debug",
"file": "./ci-claude.log"
},
"planning": {
"autoEnter": false,
"requireApproval": false
}
}
},
"security_audit": {
"name": "Security Audit",
"description": "Configuration for security-focused code analysis",
"config": {
"general": {
"model": "claude-opus-4",
"temperature": 0.2
},
"permissions": {
"mode": "plan"
},
"extendedThinking": {
"enabled": true,
"showThinkingProcess": true,
"minThinkingTime": 10
},
"hooks": {
"PostToolUse:Read": "~/.claude/hooks/security-scan.sh ${file_path}"
}
}
},
"performance_optimization": {
"name": "Performance Optimization",
"description": "Configuration for performance analysis and optimization",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0.4
},
"planning": {
"autoEnter": true,
"requireApproval": true
},
"backgroundTasks": {
"enabled": true,
"maxConcurrentTasks": 5
},
"checkpoints": {
"autoCheckpoint": true
}
}
},
"pair_programming": {
"name": "Pair Programming",
"description": "Configuration for collaborative development",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0.6
},
"permissions": {
"mode": "confirm"
},
"planning": {
"autoEnter": true,
"requireApproval": true,
"showTimeEstimates": true
},
"extendedThinking": {
"enabled": true,
"showThinkingProcess": true
},
"ui": {
"compactMode": false,
"showProgress": true
}
}
},
"refactoring": {
"name": "Large Refactoring",
"description": "Configuration for major refactoring work",
"config": {
"general": {
"model": "claude-opus-4",
"temperature": 0.3
},
"planning": {
"autoEnter": true,
"requireApproval": true,
"showTimeEstimates": true
},
"checkpoints": {
"autoCheckpoint": true
},
"hooks": {
"PreToolUse:Edit": "~/.claude/hooks/backup-file.sh ${file_path}",
"PostToolUse:Edit": "npm test -- --findRelatedTests ${file_path}"
},
"permissions": {
"mode": "confirm"
}
}
},
"autonomous": {
"name": "Autonomous Development",
"description": "Configuration for autonomous work with auto mode safety checks",
"config": {
"general": {
"model": "claude-sonnet-4-6",
"temperature": 0.5
},
"permissions": {
"mode": "auto"
},
"sandbox": {
"enabled": true,
"failIfUnavailable": false
},
"backgroundTasks": {
"enabled": true,
"maxConcurrentTasks": 3
}
}
},
"documentation": {
"name": "Documentation Writing",
"description": "Configuration for writing documentation",
"config": {
"general": {
"model": "claude-sonnet-4-5",
"temperature": 0.7
},
"permissions": {
"mode": "unrestricted"
},
"hooks": {
"PostToolUse:Write": "markdownlint ${file_path}"
}
}
}
}
}

View File

@@ -0,0 +1,533 @@
# Planning Mode Examples
Real-world examples demonstrating effective use of planning mode in Claude Code.
## Example 1: Building a REST API
### Without Planning Mode
```
User: Build a REST API for a blog
Claude: I'll create the API...
[Starts coding immediately, may miss requirements]
```
### With Planning Mode
```
User: /plan Build a REST API for a blog
Claude: Let me create a comprehensive plan for the blog API.
## Blog REST API Implementation Plan
### Phase 1: Project Setup (15 min)
1. Initialize Node.js project with Express
2. Set up TypeScript configuration
3. Install dependencies (express, pg, jwt, joi)
4. Configure environment variables
5. Set up project structure
### Phase 2: Database Layer (30 min)
6. Design database schema
- users table (id, email, password_hash, created_at)
- posts table (id, user_id, title, content, published, created_at, updated_at)
- comments table (id, post_id, user_id, content, created_at)
7. Create migration files
8. Set up database connection pool
9. Implement database models
### Phase 3: Authentication (45 min)
10. Implement user registration endpoint
11. Implement login endpoint with JWT
12. Create authentication middleware
13. Add password hashing with bcrypt
14. Implement token refresh logic
### Phase 4: Posts API (40 min)
15. GET /api/posts - List all published posts (with pagination)
16. GET /api/posts/:id - Get single post
17. POST /api/posts - Create new post (auth required)
18. PUT /api/posts/:id - Update post (auth required, ownership check)
19. DELETE /api/posts/:id - Delete post (auth required, ownership check)
20. GET /api/users/:id/posts - Get user's posts
### Phase 5: Comments API (30 min)
21. GET /api/posts/:id/comments - Get post comments
22. POST /api/posts/:id/comments - Add comment (auth required)
23. DELETE /api/comments/:id - Delete comment (auth required, ownership check)
### Phase 6: Validation & Error Handling (30 min)
24. Add request validation with Joi
25. Implement global error handler
26. Add input sanitization
27. Implement rate limiting
### Phase 7: Testing (60 min)
28. Write unit tests for models
29. Write integration tests for auth endpoints
30. Write integration tests for posts endpoints
31. Write integration tests for comments endpoints
32. Achieve 80%+ code coverage
### Phase 8: Documentation & Deployment (30 min)
33. Generate API documentation with Swagger
34. Create README with setup instructions
35. Add Docker configuration
36. Set up CI/CD pipeline
**Estimated Time**: 4.5 hours
**Files to Create**: ~25
**Key Technologies**: Express, PostgreSQL, JWT, TypeScript
**API Endpoints Summary**:
- Authentication: 2 endpoints
- Posts: 6 endpoints
- Comments: 3 endpoints
- Total: 11 endpoints
Ready to proceed? (yes/no/modify)
User: yes
Claude: Starting Phase 1: Project Setup...
[Implements each phase systematically]
```
## Example 2: Database Migration
### With Planning Mode
```
User: /plan Migrate from MongoDB to PostgreSQL
Claude: This is a complex migration. Let me create a detailed plan.
## MongoDB to PostgreSQL Migration Plan
### Phase 1: Analysis & Preparation (Day 1)
1. Analyze current MongoDB schema
2. Identify data relationships and constraints
3. Document current data volume and growth rate
4. Design equivalent PostgreSQL schema
5. Plan data type mappings
6. Identify potential migration challenges
### Phase 2: PostgreSQL Setup (Day 1)
7. Set up PostgreSQL database
8. Create schema with tables, indexes, constraints
9. Set up connection pooling
10. Configure backup strategy
### Phase 3: Dual-Write Implementation (Day 2-3)
11. Create database abstraction layer
12. Implement dual-write to both databases
13. Add data consistency checks
14. Deploy dual-write to staging
15. Monitor for issues
### Phase 4: Data Migration (Day 4)
16. Create data export scripts for MongoDB
17. Create data import scripts for PostgreSQL
18. Implement data transformation logic
19. Run initial migration on copy of production data
20. Validate migrated data integrity
### Phase 5: Gradual Cutover (Day 5-7)
21. Enable dual-write in production
22. Migrate historical data in batches
23. Continuously validate data consistency
24. Monitor both databases
25. Fix any data synchronization issues
### Phase 6: PostgreSQL Primary (Day 8)
26. Switch read operations to PostgreSQL
27. Monitor query performance
28. Optimize slow queries
29. Continue dual-write for safety
### Phase 7: MongoDB Retirement (Day 9-10)
30. Stop writing to MongoDB
31. Keep MongoDB as backup for 2 weeks
32. Remove MongoDB dependencies from code
33. Archive MongoDB data
34. Decommission MongoDB instance
**Estimated Time**: 10 days
**Risk Level**: High
**Rollback Strategy**: Keep MongoDB running with dual-write
**Success Criteria**:
- Zero data loss
- <5% performance regression
- All tests passing
**Key Risks**:
1. Data inconsistency during migration
2. Query performance degradation
3. Application downtime
4. Data loss
**Mitigation**:
- Dual-write pattern for safety
- Gradual cutover
- Continuous monitoring
- Quick rollback capability
Proceed with this plan? (yes/no/modify)
User: Modify - let's add a rollback plan for each phase
Claude: Updated plan with rollback procedures for each phase...
```
## Example 3: Frontend Refactoring
```
User: /plan Refactor our React app from class components to hooks
Claude: I'll create a systematic refactoring plan.
## React Class to Hooks Migration Plan
### Phase 1: Preparation & Analysis (2 hours)
1. Audit all class components (find all .jsx/.tsx files)
2. Categorize by complexity:
- Simple (state only): ~15 components
- Medium (lifecycle methods): ~23 components
- Complex (multiple lifecycle, refs): ~8 components
3. Identify third-party libraries that need updates
4. Create component dependency graph
5. Plan migration order (leaf nodes first)
### Phase 2: Setup & Tooling (1 hour)
6. Update React to v18+
7. Set up ESLint rules for hooks
8. Create conversion templates
9. Set up automated tests
10. Create checkpoint before starting
### Phase 3: Migrate Simple Components (4 hours)
11. Convert simple stateful components (15 components)
12. Replace this.state with useState
13. Replace this.setState with state setters
14. Test each component after conversion
15. Update tests
### Phase 4: Migrate Medium Components (8 hours)
16. Convert components with lifecycle methods (23 components)
17. Replace componentDidMount with useEffect
18. Replace componentDidUpdate with useEffect
19. Replace componentWillUnmount with useEffect cleanup
20. Test thoroughly
### Phase 5: Migrate Complex Components (12 hours)
21. Convert complex components (8 components)
22. Replace refs with useRef
23. Extract custom hooks for shared logic
24. Handle edge cases (multiple useEffect)
25. Extensive testing
### Phase 6: Shared Logic Extraction (6 hours)
26. Identify duplicated logic across components
27. Create custom hooks:
- useAuth
- useFetch
- useLocalStorage
- useDebounce
28. Refactor components to use custom hooks
29. Test custom hooks independently
### Phase 7: Performance Optimization (4 hours)
30. Add React.memo where needed
31. Optimize with useCallback
32. Optimize with useMemo
33. Profile and fix performance regressions
### Phase 8: Cleanup & Documentation (2 hours)
34. Remove unused class component utilities
35. Update documentation
36. Update coding guidelines
37. Create migration guide for team
**Estimated Time**: 5 days (39 hours)
**Files to Modify**: 46 components
**Risk Level**: Medium
**Migration Order**:
1. Leaf components (no dependencies)
2. Mid-level components
3. Top-level container components
4. App.jsx (last)
**Testing Strategy**:
- Unit tests for each component
- Integration tests for user flows
- Visual regression tests
- Performance benchmarks
**Success Metrics**:
- All tests passing
- No visual regressions
- Performance maintained or improved
- Bundle size not significantly increased
Proceed? (yes/no/modify)
```
## Example 4: Security Implementation
```
User: /plan Implement comprehensive security for our web app
Claude: Let me create a thorough security implementation plan.
## Web Application Security Implementation Plan
### Phase 1: Security Audit (Day 1)
1. Run automated security scanners (npm audit, Snyk)
2. Review dependencies for vulnerabilities
3. Check OWASP Top 10 compliance
4. Audit authentication flows
5. Review data handling practices
6. Document current security gaps
### Phase 2: Authentication Hardening (Day 2-3)
7. Implement strong password requirements
8. Add password strength meter
9. Implement rate limiting on login
10. Add account lockout after failed attempts
11. Implement 2FA (TOTP)
12. Add session management improvements
13. Implement secure password reset flow
### Phase 3: Authorization & Access Control (Day 3-4)
14. Implement RBAC (Role-Based Access Control)
15. Add permission checks on all endpoints
16. Implement principle of least privilege
17. Add audit logging for sensitive operations
18. Implement resource-level permissions
### Phase 4: Data Protection (Day 4-5)
19. Implement encryption at rest (sensitive fields)
20. Ensure TLS/SSL for all communications
21. Implement secure session storage
22. Add PII data masking in logs
23. Implement data retention policies
24. Add secure file upload handling
### Phase 5: Input Validation & Sanitization (Day 5-6)
25. Implement input validation on all endpoints
26. Add XSS protection (Content Security Policy)
27. Implement SQL injection prevention (parameterized queries)
28. Add CSRF protection
29. Implement request size limits
30. Add file upload type validation
### Phase 6: Security Headers & Configuration (Day 6)
31. Add security headers:
- Strict-Transport-Security
- X-Content-Type-Options
- X-Frame-Options
- X-XSS-Protection
- Content-Security-Policy
32. Configure CORS properly
33. Disable unnecessary HTTP methods
34. Remove server version headers
### Phase 7: Monitoring & Logging (Day 7)
35. Implement security event logging
36. Add anomaly detection
37. Set up intrusion detection
38. Implement real-time alerting
39. Create security dashboard
### Phase 8: Testing & Documentation (Day 8-9)
40. Perform penetration testing
41. Run security scanners
42. Test all security features
43. Create security documentation
44. Train team on security practices
45. Create incident response plan
### Phase 9: Compliance & Policies (Day 10)
46. GDPR compliance check
47. Create privacy policy
48. Implement data subject rights
49. Add cookie consent
50. Create security policies documentation
**Estimated Time**: 10 days
**Risk Level**: Critical
**Priority**: High
**Security Improvements Summary**:
- Authentication: 7 enhancements
- Authorization: 5 enhancements
- Data Protection: 6 enhancements
- Input Validation: 6 enhancements
- Infrastructure: 9 enhancements
- Monitoring: 5 enhancements
**Compliance**: OWASP Top 10, GDPR
**Success Criteria**:
- Zero critical vulnerabilities
- All OWASP Top 10 mitigated
- Security score >90/100
- All pen test issues resolved
Proceed? (yes/no/modify)
```
## Example 5: Performance Optimization
```
User: /plan Optimize our slow e-commerce website
Claude: Let me create a comprehensive performance optimization plan.
## E-commerce Performance Optimization Plan
### Phase 1: Performance Audit (4 hours)
1. Run Lighthouse audit
2. Analyze Chrome DevTools performance profile
3. Measure Core Web Vitals:
- LCP (Largest Contentful Paint)
- FID (First Input Delay)
- CLS (Cumulative Layout Shift)
4. Identify performance bottlenecks
5. Create baseline performance metrics
**Current Metrics**:
- LCP: 4.2s (target: <2.5s)
- FID: 280ms (target: <100ms)
- CLS: 0.25 (target: <0.1)
- Page Load: 8.3s (target: <3s)
### Phase 2: Image Optimization (6 hours)
6. Convert images to WebP format
7. Implement responsive images
8. Add lazy loading for images
9. Optimize image sizes (compression)
10. Implement CDN for images
11. Add image placeholders
**Expected Impact**: -40% load time
### Phase 3: Code Splitting & Lazy Loading (8 hours)
12. Implement route-based code splitting
13. Lazy load non-critical components
14. Split vendor bundles
15. Optimize chunk sizes
16. Implement dynamic imports
17. Add preloading for critical resources
**Expected Impact**: -30% initial bundle size
### Phase 4: Caching Strategy (6 hours)
18. Implement browser caching (Cache-Control)
19. Add service worker for offline support
20. Implement API response caching
21. Add Redis cache for database queries
22. Implement stale-while-revalidate
23. Configure CDN caching
**Expected Impact**: -50% API response time
### Phase 5: Database Optimization (8 hours)
24. Add database indexes
25. Optimize slow queries (>100ms)
26. Implement query result caching
27. Add connection pooling
28. Denormalize where appropriate
29. Implement database read replicas
**Expected Impact**: -60% database query time
### Phase 6: Frontend Optimization (10 hours)
30. Minimize and compress JavaScript
31. Minimize and compress CSS
32. Remove unused CSS (PurgeCSS)
33. Implement critical CSS
34. Defer non-critical JavaScript
35. Reduce DOM size
36. Optimize React rendering (memo, useMemo)
37. Implement virtual scrolling for long lists
**Expected Impact**: -35% JavaScript execution time
### Phase 7: Network Optimization (4 hours)
38. Enable HTTP/2
39. Implement resource hints (preconnect, prefetch)
40. Reduce number of HTTP requests
41. Enable Brotli compression
42. Optimize third-party scripts
**Expected Impact**: -25% network time
### Phase 8: Monitoring & Testing (4 hours)
43. Set up performance monitoring (Datadog/New Relic)
44. Add Real User Monitoring (RUM)
45. Create performance budgets
46. Set up automated Lighthouse CI
47. Test on real devices
**Estimated Time**: 50 hours (2 weeks)
**Target Metrics** (90th percentile):
- LCP: <2.0s (from 4.2s) ✅
- FID: <50ms (from 280ms) ✅
- CLS: <0.05 (from 0.25) ✅
- Page Load: <2.5s (from 8.3s) ✅
**Expected Revenue Impact**:
- 100ms faster = 1% conversion increase
- Target: 5.8s improvement = ~58% conversion increase
- Estimated additional revenue: Significant
**Priority Order**:
1. Image optimization (quick wins)
2. Code splitting (high impact)
3. Caching (high impact)
4. Database optimization (critical)
5. Frontend optimization (polish)
Proceed with this plan? (yes/no/modify)
```
## Key Takeaways
### Benefits of Planning Mode
1. **Clarity**: Clear roadmap before starting
2. **Estimation**: Time and effort estimates
3. **Risk Assessment**: Identify potential issues early
4. **Prioritization**: Logical order of tasks
5. **Approval**: Review and approve before execution
6. **Modification**: Adjust plan based on feedback
### When to Use Planning Mode
**Always use for**:
- Multi-day projects
- Team collaborations
- Critical system changes
- Learning new concepts
- Complex refactoring
**Don't use for**:
- Bug fixes
- Small tweaks
- Simple queries
- Quick experiments
### Best Practices
1. **Review plans carefully** before approving
2. **Modify plans** when you spot issues
3. **Break down** complex tasks
4. **Estimate realistic** timeframes
5. **Include rollback** strategies
6. **Add success** criteria
7. **Plan for testing** at each phase

View File

@@ -0,0 +1,265 @@
#!/usr/bin/env python3
"""
setup-auto-mode-permissions.py
Seed ~/.claude/settings.json with a conservative baseline of safe permissions
for Claude Code. The default set is read-only and local-inspection oriented;
optional flags let you widen the allowlist for editing, test execution, git
write operations, package installs, and GitHub CLI writes.
Usage:
python3 setup-auto-mode-permissions.py
python3 setup-auto-mode-permissions.py --dry-run
python3 setup-auto-mode-permissions.py --include-edits --include-tests
"""
from __future__ import annotations
import argparse
import json
import tempfile
from pathlib import Path
from typing import Iterable
SETTINGS_PATH = Path.home() / ".claude" / "settings.json"
# Core baseline: read-only inspection and low-risk local shell commands.
CORE_PERMISSIONS = [
"Read(*)",
"Glob(*)",
"Grep(*)",
"Agent(*)",
"Skill(*)",
"WebSearch(*)",
"WebFetch(*)",
"Bash(ls:*)",
"Bash(pwd:*)",
"Bash(which:*)",
"Bash(echo:*)",
"Bash(cat:*)",
"Bash(head:*)",
"Bash(tail:*)",
"Bash(wc:*)",
"Bash(sort:*)",
"Bash(uniq:*)",
"Bash(find:*)",
"Bash(dirname:*)",
"Bash(basename:*)",
"Bash(realpath:*)",
"Bash(file:*)",
"Bash(stat:*)",
"Bash(diff:*)",
"Bash(md5sum:*)",
"Bash(sha256sum:*)",
"Bash(date:*)",
"Bash(env:*)",
"Bash(printenv:*)",
"Bash(git status:*)",
"Bash(git log:*)",
"Bash(git diff:*)",
"Bash(git branch:*)",
"Bash(git show:*)",
"Bash(git rev-parse:*)",
"Bash(git remote -v:*)",
"Bash(git remote get-url:*)",
"Bash(git stash list:*)",
]
# Optional but still local: file edits and task bookkeeping.
EDITING_PERMISSIONS = [
"Edit(*)",
"Write(*)",
"NotebookEdit(*)",
"TaskCreate(*)",
"TaskUpdate(*)",
]
# Optional dev/test commands. These can still execute arbitrary project scripts,
# so keep them opt-in rather than part of the default baseline.
TEST_AND_BUILD_PERMISSIONS = [
"Bash(npm test:*)",
"Bash(cargo test:*)",
"Bash(go test:*)",
"Bash(pytest:*)",
"Bash(python3 -m pytest:*)",
"Bash(make:*)",
"Bash(cmake:*)",
]
# Optional local git write operations. History-rewriting commands stay out of
# the default baseline because they are easy to misuse.
GIT_WRITE_PERMISSIONS = [
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git checkout:*)",
"Bash(git switch:*)",
"Bash(git stash:*)",
"Bash(git tag:*)",
]
# Optional dependency/package commands. These are intentionally excluded from
# the default baseline because they can execute project hooks or fetch code.
PACKAGE_MANAGER_PERMISSIONS = [
"Bash(npm ci:*)",
"Bash(npm install:*)",
"Bash(pip install:*)",
"Bash(pip3 install:*)",
]
# Optional GitHub CLI write access.
GITHUB_WRITE_PERMISSIONS = [
"Bash(gh pr create:*)",
]
# Optional extra GitHub CLI read access.
GITHUB_READ_PERMISSIONS = [
"Bash(gh pr view:*)",
"Bash(gh pr list:*)",
"Bash(gh issue view:*)",
"Bash(gh issue list:*)",
"Bash(gh repo view:*)",
]
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Seed Claude Code settings with a conservative permission baseline."
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Preview the rules that would be added without writing settings.json",
)
parser.add_argument(
"--include-edits",
action="store_true",
help="Add file-editing permissions (Edit/Write/NotebookEdit/TaskCreate/TaskUpdate)",
)
parser.add_argument(
"--include-tests",
action="store_true",
help="Add local build/test commands such as pytest, cargo test, and make",
)
parser.add_argument(
"--include-git-write",
action="store_true",
help="Add local git mutation commands such as add, commit, checkout, and stash",
)
parser.add_argument(
"--include-packages",
action="store_true",
help="Add package install commands such as npm ci, npm install, and pip install",
)
parser.add_argument(
"--include-gh-write",
action="store_true",
help="Add GitHub CLI write permissions such as gh pr create",
)
parser.add_argument(
"--include-gh-read",
action="store_true",
help="Add GitHub CLI read permissions such as gh pr view and gh repo view",
)
return parser.parse_args()
def load_settings(path: Path) -> dict:
if not path.exists():
return {}
try:
with path.open() as f:
settings = json.load(f)
except json.JSONDecodeError as exc:
raise SystemExit(f"Invalid JSON in {path}: {exc}") from exc
if not isinstance(settings, dict):
raise SystemExit(f"Expected {path} to contain a JSON object.")
return settings
def build_permissions(args: argparse.Namespace) -> list[str]:
permissions = list(CORE_PERMISSIONS)
if args.include_edits:
permissions.extend(EDITING_PERMISSIONS)
if args.include_tests:
permissions.extend(TEST_AND_BUILD_PERMISSIONS)
if args.include_git_write:
permissions.extend(GIT_WRITE_PERMISSIONS)
if args.include_packages:
permissions.extend(PACKAGE_MANAGER_PERMISSIONS)
if args.include_gh_write:
permissions.extend(GITHUB_WRITE_PERMISSIONS)
if args.include_gh_read:
permissions.extend(GITHUB_READ_PERMISSIONS)
return permissions
def append_unique(existing: list, new_items: Iterable[str]) -> list[str]:
seen = set(existing)
added: list[str] = []
for item in new_items:
if item not in seen:
existing.append(item)
seen.add(item)
added.append(item)
return added
def atomic_write_json(path: Path, payload: dict) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
"w",
encoding="utf-8",
dir=str(path.parent),
delete=False,
) as tmp:
json.dump(payload, tmp, indent=2)
tmp.write("\n")
tmp_path = Path(tmp.name)
tmp_path.replace(path)
def main() -> None:
args = parse_args()
permissions_to_add = build_permissions(args)
settings = load_settings(SETTINGS_PATH)
permissions = settings.setdefault("permissions", {})
if not isinstance(permissions, dict):
raise SystemExit("Expected permissions to be a JSON object.")
allow = permissions.setdefault("allow", [])
if not isinstance(allow, list):
raise SystemExit("Expected permissions.allow to be a JSON array.")
added = append_unique(allow, permissions_to_add)
if not added:
print("Nothing to add — all selected rules already present.")
return
print(f"{'Would add' if args.dry_run else 'Adding'} {len(added)} rule(s):")
for rule in added:
print(f" + {rule}")
if args.dry_run:
print("\nDry run — no changes written.")
return
atomic_write_json(SETTINGS_PATH, settings)
print(f"\nDone. {len(added)} rule(s) added to {SETTINGS_PATH}")
if __name__ == "__main__":
main()

184
vi/10-cli/README.md Normal file
View File

@@ -0,0 +1,184 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Tham Chiếu CLI / CLI Reference
## Tổng Quan / Overview
CLI Claude Code (Command Line Interface) là cách chính để tương tác với Claude Code. Nó cung cấp các tùy chọn mạnh mẽ để chạy các truy vấn, quản lý sessions, cấu hình mô hình, và tích hợp Claude vào workflows phát triển của bạn.
## Kiến Trúc / Architecture
```mermaid
graph TD
A["User Terminal"] -->|"claude [options] [query]"| B["Claude Code CLI"]
B -->|Interactive| C["REPL Mode"]
B -->|"--print"| D["Print Mode (SDK)"]
B -->|"--resume"| E["Session Resume"]
C -->|Conversation| F["Claude API"]
D -->|Single Query| F
E -->|Load Context| F
F -->|Response| G["Output"]
G -->|text/json/stream-json| H["Terminal/Pipe"]
```
## Các Lệnh CLI / CLI Commands
| Lệnh | Mô Tả | Ví Dụ |
|---------|-------------|---------|
| `claude` | Bắt đầu REPL tương tác | `claude` |
| `claude "query"` | Bắt đầu REPL với prompt ban đầu | `claude "explain this project"` |
| `claude -p "query"` | Chế độ in - query sau đó thoát | `claude -p "explain this function"` |
| `cat file \| claude -p "query"` | Xử lý nội dung được pipe | `cat logs.txt \| claude -p "explain"` |
| `claude -c` | Tiếp tục hội thoại gần đây nhất | `claude -c` |
| `claude -c -p "query"` | Tiếp tục trong chế độ in | `claude -c -p "check for type errors"` |
| `claude -r "<session>" "query"` | Resume session theo ID hoặc tên | `claude -r "auth-refactor" "finish this PR"` |
| `claude update` | Cập nhật đến phiên bản mới nhất | `claude update` |
| `claude mcp` | Cấu hình MCP servers | Xem [Tài liệu MCP](../05-mcp/) |
| `claude mcp serve` | Chạy Claude Code như một MCP server | `claude mcp serve` |
| `claude agents` | Liệt kê tất cả các subagents được cấu hình | `claude agents` |
| `claude auto-mode defaults` | In các quy tắc mặc định chế độ tự động như JSON | `claude auto-mode defaults` |
| `claude remote-control` | Bắt đầu server Remote Control | `claude remote-control` |
| `claude plugin` | Quản lý plugins (cài đặt, kích hoạt, vô hiệu hóa) | `claude plugin install my-plugin` |
| `claude auth login` | Đăng nhập (hỗ trợ `--email`, `--sso`) | `claude auth login --email user@example.com` |
| `claude auth logout` | Đăng xuất khỏi tài khoản hiện tại | `claude auth logout` |
| `claude auth status` | Kiểm tra trạng thái auth (exit 0 nếu đã đăng nhập, 1 nếu chưa) | `claude auth status` |
## Các Cờ Chính / Core Flags
| Cờ | Mô Tả | Ví Dụ |
|------|-------------|---------|
| `-p, --print` | In phản hồi mà không có chế độ tương tác | `claude -p "query"` |
| `-c, --continue` | Tải hội thoại gần đây nhất | `claude --continue` |
| `-r, --resume` | Resume session cụ thể theo ID hoặc tên | `claude --resume auth-refactor` |
| `-v, --version` | In số phiên bản | `claude -v` |
| `-w, --worktree` | Bắt đầu trong git worktree cô lập | `claude -w` |
| `-n, --name` | Tên hiển thị session | `claude -n "auth-refactor"` |
| `--from-pr <number>` | Resume sessions được liên kết đến GitHub PR | `claude --from-pr 42` |
| `--remote "task"` | Tạo session web trên claude.ai | `claude --remote "implement API"` |
| `--remote-control, --rc` | Session tương tác với Remote Control | `claude --rc` |
| `--teleport` | Resume session web cục bộ | `claude --teleport` |
| `--teammate-mode` | Chế độ hiển thị agent team | `claude --teammate-mode tmux` |
| `--bare` | Chế độ tối thiểu (bỏ qua hooks, skills, plugins, MCP, auto memory, CLAUDE.md) | `claude --bare` |
| `--enable-auto-mode` | Mở khóa chế độ quyền tự động | `claude --enable-auto-mode` |
| `--channels` | Đăng ký các plugin kênh MCP | `claude --channels discord,telegram` |
| `--chrome` / `--no-chrome` | Bật/tắt tích hợp trình duyệt Chrome | `claude --chrome` |
| `--effort` | Đặt mức độ suy nghĩ | `claude --effort high` |
| `--init` / `--init-only` | Chạy các hooks khởi tạo | `claude --init` |
| `--maintenance` | Chạy các hooks bảo trì và thoát | `claude --maintenance` |
| `--disable-slash-commands` | Vô hiệu hóa tất cả skills và lệnh slash | `claude --disable-slash-commands` |
| `--no-session-persistence` | Vô hiệu hóa lưu session (chế độ in) | `claude -p --no-session-persistence "query"` |
### Tương Tác vs Chế Độ In / Interactive vs Print Mode
```mermaid
graph LR
A["claude"] -->|Default| B["Interactive REPL"]
A -->|"-p flag"| C["Print Mode"]
B -->|Features| D["Multi-turn conversation<br>Tab completion<br>History<br>Slash commands"]
C -->|Features| E["Single query<br>Scriptable<br>Pipeable<br>JSON output"]
```
**Chế Độ Tương Tác** (mặc định):
```bash
# Bắt đầu session tương tác
claude
# Bắt đầu với prompt ban đầu
claude "explain the authentication flow"
```
**Chế Độ In** (không tương tác):
```bash
# Query đơn, sau đó thoát
claude -p "what does this function do?"
# Xử lý nội dung file
cat error.log | claude -p "explain this error"
# Chuỗi với các công cụ khác
claude -p "list todos" | grep "URGENT"
```
## Mô Hình & Cấu Hình / Model & Configuration
| Cờ | Mô Tả | Ví Dụ |
|------|-------------|---------|
| `--model` | Đặt mô hình (sonnet, opus, haiku, hoặc tên đầy đủ) | `claude --model opus` |
| `--fallback-model` | Fallback mô hình tự động khi quá tải | `claude -p --fallback-model sonnet "query"` |
| `--agent` | Chỉ định agent cho session | `claude --agent my-custom-agent` |
| `--agents` | Định nghĩa subagents tùy chỉnh qua JSON | Xem [Tác Nhân Con](../04-subagents/) |
| `--effort` | Đặt mức độ effort (low, medium, high, max) | `claude --effort high` |
### Ví Dụ Chọn Mô Hình / Model Selection Examples
```bash
# Sử dụng Opus 4.6 cho các tác vụ phức tạp
claude --model opus "design a caching strategy"
# Sử dụng Haiku 4.5 cho các tác vụ nhanh
claude --model haiku -p "format this JSON"
# Tên mô hình đầy đủ
claude --model claude-sonnet-4-6-20250929 "review this code"
# Với fallback để đảm bảo độ tin cậy
claude -p --model opus --fallback-model sonnet "analyze architecture"
# Sử dụng opusplan (Opus plans, Sonnet executes)
claude --model opusplan "design and implement the caching layer"
```
## Tùy Chọn System Prompt / System Prompt Customization
| Cờ | Mô Tả | Ví Dụ |
|------|-------------|---------|
| `--system-prompt` | Thay thế toàn bộ prompt mặc định | `claude --system-prompt "You are a Python expert"` |
| `--system-prompt-file` | Tải prompt từ file (chế độ in) | `claude -p --system-prompt-file ./prompt.txt "query"` |
| `--append-system-prompt` | Append vào prompt mặc định | `claude --append-system-prompt "Always use TypeScript"` |
## Công Cụ & Quản Lý Quyền / Tool & Permission Management
| Cờ | Mô Tả | Ví Dụ |
|------|-------------|---------|
| `--tools` | Hạn chế các công cụ có sẵn | `claude -p --tools "Bash,Edit,Read" "query"` |
| `--allowedTools` | Các công cụ thực thi mà không cần prompt | `"Bash(git log:*)" "Read"` |
| `--disallowedTools` | Các công cụ bị xóa khỏi ngữ cảnh | `"Bash(rm:*)" "Edit"` |
| `--dangerously-skip-permissions` | Bỏ qua tất cả các prompt quyền | `claude --dangerously-skip-permissions` |
| `--permission-mode` | Bắt đầu trong chế độ quyền được chỉ định | `claude --permission-mode auto` |
| `--permission-prompt-tool` | Công cụ MCP để xử lý quyền | `claude -p --permission-prompt-tool mcp_auth "query"` |
| `--enable-auto-mode` | Mở khóa chế độ quyền tự động | `claude --enable-auto-mode` |
### Ví Dụ Quyền / Permission Examples
```bash
# Chế độ read-only để review code
claude --permission-mode plan "review this codebase"
# Hạn chế đến các công cụ an toàn chỉ
claude --tools "Read,Grep,Glob" -p "find all TODO comments"
# Cho phép các lệnh git cụ thể mà không cần prompts
claude --allowedTools "Bash(git status:*)" "Bash(git log:*)"
# Chặn các thao tác nguy hiểm
claude --disallowedTools "Bash(rm -rf:*)" "Bash(git push --force:*)"
```
## Đầu Ra & Định Dạng / Output & Format
| Cờ | Mô Tả | Tùy Chọn | Ví Dụ |
|------|-------------|---------|---------|
| `--output-format` | Chỉ định định dạng đầu ra (chế độ in) | `text`, `json`, `stream-json` | `claude -p --output-format json "query"` |
| `--input-format` | Chỉ định định dạng đầu vào (chế độ in) | `text`, `stream-json` | `claude -p --input-format stream-json` |
| `--verbose` | Bật ghi nhật chi tiết | | `claude --verbose` |
| `--include-partial-messages` | Bao gồm các sự kiện streaming | Yêu cầu `stream-json` | `claude -p --output-format stream-json --include-partial-messages "query"` |
## Tài Nguyên Thêm / Additional Resources
- [Tài Liệu CLI Chính Thức](https://code.claude.com/docs/en/cli-reference)
- [Tài Liệu MCP](../05-mcp/) - Cấu hình MCP servers
- [Slash Commands](../01-slash-commands/) - Các phím tắt có thể tái sử dụng
- [Plugins](../07-plugins/) - Các gói mở rộng có thể cài đặt

516
vi/CATALOG.md Normal file
View File

@@ -0,0 +1,516 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Danh Mục Tính Năng Claude Code
> Hướng dẫn tham khảo nhanh cho tất cả tính năng Claude Code: commands, agents, skills, plugins, và hooks.
**Điều Hướng**: [Commands](#lệnh-slash) | [Permission Modes](#permission-modes) | [Tác Nhân Con](#tác-nhân-con) | [Skills](#skills) | [Plugins](#plugins) | [MCP Servers](#mcp-servers) | [Hooks](#hooks) | [Bộ Nhớ](#files-bộ-nhớ) | [Tính Năng Mới](#tính-năng-mới-tháng-3-năm-2026)
---
## Tóm Tắt
| Tính Năng | Built-in | Ví Dụ | Tổng | Tham Chiếu |
|---------|----------|----------|-------|-----------|
| **Lệnh Slash** | 55+ | 8 | 63+ | [01-slash-commands/](../01-slash-commands/) |
| **Tác Nhân Con** | 6 | 10 | 16 | [04-subagents/](../04-subagents/) |
| **Skills** | 5 bundled | 4 | 9 | [03-skills/](../03-skills/) |
| **Plugins** | - | 3 | 3 | [07-plugins/](../07-plugins/) |
| **MCP Servers** | 1 | 8 | 9 | [05-mcp/](../05-mcp/) |
| **Hooks** | 25 sự kiện | 7 | 7 | [06-hooks/](../06-hooks/) |
| **Bộ Nhớ** | 7 loại | 3 | 3 | [02-memory/](../02-memory/) |
| **Tổng** | **99** | **43** | **117** | |
---
## Lệnh Slash
Commands là các lệnh tắt do người dùng gọi thực hiện các hành động cụ thể.
### Built-in Commands
| Command | Mô Tả | Khi Nào Dùng |
|---------|-------------|-------------|
| `/help` | Hiển thị thông tin help | Bắt đầu, học commands |
| `/btw` | Câu hỏi phụ không thêm vào context | Câu hỏi nhanh |
| `/chrome` | Cấu hình tích hợp Chrome | Tự động hóa trình duyệt |
| `/clear` | Xóa lịch sử conversation | Bắt đầu mới, giảm context |
| `/diff` | Trình xem diff tương tác | Review thay đổi |
| `/config` | Xem/chỉnh sửa cấu hình | Tùy chỉnh hành vi |
| `/status` | Hiển thị trạng thái session | Kiểm tra trạng thái hiện tại |
| `/agents` | Liệt kê các agents có sẵn | Xem tùy chọn ủy quyền |
| `/skills` | Liệt kê các skills có sẵn | Xem khả năng auto-invoke |
| `/hooks` | Liệt kê các hooks đã cấu hình | Debug tự động hóa |
| `/insights` | Phân tích patterns của session | Tối ưu hóa session |
| `/install-slack-app` | Cài đặt Claude Slack app | Tích hợp Slack |
| `/keybindings` | Tùy chỉnh phím tắt | Tùy chỉnh phím |
| `/mcp` | Liệt kê MCP servers | Kiểm tra tích hợp bên ngoài |
| `/memory` | Xem các file bộ nhớ đã tải | Debug tải context |
| `/mobile` | Tạo QR code mobile | Truy cập mobile |
| `/passes` | Xem usage passes | Thông tin subscription |
| `/plugin` | Quản lý plugins | Cài đặt/gỡ mở rộng |
| `/plan` | Vào planning mode | Triển khai phức tạp |
| `/rewind` | Rewind về checkpoint | Hoàn tác thay đổi, khám phá alternatives |
| `/checkpoint` | Quản lý checkpoints | Lưu/khôi phục trạng thái |
| `/cost` | Hiển thị chi phí usage token | Giám sát chi tiêu |
| `/context` | Hiển thị usage context window | Quản lý độ dài conversation |
| `/export` | Xuất conversation | Lưu để tham khảo |
| `/extra-usage` | Cấu hình giới hạn usage thêm | Quản lý rate limit |
| `/feedback` | Gửi feedback hoặc báo cáo bug | Báo cáo vấn đề |
| `/login` | Xác thực với Anthropic | Truy cập tính năng |
| `/logout` | Đăng xuất | Chuyển tài khoản |
| `/sandbox` | Bật/tắt sandbox mode | Thực thi command an toàn |
| `/vim` | Bật/tắt vim mode | Chỉnh sửa kiểu Vim |
| `/doctor` | Chạy chẩn đoán | Khắc phục sự cố |
| `/reload-plugins` | Tải lại plugins đã cài đặt | Quản lý plugin |
| `/release-notes` | Hiển thị release notes | Kiểm tra tính năng mới |
| `/remote-control` | Bật điều khiển từ xa | Truy cập từ xa |
| `/permissions` | Quản lý permissions | Kiểm soát truy cập |
| `/session` | Quản lý sessions | Workflows đa session |
| `/rename` | Đổi tên session hiện tại | Tổ chức sessions |
| `/resume` | Tiếp tục session trước | Tiếp tục làm việc |
| `/todo` | Xem/quản lý todo list | Theo dõi tasks |
| `/tasks` | Xem background tasks | Giám sát operations async |
| `/copy` | Sao chép response cuối vào clipboard | Chia sẻ output nhanh |
| `/teleport` | Chuyển session sang máy khác | Tiếp tục làm việc từ xa |
| `/desktop` | Mở Claude Desktop app | Chuyển sang interface desktop |
| `/theme` | Đổi màu theme | Tùy chỉnh giao diện |
| `/usage` | Hiển thị thống kê usage API | Giám sát quota và chi phí |
| `/fork` | Fork conversation hiện tại | Khám phá alternatives |
| `/stats` | Hiển thị thống kê session | Review metrics session |
| `/statusline` | Cấu hình status line | Tùy chỉnh hiển thị trạng thái |
| `/stickers` | Xem stickers của session | Phần thưởng vui |
| `/fast` | Bật/tắt mode output nhanh | Tăng tốc độ responses |
| `/terminal-setup` | Cấu hình tích hợp terminal | Thiết lập tính năng terminal |
| `/upgrade` | Kiểm tra cập nhật | Quản lý phiên bản |
### Custom Commands (Ví Dụ)
| Command | Mô Tả | Khi Nào Dùng | Phạm Vi | Cài Đặt |
|---------|-------------|-------------|-------|--------------|
| `/optimize` | Phân tích code để tối ưu hóa | Cải thiện hiệu năng | Project | `cp ../01-slash-commands/optimize.md .claude/commands/` |
| `/pr` | Chuẩn bị pull request | Trước khi gửi PRs | Project | `cp ../01-slash-commands/pr.md .claude/commands/` |
| `/generate-api-docs` | Tạo tài liệu API | Tài liệu hóa APIs | Project | `cp ../01-slash-commands/generate-api-docs.md .claude/commands/` |
| `/commit` | Tạo git commit với context | Commit thay đổi | User | `cp ../01-slash-commands/commit.md .claude/commands/` |
| `/push-all` | Stage, commit, và push | Triển khai nhanh | User | `cp ../01-slash-commands/push-all.md .claude/commands/` |
| `/doc-refactor` | Tái cấu trúc tài liệu | Cải thiện docs | Project | `cp ../01-slash-commands/doc-refactor.md .claude/commands/` |
| `/setup-ci-cd` | Thiết lập pipeline CI/CD | Dự án mới | Project | `cp ../01-slash-commands/setup-ci-cd.md .claude/commands/` |
| `/unit-test-expand` | Mở rộng độ phủ test | Cải thiện testing | Project | `cp ../01-slash-commands/unit-test-expand.md .claude/commands/` |
> **Phạm Vi**: `User` = workflows cá nhân (`~/.claude/commands/`), `Project` = chia sẻ team (`.claude/commands/`)
**Tham Chiếu**: [01-slash-commands/](../01-slash-commands/) | [Tài Liệu Chính Thức](https://code.claude.com/docs/en/interactive-mode)
**Cài Đặt Nhanh (Tất Cả Custom Commands)**:
```bash
cp ../01-slash-commands/*.md .claude/commands/
```
---
## Permission Modes
Claude Code hỗ trợ 6 permission modes điều khiển cách tool use được ủy quyền.
| Mode | Mô Tả | Khi Nào Dùng |
|------|-------------|-------------|
| `default` | Hỏi cho mỗi tool call | Sử dụng tương tác tiêu chuẩn |
| `acceptEdits` | Tự động chấp nhận edits file, hỏi cho các khác | Workflows chỉnh sửa tin cậy |
| `plan` | Chỉ tools read-only, không ghi | Lập kế hoạch và khám phá |
| `auto` | Chấp nhận tất cả tools mà không hỏi | Vận hành hoàn toàn tự động (Research Preview) |
| `bypassPermissions` | Bỏ qua tất cả kiểm tra permissions | CI/CD, môi trường headless |
| `dontAsk` | Bỏ qua tools cần yêu cầu permission | Scripting không tương tác |
> **Lưu Ý**: `auto` mode là tính năng Research Preview (Tháng 3 năm 2026). Chỉ dùng `bypassPermissions` trong môi trường tin cậy, được sandbox.
**Tham Chiếu**: [Tài Liệu Chính Thức](https://code.claude.com/docs/en/permissions)
---
## Tác Nhân Con
Các trợ lý AI chuyên biệt với context bị cô lập cho các tasks cụ thể.
### Built-in Subagents
| Agent | Mô Tả | Tools | Model | Khi Nào Dùng |
|-------|-------------|-------|-------|-------------|
| **general-purpose** | Tasks đa bước, nghiên cứu | All tools | Kế thừa model | Nghiên cứu phức tạp, tasks đa file |
| **Plan** | Lập kế hoạch triển khai | Read, Glob, Grep, Bash | Kế thừa model | Thiết kế kiến trúc, lập kế hoạch |
| **Explore** | Khám phá codebase | Read, Glob, Grep | Haiku 4.5 | Tìm kiếm nhanh, hiểu code |
| **Bash** | Thực thi command | Bash | Kế thừa model | Operations Git, tasks terminal |
| **statusline-setup** | Cấu hình status line | Bash, Read, Write | Sonnet 4.6 | Cấu hình hiển thị status line |
| **Claude Code Guide** | Trợ giúp và tài liệu | Read, Glob, Grep | Haiku 4.5 | Nhận trợ giúp, học tính năng |
### Subagent Configuration Fields
| Field | Type | Mô Tả |
|-------|------|-------------|
| `name` | string | Định danh agent |
| `description` | string | Agent làm gì |
| `model` | string | Ghi đè model (ví dụ: `haiku-4.5`) |
| `tools` | array | Danh sách tools được phép |
| `effort` | string | Mức độ effort lý luận (`low`, `medium`, `high`) |
| `initialPrompt` | string | System prompt được chèn khi agent bắt đầu |
| `disallowedTools` | array | Tools bị từ chối rõ ràng cho agent này |
### Custom Subagents (Ví Dụ)
| Agent | Mô Tả | Khi Nào Dùng | Phạm Vi | Cài Đặt |
|-------|-------------|-------------|-------|--------------|
| `code-reviewer` | Chất lượng code toàn diện | Sessions review code | Project | `cp ../04-subagents/code-reviewer.md .claude/agents/` |
| `code-architect` | Thiết kế kiến trúc tính năng | Lập kế hoạch tính năng mới | Project | `cp ../04-subagents/code-architect.md .claude/agents/` |
| `code-explorer` | Phân tích codebase sâu | Hiểu tính năng hiện có | Project | `cp ../04-subagents/code-explorer.md .claude/agents/` |
| `clean-code-reviewer` | Review nguyên tắc Clean Code | Review khả năng bảo trì | Project | `cp ../04-subagents/clean-code-reviewer.md .claude/agents/` |
| `test-engineer` | Chiến lược & độ phủ test | Lập kế hoạch test | Project | `cp ../04-subagents/test-engineer.md .claude/agents/` |
| `documentation-writer` | Tài liệu kỹ thuật | Tài liệu API, hướng dẫn | Project | `cp ../04-subagents/documentation-writer.md .claude/agents/` |
| `secure-reviewer` | Review tập trung bảo mật | Kiểm tra bảo mật | Project | `cp ../04-subagents/secure-reviewer.md .claude/agents/` |
| `implementation-agent` | Triển khai tính năng hoàn chỉnh | Phát triển tính năng | Project | `cp ../04-subagents/implementation-agent.md .claude/agents/` |
| `debugger` | Phân tích nguyên nhân gốc | Điều tra bug | User | `cp ../04-subagents/debugger.md ~/.claude/agents/` |
| `data-scientist` | Truy vấn SQL, phân tích dữ liệu | Tasks dữ liệu | User | `cp ../04-subagents/data-scientist.md ~/.claude/agents/` |
> **Phạm Vi**: `User` = cá nhân (`~/.claude/agents/`), `Project` = chia sẻ team (`.claude/agents/`)
**Tham Chiếu**: [04-subagents/](../04-subagents/) | [Tài Liệu Chính Thức](https://code.claude.com/docs/en/sub-agents)
**Cài Đặt Nhanh (Tất Cả Custom Agents)**:
```bash
cp ../04-subagents/*.md .claude/agents/
```
---
## Skills
Các khả năng tự động gọi với hướng dẫn, scripts, và templates.
### Ví Dụ Skills
| Skill | Mô Tả | Khi Tự Động Gọi | Phạm Vi | Cài Đặt |
|-------|-------------|-------------------|-------|--------------|
| `code-review` | Review code toàn diện | "Review this code", "Check quality" | Project | `cp -r ../03-skills/code-review .claude/skills/` |
| `brand-voice` | Kiểm tra nhất quán brand | Viết marketing copy | Project | `cp -r ../03-skills/brand-voice .claude/skills/` |
| `doc-generator` | Trình tạo tài liệu API | "Generate docs", "Document API" | Project | `cp -r ../03-skills/doc-generator .claude/skills/` |
| `refactor` | Refactor code có hệ thống (Martin Fowler) | "Refactor this", "Clean up code" | User | `cp -r ../03-skills/refactor ~/.claude/skills/` |
> **Phạm Vi**: `User` = cá nhân (`~/.claude/skills/`), `Project` = chia sẻ team (`.claude/skills/`)
### Skill Structure
```
~/.claude/skills/skill-name/
├── SKILL.md # Định nghĩa & hướng dẫn skill
├── scripts/ # Scripts hỗ trợ
└── templates/ # Templates output
```
### Skill Frontmatter Fields
Skills hỗ trợ YAML frontmatter trong `SKILL.md` để cấu hình:
| Field | Type | Mô Tả |
|-------|------|-------------|
| `name` | string | Tên hiển thị skill |
| `description` | string | Skill làm gì |
| `autoInvoke` | array | Cụm từ kích hoạt cho auto-invocation |
| `effort` | string | Mức độ effort lý luận (`low`, `medium`, `high`) |
| `shell` | string | Shell để dùng cho scripts (`bash`, `zsh`, `sh`) |
**Tham Chiếu**: [03-skills/](../03-skills/) | [Tài Liệu Chính Thức](https://code.claude.com/docs/en/skills)
**Cài Đặt Nhanh (Tất Cả Skills)**:
```bash
cp -r ../03-skills/* ~/.claude/skills/
```
### Bundled Skills
| Skill | Mô Tả | Khi Tự Động Gọi |
|-------|-------------|-------------------|
| `/simplify` | Review code về chất lượng | Sau khi viết code |
| `/batch` | Chạy prompts trên nhiều files | Operations hàng loạt |
| `/debug` | Debug tests/errors thất bại | Sessions debugging |
| `/loop` | Chạy prompts theo interval | Tasks định kỳ |
| `/claude-api` | Xây dựng apps với Claude API | Phát triển API |
---
## Plugins
Bộ sưu tập được đóng gói của commands, agents, MCP servers, và hooks.
### Ví Dụ Plugins
| Plugin | Mô Tả | Components | Khi Nào Dùng | Phạm Vi | Cài Đặt |
|--------|-------------|------------|-------------|-------|--------------|
| `pr-review` | Workflow review PR | 3 commands, 3 agents, GitHub MCP | Review code | Project | `/plugin install pr-review` |
| `devops-automation` | Triển khai & giám sát | 4 commands, 3 agents, K8s MCP | Tasks DevOps | Project | `/plugin install devops-automation` |
| `documentation` | Bộ tạo tài liệu | 4 commands, 3 agents, templates | Tài liệu | Project | `/plugin install documentation` |
> **Phạm Vi**: `Project` = chia sẻ team, `User` = workflows cá nhân
### Plugin Structure
```
.claude-plugin/
├── plugin.json # File manifest
├── commands/ # Lệnh slash
├── agents/ # Tác nhân con
├── skills/ # Skills
├── mcp/ # Cấu hình MCP
├── hooks/ # Script hooks
└── scripts/ # Scripts tiện ích
```
**Tham Chiếu**: [07-plugins/](../07-plugins/) | [Tài Liệu Chính Thức](https://code.claude.com/docs/en/plugins)
**Plugin Management Commands**:
```bash
/plugin list # Liệt kê plugins đã cài
/plugin install <name> # Cài plugin
/plugin remove <name> # Gỡ plugin
/plugin update <name> # Cập nhật plugin
```
---
## MCP Servers
Máy chủ Model Context Protocol cho truy cập công cụ và API bên ngoài.
### MCP Servers Phổ Biến
| Server | Mô Tả | Khi Nào Dùng | Phạm Vi | Cài Đặt |
|--------|-------------|-------------|-------|--------------|
| **GitHub** | Quản lý PR, issues, code | Workflows GitHub | Project | `claude mcp add github -- npx -y @modelcontextprotocol/server-github` |
| **Database** | Truy vấn SQL, truy cập dữ liệu | Operations database | Project | `claude mcp add db -- npx -y @modelcontextprotocol/server-postgres` |
| **Filesystem** | Operations file nâng cao | Tasks file phức tạp | User | `claude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem` |
| **Slack** | Communication team | Thông báo, cập nhật | Project | Cấu hình trong settings |
| **Google Docs** | Truy cập tài liệu | Chỉnh sửa, review docs | Project | Cấu hình trong settings |
| **Asana** | Quản lý dự án | Theo dõi tasks | Project | Cấu hình trong settings |
| **Stripe** | Dữ liệu thanh toán | Phân tích tài chính | Project | Cấu hình trong settings |
| **Memory** | Bộ nhớ lưu trữ | Nhớ lại qua sessions | User | Cấu hình trong settings |
| **Context7** | Tài liệu thư viện | Tra cứu docs cập nhật | Built-in | Built-in |
> **Phạm Vi**: `Project` = team (`.mcp.json`), `User` = cá nhân (`~/.claude.json`), `Built-in` = được cài trước
### MCP Configuration Example
```json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
}
}
}
```
**Tham Chiếu**: [05-mcp/](../05-mcp/) | [Tài Liệu Giao Thức MCP](https://modelcontextprotocol.io)
**Cài Đặt Nhanh (GitHub MCP)**:
```bash
export GITHUB_TOKEN="your_token" && claude mcp add github -- npx -y @modelcontextprotocol/server-github
```
---
## Hooks
Tự động hóa dựa trên sự kiện thực thi shell commands trên các sự kiện Claude Code.
### Hook Events
| Event | Mô Tả | Khi Được Kích Hoạt | Use Cases |
|-------|-------------|----------------|-----------|
| `SessionStart` | Session bắt đầu/tiếp tục | Khởi tạo session | Tasks thiết lập |
| `InstructionsLoaded` | Hướng dẫn được tải | CLAUDE.md hoặc file rules được tải | Xử lý hướng dẫn tùy chỉnh |
| `UserPromptSubmit` | Trước khi xử lý prompt | User gửi tin nhắn | Xác thực input |
| `PreToolUse` | Trước khi thực thi tool | Trước khi bất kỳ tool chạy | Xác thực, logging |
| `PermissionRequest` | Dialog permission được hiển thị | Trước hành động nhạy cảm | Flows phê duyệt tùy chỉnh |
| `PostToolUse` | Sau khi tool thành công | Sau khi bất kỳ tool hoàn thành | Formatting, thông báo |
| `PostToolUseFailure` | Thực thi tool thất bại | Sau khi tool lỗi | Xử lý lỗi, logging |
| `Notification` | Thông báo được gửi | Claude gửi thông báo | Cảnh báo bên ngoài |
| `SubagentStart` | Subagent được tạo | Task subagent bắt đầu | Khởi tạo context subagent |
| `SubagentStop` | Subagent hoàn thành | Task subagent hoàn tất | Chuỗi hành động |
| `Stop` | Claude hoàn thành phản hồi | Phản hồi hoàn tất | Dọn dẹp, báo cáo |
| `StopFailure` | Lỗi API kết thúc turn | Lỗi API xảy ra | Phục hồi lỗi, logging |
| `TeammateIdle` | Agent teammate rảnh | Phối hợp agent team | Phân phối work |
| `TaskCompleted` | Task được đánh dấu hoàn tất | Task xong | Xử lý post-task |
| `TaskCreated` | Task được tạo qua TaskCreate | Task mới được tạo | Theo dõi task, logging |
| `ConfigChange` | Cấu hình được cập nhật | Settings được sửa đổi | Phản ứng thay đổi config |
| `CwdChanged` | Thư mục làm việc thay đổi | Thư mục thay đổi | Thiết lập cụ thể theo thư mục |
| `FileChanged` | File được theo dõi thay đổi | File được sửa | Giám sát file, rebuild |
| `PreCompact` | Trước operation compact | Nén context | Bảo toàn trạng thái |
| `PostCompact` | Sau khi compact hoàn tất | Compact xong | Hành động post-compact |
| `WorktreeCreate` | Worktree đang được tạo | Git worktree được tạo | Thiết lập môi trường worktree |
| `WorktreeRemove` | Worktree đang bị gỡ | Git worktree bị gỡ | Dọn dẹp tài nguyên worktree |
| `Elicitation` | MCP server yêu cầu input | MCP elicitation | Xác thực input |
| `ElicitationResult` | User phản hồi elicitation | User phản hồi | Xử lý phản hồi |
| `SessionEnd` | Session chấm dứt | Chấm dứt session | Dọn dẹp, lưu trạng thái |
### Ví Dụ Hooks
| Hook | Mô Tả | Event | Phạm Vi | Cài Đặt |
|------|-------------|-------|-------|--------------|
| `validate-bash.py` | Xác thực command | PreToolUse:Bash | Project | `cp ../06-hooks/validate-bash.py .claude/hooks/` |
| `security-scan.py` | Quét bảo mật | PostToolUse:Write | Project | `cp ../06-hooks/security-scan.py .claude/hooks/` |
| `format-code.sh` | Tự động format | PostToolUse:Write | User | `cp ../06-hooks/format-code.sh ~/.claude/hooks/` |
| `validate-prompt.py` | Xác thực prompt | UserPromptSubmit | Project | `cp ../06-hooks/validate-prompt.py .claude/hooks/` |
| `context-tracker.py` | Theo dõi usage token | Stop | User | `cp ../06-hooks/context-tracker.py ~/.claude/hooks/` |
| `pre-commit.sh` | Xác thực pre-commit | PreToolUse:Bash | Project | `cp ../06-hooks/pre-commit.sh .claude/hooks/` |
| `log-bash.sh` | Ghi log commands | PostToolUse:Bash | User | `cp ../06-hooks/log-bash.sh ~/.claude/hooks/` |
> **Phạm Vi**: `Project` = team (`.claude/settings.json`), `User` = cá nhân (`~/.claude/settings.json`)
### Hook Configuration
```json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"command": "~/.claude/hooks/validate-bash.py"
}
],
"PostToolUse": [
{
"matcher": "Write",
"command": "~/.claude/hooks/format-code.sh"
}
]
}
}
```
**Tham Chiếu**: [06-hooks/](../06-hooks/) | [Tài Liệu Chính Thức](https://code.claude.com/docs/en/hooks)
**Cài Đặt Nhanh (Tất Cả Hooks)**:
```bash
mkdir -p ~/.claude/hooks && cp ../06-hooks/*.sh ~/.claude/hooks/ && chmod +x ~/.claude/hooks/*.sh
```
---
## Files Bộ Nhớ
Ngữ cảnh lưu trữ được tải tự động qua sessions.
### Loại Bộ Nhớ
| Loại | Vị Trí | Phạm Vi | Khi Nào Dùng |
|------|----------|-------|-------------|
| **Managed Policy** | Policies được quản lý bởi tổ chức | Tổ chức | Thực thi tiêu chuẩn toàn tổ chức |
| **Project** | `./CLAUDE.md` | Project (team) | Tiêu chuẩn team, context dự án |
| **Project Rules** | `.claude/rules/` | Project (team) | Rules dự án modular |
| **User** | `~/.claude/CLAUDE.md` | User (cá nhân) | Sở thích cá nhân |
| **User Rules** | `~/.claude/rules/` | User (cá nhân) | Rules cá nhân modular |
| **Local** | `./CLAUDE.local.md` | Local (git-ignored) | Ghi đè cụ thể theo máy (không trong tài liệu chính thức tính đến tháng 3/2026; có thể là legacy) |
| **Auto Memory** | Tự động | Session | Insights và chỉnh sửa được tự động nắm bắt |
> **Phạm Vi**: `Organization` = được quản lý bởi admins, `Project` = chia sẻ với team qua git, `User` = sở thích cá nhân, `Local` = không được commit, `Session` = được tự động quản lý
**Tham Chiếu**: [02-memory/](../02-memory/) | [Tài Liệu Chính Thức](https://code.claude.com/docs/en/memory)
**Cài Đặt Nhanh**:
```bash
cp ../02-memory/project-CLAUDE.md ./CLAUDE.md
cp ../02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md
```
---
## Tính Năng Mới (Tháng 3 Năm 2026)
| Tính Năng | Mô Tả | Cách Dùng |
|---------|-------------|------------|
| **Remote Control** | Điều khiển sessions Claude Code từ xa qua API | Sử dụng API điều khiển từ xa để gửi prompts và nhận responses theo chương trình |
| **Web Sessions** | Chạy Claude Code trong môi trường dựa trên trình duyệt | Truy cập qua `claude web` hoặc qua Anthropic Console |
| **Desktop App** | Ứng dụng desktop native cho Claude Code | Sử dụng `/desktop` hoặc tải từ website Anthropic |
| **Agent Teams** | Phối hợp nhiều agents làm việc trên các tasks liên quan | Cấu hình teammate agents cộng tác và chia sẻ context |
| **Task List** | Quản lý và giám sát background tasks | Sử dụng `/tasks` để xem và quản lý operations nền |
| **Prompt Suggestions** | Gợi ý command nhận biết ngữ cảnh | Gợi ý xuất hiện tự động dựa trên ngữ cảnh hiện tại |
| **Git Worktrees** | Git worktrees bị cô lập để phát triển song song | Sử dụng commands worktree để làm việc branch song song an toàn |
| **Sandboxing** | Môi trường thực thi bị cô lập để an toàn | Sử dụng `/sandbox` để bật/tắt; chạy commands trong môi trường bị hạn chế |
| **MCP OAuth** | Xác thực OAuth cho MCP servers | Cấu hình credentials OAuth trong settings MCP server để truy cập an toàn |
| **MCP Tool Search** | Tìm kiếm và khám phá MCP tools động | Sử dụng tìm kiếm tool để tìm MCP tools có sẵn qua các servers được kết nối |
| **Scheduled Tasks** | Thiết lập tasks định kỳ với `/loop` và cron tools | Sử dụng `/loop 5m /command` hoặc công cụ CronCreate |
| **Chrome Integration** | Tự động hóa trình duyệt với headless Chromium | Sử dụng flag `--chrome` hoặc command `/chrome` |
| **Keyboard Customization** | Tùy chỉnh keybindings bao gồm hỗ trợ chord | Sử dụng `/keybindings` hoặc chỉnh sửa `~/.claude/keybindings.json` |
| **Auto Mode** | Vận hành hoàn toàn tự động mà không cần prompts permission (Research Preview) | Sử dụng `--mode auto` hoặc `/permissions auto`; Tháng 3 năm 2026 |
| **Channels** | Communication đa kênh (Telegram, Slack, v.v.) (Research Preview) | Cấu hình plugins channels; Tháng 3 năm 2026 |
| **Voice Dictation** | Input giọng nói cho prompts | Sử dụng icon microphone hoặc keybinding giọng nói |
| **Agent Hook Type** | Hooks tạo subagent thay vì chạy shell command | Đặt `"type": "agent"` trong cấu hình hook |
| **Prompt Hook Type** | Hooks chèn văn bản prompt vào conversation | Đặt `"type": "prompt"` trong cấu hình hook |
| **MCP Elicitation** | MCP servers có thể yêu cầu input người dùng trong khi thực thi tool | Xử lý qua các sự kiện hook `Elicitation``ElicitationResult` |
| **WebSocket MCP Transport** | Transport dựa trên WebSocket cho kết nối MCP server | Sử dụng `"transport": "websocket"` trong cấu hình MCP server |
| **Plugin LSP Support** | Tích hợp Language Server Protocol qua plugins | Cấu hình servers LSP trong `plugin.json` cho tính năng editor |
| **Managed Drop-ins** | Cấu hình drop-ins được quản lý bởi tổ chức (v2.1.83) | Được cấu hình bởi admin qua policies được quản lý; tự động áp dụng cho tất cả users |
---
## Ma Trận Tham Khảo Nhanh
### Hướng Dẫn Chọn Tính Năng
| Nhu Cầu | Tính Năng Khuyến Nghị | Tại Sao |
|------|---------------------|-----|
| Phím tắt nhanh | Lệnh Slash | Thủ công, ngay lập tức |
| Ngữ cảnh lưu trữ | Bộ Nhớ | Tự động tải |
| Tự động hóa phức tạp | Skill | Tự động gọi |
| Task chuyên biệt | Tác Nhân Con | Context bị cô lập |
| Dữ liệu bên ngoài | MCP Server | Truy cập thời gian thực |
| Tự động hóa sự kiện | Hook | Được kích hoạt bởi sự kiện |
| Giải pháp hoàn chỉnh | Plugin | Gói tất cả trong một |
### Ưu Tiên Cài Đặt
| Ưu Tiên | Tính Năng | Command |
|----------|---------|---------|
| 1. Thiết Yếu | Bộ Nhớ | `cp ../02-memory/project-CLAUDE.md ./CLAUDE.md` |
| 2. Dùng Hàng Ngày | Lệnh Slash | `cp ../01-slash-commands/*.md .claude/commands/` |
| 3. Chất Lượng | Tác Nhân Con | `cp ../04-subagents/*.md .claude/agents/` |
| 4. Tự Động Hóa | Hooks | `cp ../06-hooks/*.sh ~/.claude/hooks/ && chmod +x ~/.claude/hooks/*.sh` |
| 5. Bên Ngoài | MCP | `claude mcp add github -- npx -y @modelcontextprotocol/server-github` |
| 6. Nâng Cao | Skills | `cp -r ../03-skills/* ~/.claude/skills/` |
| 7. Hoàn Chỉnh | Plugins | `/plugin install pr-review` |
---
## Cài Đặt Một Lệnh Hoàn Chỉnh
Cài đặt tất cả ví dụ từ repository này:
```bash
# Tạo thư mục
mkdir -p .claude/{commands,agents,skills} ~/.claude/{hooks,skills}
# Cài đặt tất cả tính năng
cp ../01-slash-commands/*.md .claude/commands/ && \
cp ../02-memory/project-CLAUDE.md ./CLAUDE.md && \
cp -r ../03-skills/* ~/.claude/skills/ && \
cp ../04-subagents/*.md .claude/agents/ && \
cp ../06-hooks/*.sh ~/.claude/hooks/ && \
chmod +x ~/.claude/hooks/*.sh
```
---
## Tài Nguyên Thêm
- [Tài Liệu Chính Thức Claude Code](https://code.claude.com/docs/en/overview)
- [Đặc Tả Giao Thức MCP](https://modelcontextprotocol.io)
- [Lộ Trình Học Tập](../LEARNING-ROADMAP.md)
- [README Chính](../README.md)
---
**Cập Nhật Lần**: Tháng 3 năm 2026

80
vi/CHANGELOG.md Normal file
View File

@@ -0,0 +1,80 @@
# Changelog
## v2.2.0 — 2026-03-26
### Tài Liệu / Documentation
- Đồng bộ tất cả các hướng dẫn và tham khảo với Claude Code v2.1.84 (f78c094) @luongnv89
- Cập nhật slash commands thành 55+ built-in + 5 bundled skills, đánh dấu 3 deprecated
- Mở rộng các sự kiện hook từ 18 lên 25, thêm loại hook `agent` (bây giờ 4 loại)
- Thêm Auto Mode, Channels, Voice Dictation vào tính năng nâng cao
- Thêm `effort`, `shell` skill frontmatter fields; `initialPrompt`, `disallowedTools` agent fields
- Thêm WebSocket MCP transport, elicitation, giới hạn 2KB tool
- Thêm hỗ trợ LSP plugin, `userConfig`, `${CLAUDE_PLUGIN_DATA}`
- Cập nhật tất cả tài liệu tham khảo (CATALOG, QUICK_REFERENCE, LEARNING-ROADMAP, INDEX)
- Viết lại README như hướng dẫn có cấu trúc landing-page (32a0776) @luongnv89
### Sửa Lỗi / Bug Fixes
- Thêm các từ cSpell bị thiếu và các phần README bị thiếu cho tuân thủ CI (93f9d51) @luongnv89
- Thêm `Sandboxing` vào từ điển cSpell (b80ce6f) @luongnv89
**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.1.1...v2.2.0
---
## v2.1.1 — 2026-03-13
### Sửa Lỗi / Bug Fixes
- Xóa link marketplace chết gây thất bại kiểm tra link CI (3fdf0d6) @luongnv89
- Thêm `sandboxed``pycache` vào từ điển cSpell (dc64618) @luongnv89
**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.1.0...v2.1.1
---
## v2.1.0 — 2026-03-13
### Tính Năng / Features
- Thêm đường dẫn học tập thích ứng với self-assessment và kỹ năng quiz bài học (1ef46cd) @luongnv89
- `/self-assessment` — quiz trình độ tương tác trên 10 lĩnh vực tính năng với đường dẫn học tập được cá nhân hóa
- `/lesson-quiz [lesson]` — kiểm tra kiến thức mỗi bài học với 8-10 câu hỏi được nhắm mục tiêu
### Sửa Lỗi / Bug Fixes
- Cập nhật các URL bị hỏ, các tính năng lỗi thời, và các tham khảo cũ (8fe4520) @luongnv89
- Sửa các liên kết bị hỏng trong resources và kỹ năng self-assessment (7a05863) @luongnv89
- Sử dụng hàng rào cho các khối code lồng nhau trong hướng dẫn khái niệm (5f82719) @VikalpP
- Thêm các từ còn thiếu vào từ điển cSpell (8df7572) @luongnv89
### Tài Liệu / Documentation
- Giai đoạn 5 QA — sửa nhất quán, URLs, và thuật ngữ trên các tài liệu (00bbe4c) @luongnv89
- Hoàn thành Giai đoạn 3-4 — phạm vi tính năng mới và cập nhật tài liệu tham khảo (132de29) @luongnv89
- Thêm runtime MCPorter vào phần context bloat MCP (ef52705) @luongnv89
- Thêm các lệnh, tính năng, và settings bị thiếu qua 6 hướng dẫn (4bc8f15) @luongnv89
- Thêm hướng dẫn style dựa trên các quy ước repo hiện có (84141d0) @luongnv89
- Thêm hàng self-assessment vào bảng so sánh hướng dẫn (8fe0c96) @luongnv89
- Thêm VikalpP vào danh sách người đóng góp cho PR #7 (d5b4350) @luongnv89
- Thêm các tham khảo self-assessment và lesson-quiz skill vào README và roadmap (d5a6106) @luongnv89
### Người Đóng Góp Mới / New Contributors
- @VikalpP đã thực hiện đóng góp đầu tiên của họ trong #7
**Full Changelog**: https://github.com/luongnv89/claude-howto/compare/v2.0.0...v2.1.0
---
## v2.0.0 — 2026-02-01
### Tính Năng / Features
- Đồng bộ tất cả tài liệu với các tính năng Claude Code tháng 2 năm 2026 (487c96d)
- Cập nhật 26 files trên tất cả 10 thư mục hướng dẫn và 7 tài liệu tham khảo
- Thêm tài liệu cho **Auto Memory** — các bài học liên tục cho mỗi dự án
- Thêm tài liệu cho **Remote Control**, **Web Sessions**, và **Desktop App**
- Thêm tài liệu cho **Agent Teams** (hợp tác đa tác nhân thực nghiệm)
- Thêm tài liệu cho **MCP OAuth 2.0**, **Tool Search**, và **Claude.ai Connectors**

82
vi/CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,82 @@
# Quy Tắc Ứng Xuất / Contributor Code of Conduct
## Cam Kết Của Chúng Tôi / Our Commitment
Chúng tôi cam kết cung cấp một cộng đồng chào đón và truyền cảm hứng cho tất cả mọi người. Chúng tôi cam kết rằng tham gia vào cộng đồng của chúng tôi là một trải nghiệm không quấy rối cho tất cả mọi người, bất kể độ tuổi, kích thước cơ thể, đẳng cấp, khuyết tật, sắc tộc, đặc điểm tính dục, bản dạng và biểu hiện giới tính, trình độ kinh nghiệm, giáo dục, địa vị kinh tế - xã hội, quốc tịch, ngoại hình, chủng tộc, tôn giáo, hoặc định hướng và bản sắc tình dục.
Chúng tôi dành riêng để cung cấp một môi trường tích cực, bao gồm và an toàn nơi tất cả người đóng góp cảm thấy được tôn trọng, được đánh giá cao, và được trao quyền để đóng góp công việc tốt nhất của họ.
## Tiêu Chuẩn Của Chúng Tôi / Our Standards
Các ví dụ về hành vi góp phần tạo ra một môi trường tích cực bao gồm:
### Tôn Trọng / Be Respectful
- Sử dụng ngôn ngữ chào đón và bao gồm
- Tôn trọng các ý kiến, quan điểm, và kinh nghiệm khác nhau
- Chấp nhận criticism mang tính xây dựng một cách khéo léo
- Tôn trọng các khác biệt về văn hóa và ngôn ngữ
- Công nhận và ăn mừng các nền tảng đa dạng
### Hợp Tác / Be Collaborative
- Làm việc cùng nhau để giải quyết xung đột
- Ghi nhận và công nhận đóng góp của người khác
- Giúp người khác học và phát triển
- Chia sẻ kiến thức và đặt câu hỏi
- Hỗ trợ các thành viên cộng đồng khác
### Chuyên Nghiệp / Be Professional
- Giữ các cuộc thảo luận tập trung và mang tính sản xuất
- Tránh các nhận xét hạ thấp hoặc xúc phạm
- Giữ chủ đề trong các vấn đề và thảo luận
- Sử dụng giao tiếp rõ ràng và tôn trọng
- Giả định ý định tốt trong thông điệp của người khác
### Bao Gồm / Be Inclusive
- Chào đón những người đóng góp mới
- Giúp các người mới onboard vào dự án
- Cung cấp feedback mang tính xây dựng
- Bao gồm những người có quan điểm khác nhau
- Tạo không gian cho những tiếng nói nhỏ được nghe thấy
## Hành Vi Không Chấp Nhận / Unacceptable Behavior
Các hành vi sau được coi là quấy rối và không thể chấp nhận trong cộng đồng của chúng tôi:
### Quấy Rối và Phân Biệt Ức / Harassment and Discrimination
- Các bình luận phân biệt chủng tộc liên quan đến giới tính, bản dạng và biểu hiện giới tính, định hướng tình dục, khuyết tật, bệnh tâm thần, neuro(a)typicality, ngoại hình, kích thước cơ thể, độ tuổi, chủng tộc, hoặc tôn giáo
- Các bình luận không chào đón liên quan đến lựa chọn phong cách và thực hành của một người
- Đánh đồng giới tính hoặc sử dụng tên 'chết' hoặc bị từ chối một cách có chủ đích
- Hình ảnh hoặc hành vi tình dục ngoài chủ đề hoặc không liên quan
- Tiếp xúc vật lý và mô phỏng tiếp xúc vật lý mà không có sự đồng ý hoặc sau khi yêu cầu dừng
### Hành Vi Lạm Dụng / Abusive Behavior
- Các đe dọa bạo lực hoặc ngôn ngữ bạo lực được hướng đến một người khác
- Kích động bạo lực hoặc ngôn ngữ bạo lực đối với bất kỳ cá nhân nào
- Đe dọa có chủ đích
- Stalking hoặc theo dõi
- Quấy rối qua liên lạc lặp đi lặp lại
- Bất kỳ hành vi nào khác có thể được coi là không phù hợp
### Quấy Rối Trực Tuyến / Online Harassment
- Gián đoạn các cuộc thảo luận trực tuyến
- Công bố thông tin riêng tư của người khác (doxxing)
- Sự chú ý tình dục không chào đón hoặc các tiến bộ
- Trolling hoặc gây gián đoạn có chủ đích
- Spam hoặc quảng cáo lặp đi lặp
- Lan truyền thông tin sai lệch hoặc thông tin sai
## Phạm Vi / Scope
Quy Tắc Ứng Xuất này áp dụng cho:
- Tất cả các không gian cộng đồng (GitHub issues, pull requests, thảo luận, v.v.)
- Kho chứa dự án và tài liệu
- Các sự kiện và cuộc họp được tổ chức bởi hoặc đại diện cho dự án
- Các không gian công cộng nơi các cá nhân đang đại diện cho dự án hoặc cộng đồng
## Báo Cáo / Reporting
Nếu bạn witness hoặc là mục tiêu của hành vi quấy rối, vui lòng báo cáo cho:
- Người bảo trì dự án: [Contact Info]
- Báo cáo vấn đề an toàn/đe dọa cho nền tảng phù hợp
Chúng tôi sẽ điều tra và phản hồi tất cả các khiếu nại một cách bảo mật và nghiêm túc.

99
vi/CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,99 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="resources/logos/claude-howto-logo.svg">
</picture>
# Đóng Góp Cho Claude How To / Contributing to Claude How To
Cảm ơn bạn quan tâm đến việc đóng góp cho dự án này! Hướng dẫn này sẽ giúp bạn hiểu cách đóng góp hiệu quả.
## Về Dự Án Này / About This Project
Claude How To là một hướng dẫn trực quan, dựa trên ví dụ cho Claude Code. Chúng tôi cung cấp:
- **Sơ đồ Mermaid** giải thích cách các tính năng hoạt động
- **Mẫu sản xuất sẵn** bạn có thể sử dụng ngay lập tức
- **Ví dụ thực tế** với ngữ cảnh và thực hành tốt nhất
- **Đường dẫn học tập tiến bộ** từ người mới bắt đầu đến nâng cao
## Các Loại Đóng Góp / Types of Contributions
### 1. Ví Dụ hoặc Mẫu Mới
Thêm ví dụ cho các tính năng hiện có (slash commands, skills, hooks, v.v.):
- Code sẵn sàng để copy-paste
- Giải thích rõ ràng cách nó hoạt động
- Các trường hợp sử dụng và lợi ích
- Mẹo xử lý sự cố
### 2. Cải Tiện Tài Liệu
- Làm rõ các phần nhầm hiểu
- Sửa lỗi chính tả và ngữ pháp
- Thêm thông tin còn thiếu
- Cải thiện các ví dụ code
### 3. Hướng Dẫn Tính Năng
Tạo hướng dẫn cho các tính năng Claude Code mới:
- Hướng dẫn từng bước
- Sơ đồ kiến trúc
- Các mẫu và anti-patterns phổ biến
- Workflows thực tế
### 4. Báo Cáo Lỗi
Báo cáo các vấn đề bạn gặp phải:
- Mô tả những gì bạn mong đợi
- Mô tả những gì thực sự xảy ra
- Bao gồm các bước để tái tạo
- Thêm phiên bản Claude Code và OS có liên quan
### 5. Feedback và Đề Xuất
Giúp cải thiện hướng dẫn:
- Đề xuất giải thích tốt hơn
- Chỉ ra các khoảng trống trong phạm vi
- Khuyến nghị các phần mới hoặc tái tổ chức
## Bắt Đầu / Getting Started
### 1. Fork và Clone
```bash
git clone https://github.com/luongnv89/claude-howto.git
cd claude-howto
```
### 2. Tạo một Nhánh
Sử dụng tên nhánh mô tả:
```bash
git checkout -b add/feature-name
git checkout -b fix/issue-description
git checkout -b docs/improvement-area
```
### 3. Thiết Lập Môi Trường Của Bạn
Pre-commit hooks chạy cùng các kiểm tra như CI cục bộ trước mỗi commit. Tất cả bốn kiểm tra phải pass trước khi PR được chấp nhận.
**Dependencies được yêu cầu:**
```bash
# Python tooling (uv là trình quản lý package cho dự án này)
pip install uv
uv venv
source .venv/bin/activate
uv pip install -r scripts/requirements-dev.txt
# Markdown linter (Node.js)
npm install -g markdownlint-cli
# Mermaid diagram validator (Node.js)
npm install -g @mermaid-js/mermaid-cli
# Install pre-commit và activate hooks
uv pip install pre-commit
pre-commit install
```
**Xác minh thiết lập của bạn:**
```bash
pre-commit run --all-files
```
Các hooks chạy trên mỗi commit là:

882
vi/INDEX.md Normal file
View File

@@ -0,0 +1,882 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Các Ví Dụ Claude Code - Danh Mục Hoàn Chỉnh
Tài liệu này cung cấp danh mục hoàn chỉnh của tất cả các file ví dụ được tổ chức theo loại tính năng.
## Thống Kê Tóm Tắt
- **Tổng Số File**: 100+ files
- **Danh Mục**: 10 danh mục tính năng
- **Plugins**: 3 plugins hoàn chỉnh
- **Skills**: 6 skills hoàn chỉnh
- **Hooks**: 8 hooks ví dụ
- **Sẵn Sàng Sử Dụng**: Tất cả ví dụ
---
## 01. Lệnh Slash (10 files)
Các lệnh tắt do người dùng gọi cho các workflow phổ biến.
| File | Mô Tả | Use Case |
|------|-------------|----------|
| `optimize.md` | Trình phân tích tối ưu hóa code | Tìm vấn đề hiệu năng |
| `pr.md` | Chuẩn bị pull request | Tự động hóa workflow PR |
| `generate-api-docs.md` | Trình tạo tài liệu API | Tạo tài liệu API |
| `commit.md` | Trình hỗ trợ commit message | Commit chuẩn hóa |
| `setup-ci-cd.md` | Thiết lập pipeline CI/CD | Tự động hóa DevOps |
| `push-all.md` | Push tất cả thay đổi | Workflow push nhanh |
| `unit-test-expand.md` | Mở rộng độ phủ unit test | Tự động hóa test |
| `doc-refactor.md` | Tái cấu trúc tài liệu | Cải thiện tài liệu |
| `pr-slash-command.png` | Ví dụ screenshot | Tham khảo hình ảnh |
| `README.md` | Tài liệu | Hướng dẫn cài đặt và sử dụng |
**Đường Dẫn Cài Đặt**: `.claude/commands/`
**Cách Dùng**: `/optimize`, `/pr`, `/generate-api-docs`, `/commit`, `/setup-ci-cd`, `/push-all`, `/unit-test-expand`, `/doc-refactor`
---
## 02. Bộ Nhớ (6 files)
Ngữ cảnh lưu trữ và tiêu chuẩn dự án.
| File | Mô Tả | Phạm Vi | Vị Trí |
|------|-------------|-------|----------|
| `project-CLAUDE.md` | Tiêu chuẩn dự án nhóm | Toàn dự án | `./CLAUDE.md` |
| `directory-api-CLAUDE.md` | Quy tắc cụ thể cho API | Thư mục | `./src/api/CLAUDE.md` |
| `personal-CLAUDE.md` | Sở thích cá nhân | Người dùng | `~/.claude/CLAUDE.md` |
| `memory-saved.png` | Screenshot: bộ nhớ đã lưu | - | Tham khảo hình ảnh |
| `memory-ask-claude.png` | Screenshot: hỏi Claude | - | Tham khảo hình ảnh |
| `README.md` | Tài liệu | - | Tham khảo |
**Cài Đặt**: Sao chép đến vị trí phù hợp
**Cách Dùng**: Tự động tải bởi Claude
---
## 03. Skills (28 files)
Các khả năng tự động gọi với scripts và templates.
### Code Review Skill (5 files)
```
code-review/
├── SKILL.md # Định nghĩa skill
├── scripts/
│ ├── analyze-metrics.py # Trình phân tích metrics code
│ └── compare-complexity.py # So sánh độ phức tạp
└── templates/
├── review-checklist.md # Checklist review
└── finding-template.md # Tài liệu phát hiện
```
**Mục Đích**: Review code toàn diện với phân tích bảo mật, hiệu năng, và chất lượng
**Tự Động Gọi**: Khi review code
---
### Brand Voice Skill (4 files)
```
brand-voice/
├── SKILL.md # Định nghĩa skill
├── templates/
│ ├── email-template.txt # Định dạng email
│ └── social-post-template.txt # Định dạng social media
└── tone-examples.md # Ví dụ tin nhắn
```
**Mục Đích**: Đảm bảo brand voice nhất quán trong communications
**Tự Động Gọi**: Khi tạo marketing copy
---
### Documentation Generator Skill (2 files)
```
doc-generator/
├── SKILL.md # Định nghĩa skill
└── generate-docs.py # Trình trích xuất doc Python
```
**Mục Đích**: Tạo tài liệu API toàn diện từ source code
**Tự Động Gọi**: Khi tạo/cập nhật tài liệu API
---
### Refactor Skill (5 files)
```
refactor/
├── SKILL.md # Định nghĩa skill
├── scripts/
│ ├── analyze-complexity.py # Trình phân tích độ phức tạp
│ └── detect-smells.py # Trình phát hiện code smells
├── references/
│ ├── code-smells.md # Danh mục code smells
│ └── refactoring-catalog.md # Patterns refactoring
└── templates/
└── refactoring-plan.md # Template kế hoạch refactoring
```
**Mục Đích**: Refactor code có hệ thống với phân tích độ phức tạp
**Tự Động Gọi**: Khi refactor code
---
### Claude MD Skill (1 file)
```
claude-md/
└── SKILL.md # Định nghĩa skill
```
**Mục Đích**: Quản lý và tối ưu hóa files CLAUDE.md
---
### Blog Draft Skill (3 files)
```
blog-draft/
├── SKILL.md # Định nghĩa skill
└── templates/
├── draft-template.md # Template blog draft
└── outline-template.md # Template blog outline
```
**Mục Đích**: Soạn blog posts với cấu trúc nhất quán
**Plus**: `README.md` - Tổng quan skills và hướng dẫn sử dụng
**Đường Dẫn Cài Đặt**: `~/.claude/skills/` hoặc `.claude/skills/`
---
## 04. Tác Nhân Con (9 files)
Các trợ lý AI chuyên biệt với khả năng tùy chỉnh.
| File | Mô Tả | Tools | Use Case |
|------|-------------|-------|----------|
| `code-reviewer.md` | Phân tích chất lượng code | read, grep, diff, lint_runner | Review toàn diện |
| `test-engineer.md` | Phân tích độ phủ test | read, write, bash, grep | Tự động hóa test |
| `documentation-writer.md` | Tạo tài liệu | read, write, grep | Tạo tài liệu |
| `secure-reviewer.md` | Review bảo mật (read-only) | read, grep | Kiểm tra bảo mật |
| `implementation-agent.md` | Triển khai hoàn chỉnh | read, write, bash, grep, edit, glob | Phát triển tính năng |
| `debugger.md` | Chuyên gia debug | read, bash, grep | Điều tra bug |
| `data-scientist.md` | Chuyên gia phân tích dữ liệu | read, write, bash | Workflow dữ liệu |
| `clean-code-reviewer.md` | Tiêu chuẩn clean code | read, grep | Chất lượng code |
| `README.md` | Tài liệu | - | Hướng dẫn cài đặt và sử dụng |
**Đường Dẫn Cài Đặt**: `.claude/agents/`
**Cách Dùng**: Tự động ủy quyền bởi tác nhân chính
---
## 05. Giao Thức MCP (5 files)
Các tích hợp công cụ và API bên ngoài.
| File | Mô Tả | Tích Hợp Với | Use Case |
|------|-------------|-----------------|----------|
| `github-mcp.json` | Tích hợp GitHub | GitHub API | Quản lý PR/issue |
| `database-mcp.json` | Truy vấn database | PostgreSQL/MySQL | Truy vấn dữ liệu trực tiếp |
| `filesystem-mcp.json` | Thao tác file | Filesystem cục bộ | Quản lý file |
| `multi-mcp.json` | Nhiều servers | GitHub + DB + Slack | Tích hợp hoàn chỉnh |
| `README.md` | Tài liệu | - | Hướng dẫn cài đặt và sử dụng |
**Đường Dẫn Cài Đặt**: `.mcp.json` (phạm vi dự án) hoặc `~/.claude.json` (phạm vi người dùng)
**Cách Dùng**: `/mcp__github__list_prs`, v.v.
---
## 06. Hooks (9 files)
Các script tự động hóa dựa trên sự kiện thực thi tự động.
| File | Mô Tả | Sự Kiện | Use Case |
|------|-------------|-------|----------|
| `format-code.sh` | Tự động format code | PreToolUse:Write | Format code |
| `pre-commit.sh` | Chạy test trước commit | PreToolUse:Bash | Tự động hóa test |
| `security-scan.sh` | Quét bảo mật | PostToolUse:Write | Kiểm tra bảo mật |
| `log-bash.sh` | Ghi log bash commands | PostToolUse:Bash | Ghi log commands |
| `validate-prompt.sh` | Xác thực prompts | PreToolUse | Xác thực input |
| `notify-team.sh` | Gửi thông báo | Notification | Thông báo nhóm |
| `context-tracker.py` | Theo dõi usage context window | PostToolUse | Giám sát context |
| `context-tracker-tiktoken.py` | Theo dõi context dựa trên token | PostToolUse | Đếm token chính xác |
| `README.md` | Tài liệu | - | Hướng dẫn cài đặt và sử dụng |
**Đường Dẫn Cài Đặt**: Cấu hình trong `~/.claude/settings.json`
**Cách Dùng**: Cấu hình trong settings, thực thi tự động
**Hook Types** (4 types, 25 events):
- Tool Hooks: PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest
- Session Hooks: SessionStart, SessionEnd, Stop, StopFailure, SubagentStart, SubagentStop
- Task Hooks: UserPromptSubmit, TaskCompleted, TaskCreated, TeammateIdle
- Lifecycle Hooks: ConfigChange, CwdChanged, FileChanged, PreCompact, PostCompact, WorktreeCreate, WorktreeRemove, Notification, InstructionsLoaded, Elicitation, ElicitationResult
---
## 07. Plugins (3 plugins hoàn chỉnh, 40 files)
Các bộ sưu tập tính năng được đóng gói.
### PR Review Plugin (10 files)
```
pr-review/
├── .claude-plugin/
│ └── plugin.json # Plugin manifest
├── commands/
│ ├── review-pr.md # Review toàn diện
│ ├── check-security.md # Kiểm tra bảo mật
│ └── check-tests.md # Kiểm tra độ phủ test
├── agents/
│ ├── security-reviewer.md # Chuyên gia bảo mật
│ ├── test-checker.md # Chuyên gia test
│ └── performance-analyzer.md # Chuyên gia hiệu năng
├── mcp/
│ └── github-config.json # Tích hợp GitHub
├── hooks/
│ └── pre-review.js # Xác thực pre-review
└── README.md # Tài liệu plugin
```
**Tính Năng**: Phân tích bảo mật, độ phủ test, tác động hiệu năng
**Commands**: `/review-pr`, `/check-security`, `/check-tests`
**Cài Đặt**: `/plugin install pr-review`
---
### DevOps Automation Plugin (15 files)
```
devops-automation/
├── .claude-plugin/
│ └── plugin.json # Plugin manifest
├── commands/
│ ├── deploy.md # Triển khai
│ ├── rollback.md # Rollback
│ ├── status.md # Trạng thái hệ thống
│ └── incident.md # Phản hồi sự cố
├── agents/
│ ├── deployment-specialist.md # Chuyên gia triển khai
│ ├── incident-commander.md # Điều phối viên sự cố
│ └── alert-analyzer.md # Trình phân tích alert
├── mcp/
│ └── kubernetes-config.json # Tích hợp Kubernetes
├── hooks/
│ ├── pre-deploy.js # Kiểm tra pre-deployment
│ └── post-deploy.js # Tasks post-deployment
├── scripts/
│ ├── deploy.sh # Tự động hóa triển khai
│ ├── rollback.sh # Tự động hóa rollback
│ └── health-check.sh # Kiểm tra sức khỏe
└── README.md # Tài liệu plugin
```
**Tính Năng**: Triển khai Kubernetes, rollback, giám sát, phản hồi sự cố
**Commands**: `/deploy`, `/rollback`, `/status`, `/incident`
**Cài Đặt**: `/plugin install devops-automation`
---
### Documentation Plugin (14 files)
```
documentation/
├── .claude-plugin/
│ └── plugin.json # Plugin manifest
├── commands/
│ ├── generate-api-docs.md # Tạo tài liệu API
│ ├── generate-readme.md # Tạo README
│ ├── sync-docs.md # Đồng bộ tài liệu
│ └── validate-docs.md # Xác thực tài liệu
├── agents/
│ ├── api-documenter.md # Chuyên gia tài liệu API
│ ├── code-commentator.md # Chuyên gia comment code
│ └── example-generator.md # Trình tạo ví dụ
├── mcp/
│ └── github-docs-config.json # Tích hợp GitHub
├── templates/
│ ├── api-endpoint.md # Template API endpoint
│ ├── function-docs.md # Template tài liệu function
│ └── adr-template.md # Template ADR
└── README.md # Tài liệu plugin
```
**Tính Năng**: Tài liệu API, tạo README, đồng bộ docs, xác thực
**Commands**: `/generate-api-docs`, `/generate-readme`, `/sync-docs`, `/validate-docs`
**Cài Đặt**: `/plugin install documentation`
**Plus**: `README.md` - Tổng quan plugins và hướng dẫn sử dụng
---
## 08. Checkpoints và Rewind (2 files)
Lưu trạng thái conversation và khám phá các cách tiếp cận thay thế.
| File | Mô Tả | Nội Dung |
|------|-------------|---------|
| `README.md` | Tài liệu | Hướng dẫn toàn diện về checkpoints |
| `checkpoint-examples.md` | Ví dụ thực tế | Database migration, tối ưu hóa hiệu năng, UI iteration, debug | | | |
**Khái Niệm Chính**:
- **Checkpoint**: Snapshot của trạng thái conversation
- **Rewind**: Trở về checkpoint trước đó
- **Branch Point**: Khám phá nhiều cách tiếp cận
**Cách Dùng**:
```
# Checkpoints được tạo tự động với mỗi user prompt
# Để rewind, nhấn Esc hai lần hoặc dùng:
/rewind
# Sau đó chọn: Khôi phục code và conversation, Khôi phục conversation,
# Khôi phục code, Tóm tắt từ đây, hoặc Bỏ qua
```
**Use Cases**:
- Thử các implementations khác nhau
- Phục hồi từ lỗi
- Thử nghiệm an toàn
- So sánh giải pháp
- A/B testing
---
## 09. Tính Nâng Cao (3 files)
Các khả năng nâng cao cho workflows phức tạp.
| File | Mô Tả | Tính Năng |
|------|-------------|----------|
| `README.md` | Hướng dẫn hoàn chỉnh | Tài liệu tất cả tính năng nâng cao |
| `config-examples.json` | Ví dụ cấu hình | 10+ cấu hình cụ thể theo use-case |
| `planning-mode-examples.md` | Ví dụ lập kế hoạch | REST API, database migration, refactoring |
| Scheduled Tasks | Tasks định kỳ với `/loop` và cron tools | Workflows định kỳ tự động |
| Chrome Integration | Tự động hóa trình duyệt qua headless Chromium | Testing và scraping web |
| Remote Control (expanded) | Phương thức kết nối, bảo mật, bảng so sánh | Quản lý session từ xa |
| Keyboard Customization | Phím tắt tùy chỉnh, hỗ trợ chord, contexts | Phím tắt cá nhân hóa |
| Desktop App (expanded) | Connectors, launch.json, tính năng enterprise | Tích hợp desktop | | | |
**Tính Năng Nâng Cao Được Bao Phủ**:
### Planning Mode
- Tạo kế hoạch triển khai chi tiết
- Ước tính thời gian và đánh giá rủi ro
- Phân tách task có hệ thống
### Extended Thinking
- Lý luận sâu cho vấn đề phức tạp
- Phân tích quyết định kiến trúc
- Đánh giá trade-off
### Background Tasks
- Operations dài hạn không chặn
- Workflows phát triển song song
- Quản lý và giám sát tasks
### Permission Modes
- **default**: Hỏi phê duyệt cho hành động rủi ro
- **acceptEdits**: Tự động chấp nhận edits file, hỏi cho các khác
- **plan**: Phân tích read-only, không sửa đổi
- **auto**: Tự động phê duyệt hành động an toàn, hỏi cho rủi ro
- **dontAsk**: Chấp nhận tất cả trừ rủi ro
- **bypassPermissions**: Chấp nhận tất cả (yêu cầu `--dangerously-skip-permissions`)
### Headless Mode (`claude -p`)
- Tích hợp CI/CD
- Thực thi task tự động
- Xử lý hàng loạt
### Session Management
- Nhiều work sessions
- Chuyển và lưu sessions
- Session persistence
### Interactive Features
- Phím tắt
- Lịch sử commands
- Tab completion
- Input đa dòng
### Configuration
- Quản lý settings toàn diện
- Cấu hình cụ thể theo môi trường
- Tùy chỉnh theo dự án
### Scheduled Tasks
- Tasks định kỳ với command `/loop`
- Cron tools: CronCreate, CronList, CronDelete
- Workflows định kỳ tự động
### Chrome Integration
- Tự động hóa trình duyệt qua headless Chromium
- Khả năng testing và scraping web
- Tương tác trang và trích xuất dữ liệu
### Remote Control (expanded)
- Phương thức và giao thức kết nối
- Cân nhắc bảo mật và best practices
- Bảng so sánh các tùy chọn truy cập từ xa
### Keyboard Customization
- Cấu hình keybinding tùy chỉnh
- Hỗ trợ chord cho phím tắt đa-phím
- Kích hoạt keybinding nhận biết ngữ cảnh
### Desktop App (expanded)
- Connectors cho tích hợp IDE
- Cấu hình launch.json
- Tính năng và triển khai enterprise
---
## 10. Sử Dụng CLI (1 file)
Các pattern và tham chiếu sử dụng giao diện dòng lệnh.
| File | Mô Tả | Nội Dung |
|------|-------------|---------|
| `README.md` | Tài liệu CLI | Flags, options, và patterns sử dụng |
**Tính Năng CLI Chính**:
- `claude` - Bắt đầu session tương tác
- `claude -p "prompt"` - Mode headless/không-tương-tác
- `claude web` - Khởi chạy web session
- `claude --model` - Chọn model (Sonnet 4.6, Opus 4.6)
- `claude --permission-mode` - Đặt permission mode
- `claude --remote` - Bật điều khiển từ xa qua WebSocket
---
## Files Tài Liệu (13 files)
| File | Vị Trí | Mô Tả |
|------|----------|-------------|
| `README.md` | `/` | Tổng quan ví dụ chính |
| `INDEX.md` | `/` | Danh mục hoàn chỉnh này |
| `QUICK_REFERENCE.md` | `/` | Tham khảo nhanh |
| `README.md` | `/01-slash-commands/` | Hướng dẫn lệnh slash |
| `README.md` | `/02-memory/` | Hướng dẫn bộ nhớ |
| `README.md` | `/03-skills/` | Hướng dẫn skills |
| `README.md` | `/04-subagents/` | Hướng dẫn tác nhân con |
| `README.md` | `/05-mcp/` | Hướng dẫn MCP |
| `README.md` | `/06-hooks/` | Hướng dẫn hooks |
| `README.md` | `/07-plugins/` | Hướng dẫn plugins |
| `README.md` | `/08-checkpoints/` | Hướng dẫn checkpoints |
| `README.md` | `/09-advanced-features/` | Hướng dẫn tính năng nâng cao |
| `README.md` | `/10-cli/` | Hướng dẫn CLI |
---
## Cây File Hoàn Chỉnh
```
claude-howto/
├── README.md # Tổng quan chính
├── INDEX.md # File này
├── QUICK_REFERENCE.md # Tham khảo nhanh
├── claude_concepts_guide.md # Hướng dẫn gốc
├── 01-slash-commands/ # Lệnh Slash
│ ├── optimize.md
│ ├── pr.md
│ ├── generate-api-docs.md
│ ├── commit.md
│ ├── setup-ci-cd.md
│ ├── push-all.md
│ ├── unit-test-expand.md
│ ├── doc-refactor.md
│ ├── pr-slash-command.png
│ └── README.md
├── 02-memory/ # Bộ Nhớ
│ ├── project-CLAUDE.md
│ ├── directory-api-CLAUDE.md
│ ├── personal-CLAUDE.md
│ ├── memory-saved.png
│ ├── memory-ask-claude.png
│ └── README.md
├── 03-skills/ # Skills
│ ├── code-review/
│ │ ├── SKILL.md
│ │ ├── scripts/
│ │ │ ├── analyze-metrics.py
│ │ │ └── compare-complexity.py
│ │ └── templates/
│ │ ├── review-checklist.md
│ │ └── finding-template.md
│ ├── brand-voice/
│ │ ├── SKILL.md
│ │ ├── templates/
│ │ │ ├── email-template.txt
│ │ │ └── social-post-template.txt
│ │ └── tone-examples.md
│ ├── doc-generator/
│ │ ├── SKILL.md
│ │ └── generate-docs.py
│ ├── refactor/
│ │ ├── SKILL.md
│ │ ├── scripts/
│ │ │ ├── analyze-complexity.py
│ │ │ └── detect-smells.py
│ │ ├── references/
│ │ │ ├── code-smells.md
│ │ │ └── refactoring-catalog.md
│ │ └── templates/
│ │ └── refactoring-plan.md
│ ├── claude-md/
│ │ └── SKILL.md
│ ├── blog-draft/
│ │ ├── SKILL.md
│ │ └── templates/
│ │ ├── draft-template.md
│ │ └── outline-template.md
│ └── README.md
├── 04-subagents/ # Tác Nhân Con
│ ├── code-reviewer.md
│ ├── test-engineer.md
│ ├── documentation-writer.md
│ ├── secure-reviewer.md
│ ├── implementation-agent.md
│ ├── debugger.md
│ ├── data-scientist.md
│ ├── clean-code-reviewer.md
│ └── README.md
├── 05-mcp/ # Giao Thức MCP
│ ├── github-mcp.json
│ ├── database-mcp.json
│ ├── filesystem-mcp.json
│ ├── multi-mcp.json
│ └── README.md
├── 06-hooks/ # Hooks
│ ├── format-code.sh
│ ├── pre-commit.sh
│ ├── security-scan.sh
│ ├── log-bash.sh
│ ├── validate-prompt.sh
│ ├── notify-team.sh
│ ├── context-tracker.py
│ ├── context-tracker-tiktoken.py
│ └── README.md
├── 07-plugins/ # Plugins
│ ├── pr-review/
│ │ ├── .claude-plugin/
│ │ │ └── plugin.json
│ │ ├── commands/
│ │ │ ├── review-pr.md
│ │ │ ├── check-security.md
│ │ │ └── check-tests.md
│ │ ├── agents/
│ │ │ ├── security-reviewer.md
│ │ │ ├── test-checker.md
│ │ │ └── performance-analyzer.md
│ │ ├── mcp/
│ │ │ └── github-config.json
│ │ ├── hooks/
│ │ │ └── pre-review.js
│ │ └── README.md
│ ├── devops-automation/
│ │ ├── .claude-plugin/
│ │ │ └── plugin.json
│ │ ├── commands/
│ │ │ ├── deploy.md
│ │ │ ├── rollback.md
│ │ │ ├── status.md
│ │ │ └── incident.md
│ │ ├── agents/
│ │ │ ├── deployment-specialist.md
│ │ │ ├── incident-commander.md
│ │ │ └── alert-analyzer.md
│ │ ├── mcp/
│ │ │ └── kubernetes-config.json
│ │ ├── hooks/
│ │ │ ├── pre-deploy.js
│ │ │ └── post-deploy.js
│ │ ├── scripts/
│ │ │ ├── deploy.sh
│ │ │ ├── rollback.sh
│ │ │ └── health-check.sh
│ │ └── README.md
│ ├── documentation/
│ │ ├── .claude-plugin/
│ │ │ └── plugin.json
│ │ ├── commands/
│ │ │ ├── generate-api-docs.md
│ │ │ ├── generate-readme.md
│ │ │ ├── sync-docs.md
│ │ │ └── validate-docs.md
│ │ ├── agents/
│ │ │ ├── api-documenter.md
│ │ │ ├── code-commentator.md
│ │ │ └── example-generator.md
│ │ ├── mcp/
│ │ │ └── github-docs-config.json
│ │ ├── templates/
│ │ │ ├── api-endpoint.md
│ │ │ ├── function-docs.md
│ │ │ └── adr-template.md
│ │ └── README.md
│ └── README.md
├── 08-checkpoints/ # Checkpoints
│ ├── checkpoint-examples.md
│ └── README.md
├── 09-advanced-features/ # Tính Nâng Cao
│ ├── config-examples.json
│ ├── planning-mode-examples.md
│ └── README.md
└── 10-cli/ # Sử Dụng CLI
└── README.md
```
---
## Bắt Đầu Nhanh Theo Use Case
### Chất Lượng & Reviews Code
```bash
# Cài đặt lệnh slash
cp 01-slash-commands/optimize.md .claude/commands/
# Cài đặt tác nhân con
cp 04-subagents/code-reviewer.md .claude/agents/
# Cài đặt skill
cp -r 03-skills/code-review ~/.claude/skills/
# Hoặc cài đặt plugin hoàn chỉnh
/plugin install pr-review
```
### DevOps & Triển Khai
```bash
# Cài đặt plugin (bao gồm tất cả)
/plugin install devops-automation
```
### Tài Liệu
```bash
# Cài đặt lệnh slash
cp 01-slash-commands/generate-api-docs.md .claude/commands/
# Cài đặt tác nhân con
cp 04-subagents/documentation-writer.md .claude/agents/
# Cài đặt skill
cp -r 03-skills/doc-generator ~/.claude/skills/
# Hoặc cài đặt plugin hoàn chỉnh
/plugin install documentation
```
### Tiêu Chuẩn Nhóm
```bash
# Thiết lập bộ nhớ dự án
cp 02-memory/project-CLAUDE.md ./CLAUDE.md
# Chỉnh sửa để khớp với tiêu chuẩn nhóm của bạn
```
### Tích Hợp Bên Ngoài
```bash
# Đặt biến môi trường
export GITHUB_TOKEN="your_token"
export DATABASE_URL="postgresql://..."
# Cài đặt config MCP (phạm vi dự án)
cp 05-mcp/multi-mcp.json .mcp.json
```
### Tự Động Hóa & Xác Thực
```bash
# Cài đặt hooks
mkdir -p ~/.claude/hooks
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
# Cấu hình hooks trong settings (~/.claude/settings.json)
# Xem 06-hooks/README.md
```
### Thử Nghiệm An Toàn
```bash
# Checkpoints được tạo tự động với mỗi user prompt
# Để rewind: nhấn Esc+Esc hoặc dùng:
/rewind
# Sau đó chọn: Khôi phục code và conversation, Khôi phục conversation,
# Khôi phục code, Tóm tắt từ đây, hoặc Bỏ qua
# Xem 08-checkpoints/README.md cho ví dụ
```
### Workflows Nâng Cao
```bash
# Cấu hình tính năng nâng cao
# Xem 09-advanced-features/config-examples.json
# Sử dụng planning mode
/plan Triển khai tính năng X
# Sử dụng permission modes
claude --permission-mode plan # Cho review code (read-only)
claude --permission-mode acceptEdits # Tự động chấp nhận edits
claude --permission-mode auto # Tự động phê duyệt hành động an toàn
# Chạy trong mode headless cho CI/CD
claude -p "Chạy test và báo cáo kết quả"
# Chạy background tasks
Chạy test trong background
# Xem 09-advanced-features/README.md cho hướng dẫn hoàn chỉnh
```
---
## Ma Trận Phủ Sở Tính Năng
| Danh Mục | Commands | Agents | MCP | Hooks | Scripts | Templates | Docs | Images | Tổng |
|----------|----------|--------|-----|-------|---------|-----------|------|--------|-------|
| **01 Lệnh Slash** | 8 | - | - | - | - | - | 1 | 1 | **10** |
| **02 Bộ Nhớ** | - | - | - | - | - | 3 | 1 | 2 | **6** |
| **03 Skills** | - | - | - | - | 5 | 9 | 1 | - | **28** |
| **04 Tác Nhân Con** | - | 8 | - | - | - | - | 1 | - | **9** |
| **05 MCP** | - | - | 4 | - | - | - | 1 | - | **5** |
| **06 Hooks** | - | - | - | 8 | - | - | 1 | - | **9** |
| **07 Plugins** | 11 | 9 | 3 | 3 | 3 | 3 | 4 | - | **40** |
| **08 Checkpoints** | - | - | - | - | - | - | 1 | 1 | **2** |
| **09 Nâng Cao** | - | - | - | - | - | - | 1 | 2 | **3** |
| **10 CLI** | - | - | - | - | - | - | 1 | - | **1** |
---
## Lộ Trình Học Tập
### Người Mới Bắt Đầu (Tuần 1)
1. ✅ Đọc `README.md`
2. ✅ Cài đặt 1-2 lệnh slash
3. ✅ Tạo file bộ nhớ dự án
4. ✅ Thử các commands cơ bản
### Trung Cấp (Tuần 2-3)
1. ✅ Thiết lập GitHub MCP
2. ✅ Cài đặt một tác nhân con
3. ✅ Thử ủy quyền tasks
4. ✅ Cài đặt một skill
### Nâng Cao (Tuần 4+)
1. ✅ Cài đặt plugin hoàn chỉnh
2. ✅ Tạo lệnh slash tùy chỉnh
3. ✅ Tạo tác nhân con tùy chỉnh
4. ✅ Tạo skill tùy chỉnh
5. ✅ Xây dựng plugin của riêng bạn
### Chuyên Gia (Tuần 5+)
1. ✅ Thiết lập hooks cho tự động hóa
2. ✅ Sử dụng checkpoints để thử nghiệm
3. ✅ Cấu hình planning mode
4. ✅ Sử dụng permission modes hiệu quả
5. ✅ Thiết lập headless mode cho CI/CD
6. ✅ Làm chủ session management
---
## Tìm Kiếm Theo Từ Khóa
### Hiệu Năng
- `01-slash-commands/optimize.md` - Phân tích hiệu năng
- `04-subagents/code-reviewer.md` - Review hiệu năng
- `03-skills/code-review/` - Metrics hiệu năng
- `07-plugins/pr-review/agents/performance-analyzer.md` - Chuyên gia hiệu năng
### Bảo Mật
- `04-subagents/secure-reviewer.md` - Review bảo mật
- `03-skills/code-review/` - Phân tích bảo mật
- `07-plugins/pr-review/` - Kiểm tra bảo mật
### Testing
- `04-subagents/test-engineer.md` - Kỹ sư test
- `07-plugins/pr-review/commands/check-tests.md` - Độ phủ test
### Tài Liệu
- `01-slash-commands/generate-api-docs.md` - Command tài liệu API
- `04-subagents/documentation-writer.md` - Tác nhân viết tài liệu
- `03-skills/doc-generator/` - Skill tạo tài liệu
- `07-plugins/documentation/` - Plugin tài liệu hoàn chỉnh
### Triển Khai
- `07-plugins/devops-automation/` - Giải pháp DevOps hoàn chỉnh
### Tự Động Hóa
- `06-hooks/` - Tự động hóa dựa trên sự kiện
- `06-hooks/pre-commit.sh` - Tự động hóa pre-commit
- `06-hooks/format-code.sh` - Tự động format
- `09-advanced-features/` - Headless mode cho CI/CD
### Xác Thực
- `06-hooks/security-scan.sh` - Xác thực bảo mật
- `06-hooks/validate-prompt.sh` - Xác thực prompt
### Thử Nghiệm
- `08-checkpoints/` - Thử nghiệm an toàn với rewind
- `08-checkpoints/checkpoint-examples.md` - Ví dụ thực tế
### Lập Kế Hoạch
- `09-advanced-features/planning-mode-examples.md` - Ví dụ planning mode
- `09-advanced-features/README.md` - Extended thinking
### Cấu Hình
- `09-advanced-features/config-examples.json` - Ví dụ cấu hình
---
## Ghi Chú
- Tất cả ví dụ đều sẵn sàng sử dụng
- Chỉnh sửa để phù hợp với nhu cầu cụ thể của bạn
- Ví dụ tuân theo best practices của Claude Code
- Mỗi danh mục có README riêng với hướng dẫn chi tiết
- Scripts bao gồm xử lý lỗi thích hợp
- Templates có thể tùy chỉnh
---
## Đóng Góp
Muốn thêm ví dụ nữa? Theo cấu trúc:
1. Tạo thư mục con phù hợp
2. Bao gồm README.md với hướng dẫn sử dụng
3. Theo quy ước đặt tên
4. Test kỹ lưỡng
5. Cập nhật danh mục này
---
**Cập Nhật Lần**: Tháng 3 năm 2026
**Tổng Số Ví Dụ**: 100+ files
**Danh Mục**: 10 tính năng
**Hooks**: 8 scripts tự động hóa
**Ví Dụ Cấu Hình**: 10+ scenarios
**Sẵn Sàng Sử Dụng**: Tất cả ví dụ

742
vi/LEARNING-ROADMAP.md Normal file
View File

@@ -0,0 +1,742 @@
# 📚 Lộ Trình Học Tập Claude Code
**Mới sử dụng Claude Code?** Hướng dẫn này giúp bạn làm chủ các tính năng Claude Code theo tốc độ riêng của bạn. Dù bạn là người mới hoàn toàn hay nhà phát triển có kinh nghiệm, hãy bắt đầu với quiz self-assessment bên dưới để tìm đường đi phù hợp.
---
## 🧭 Tìm Cấp Độ Của Bạn
Không phải ai cũng bắt đầu từ cùng một điểm. Làm quiz self-assessment nhanh này để tìm điểm khởi đầu phù hợp.
**Trả lời những câu hỏi này một cách trung thực:**
- [ ] Tôi có thể bắt đầu Claude Code và có một conversation (`claude`)
- [ ] Tôi đã tạo hoặc chỉnh sửa một file CLAUDE.md
- [ ] Tôi đã sử dụng ít nhất 3 built-in slash commands (ví dụ: /help, /compact, /model)
- [ ] Tôi đã tạo một custom slash command hoặc skill (SKILL.md)
- [ ] Tôi đã cấu hình một MCP server (ví dụ: GitHub, database)
- [ ] Tôi đã thiết lập hooks trong ~/.claude/settings.json
- [ ] Tôi đã tạo hoặc sử dụng custom subagents (.claude/agents/)
- [ ] Tôi đã sử dụng print mode (`claude -p`) để scripting hoặc CI/CD
**Cấp Độ Của Bạn:**
| Checks | Cấp Độ | Bắt Đầu Từ | Thời Gian Hoàn Thành |
|--------|-------|-------------|------------------|
| 0-2 | **Level 1: Người Mới** — Bắt Đầu | [Milestone 1A](#milestone-1a-lệnh-đầu-tiên--bộ-nhớ) | ~3 giờ |
| 3-5 | **Level 2: Trung Cấp** — Xây Dựng Workflows | [Milestone 2A](#milestone-2a-tự-động-hóa-skills--hooks) | ~5 giờ |
| 6-8 | **Level 3: Nâng Cao** — Power User & Team Lead | [Milestone 3A](#milestone-3a-tính-năng-nâng-cao) | ~5 giờ |
> **Mẹo**: Nếu bạn không chắc, hãy bắt đầu một level thấp hơn. Tốt hơn là xem lại tài liệu quen thuộc nhanh hơn là bỏ lỡ các khái niệm nền tảng.
> **Phiên bản tương tác**: Chạy `/self-assessment` trong Claude Code để có quiz hướng dẫn, tương tác chấm điểm proficiency của bạn qua tất cả 10 lĩnh vực tính năng và tạo learning path được cá nhân hóa.
---
## 🎯 Triết Lý Học Tập
Các thư mục trong repository này được đánh số theo **thứ tự học được khuyến nghị** dựa trên ba nguyên tắc chính:
1. **Dependencies** - Các khái niệm nền tảng đến trước
2. **Complexity** - Tính năng dễ hơn trước tính năng nâng cao
3. **Frequency of Use** - Tính năng phổ biến nhất được dạy sớm
Cách tiếp cận này đảm bảo bạn xây dựng nền tảng vững chắc trong khi có lợi ích năng suất ngay lập tức.
---
## 🗺️ Lộ Trình Học Của Bạn
```mermaid
graph TD
Q["🧭 Quiz Self-Assessment<br/>Tìm Cấp Độ Của Bạn"] --> L1
Q --> L2
Q --> L3
subgraph L1["🟢 Level 1: Người Mới — Bắt Đầu"]
direction LR
A["1A: Lệnh Đầu Tiên & Bộ Nhớ<br/>Lệnh Slash + Bộ Nhớ"] --> B["1B: Khám Phá An Toàn<br/>Checkpoints + CLI Cơ Bản"]
end
subgraph L2["🔵 Level 2: Trung Cấp — Xây Dựng Workflows"]
direction LR
C["2A: Tự Động Hóa<br/>Skills + Hooks"] --> D["2B: Tích Hợp<br/>MCP + Tác Nhân Con"]
end
subgraph L3["🔴 Level 3: Nâng Cao — Power User"]
direction LR
E["3A: Tính Năng Nâng Cao<br/>Planning + Permissions"] --> F["3B: Team & Phân Phối<br/>Plugins + CLI Mastery"]
end
L1 --> L2
L2 --> L3
style Q fill:#6A1B9A,color:#fff,stroke:#9C27B0,stroke-width:2px
style A fill:#2E7D32,color:#fff
style B fill:#2E7D32,color:#fff
style C fill:#1565C0,color:#fff
style D fill:#F57C00,color:#fff
style E fill:#C62828,color:#fff
style F fill:#B71C1C,color:#fff
```
**Chú Thích Màu:**
- 💜 Tím: Quiz Self-Assessment
- 🟢 Xanh lá: Level 1 — Đường người mới
- 🔵 Xanh / 🟡 Vàng: Level 2 — Đường trung cấp
- 🔴 Đỏ: Level 3 — Đường nâng cao
---
## 📊 Bảng Lộ Trình Hoàn Chỉnh
| Bước | Tính Năng | Độ Phức Tạp | Thời Gian | Cấp Độ | Dependencies | Tại Sao Học Cái Này | Lợi Ích Chính |
|------|---------|-----------|----------|-------|--------------|------------------|--------------|
| **1** | [Lệnh Slash](../01-slash-commands/) | ⭐ Người mới | 30 phút | Level 1 | None | Gains năng suất nhanh (55+ built-in + 5 bundled skills) | Tự động hóa tức thì, tiêu chuẩn team |
| **2** | [Bộ Nhớ](../02-memory/) | ⭐⭐ Người mới+ | 45 phút | Level 1 | None | Thiết yếu cho tất cả tính năng | Ngữ cảnh lưu trữ, sở thích |
| **3** | [Checkpoints](../08-checkpoints/) | ⭐⭐ Trung cấp | 45 phút | Level 1 | Quản lý session | Khám phá an toàn | Thử nghiệm, phục hồi |
| **4** | [CLI Cơ Bản](../10-cli/) | ⭐⭐ Người mới+ | 30 phút | Level 1 | None | Sử dụng CLI cốt | Mode tương tác & print |
| **5** | [Skills](../03-skills/) | ⭐⭐ Trung cấp | 1 giờ | Level 2 | Lệnh Slash | Chuyên môn tự động | Khả năng tái sử dụng, nhất quán |
| **6** | [Hooks](../06-hooks/) | ⭐⭐ Trung cấp | 1 giờ | Level 2 | Tools, Commands | Tự động hóa workflow (25 sự kiện, 4 types) | Xác thực, cổng chất lượng |
| **7** | [MCP](../05-mcp/) | ⭐⭐⭐ Trung cấp+ | 1 giờ | Level 2 | Cấu hình | Truy cập dữ liệu trực tiếp | Tích hợp thời gian thực, APIs |
| **8** | [Tác Nhân Con](../04-subagents/) | ⭐⭐⭐ Trung cấp+ | 1.5 giờ | Level 2 | Bộ Nhớ, Commands | Xử lý task phức tạp (6 built-in bao gồm Bash) | Ủy quyền, chuyên môn hóa |
| **9** | [Tính Năng Nâng Cao](../09-advanced-features/) | ⭐⭐⭐⭐⭐ Nâng cao | 2-3 giờ | Level 3 | Tất cả trước | Công cụ power user | Planning, Auto Mode, Channels, Voice Dictation, permissions |
| **10** | [Plugins](../07-plugins/) | ⭐⭐⭐⭐ Nâng cao | 2 giờ | Level 3 | Tất cả trước | Giải pháp hoàn chỉnh | Onboarding team, phân phối |
| **11** | [CLI Mastery](../10-cli/) | ⭐⭐⭐ Nâng cao | 1 giờ | Level 3 | Khuyến nghị: Tất cả | Làm chủ usage command-line | Scripting, CI/CD, tự động hóa |
**Tổng Thời Gian Học**: ~11-13 giờ (hoặc nhảy đến cấp độ của bạn và tiết kiệm thời gian)
---
## 🟢 Level 1: Người Mới — Bắt Đầu
**Dành Cho**: Người dùng với 0-2 quiz checks
**Thời Gian**: ~3 giờ
**Tập Trung**: Năng suất tức thì, hiểu nền tảng
**Kết Quả**: Người dùng hàng ngày thoải mái, sẵn sàng cho Level 2
### Milestone 1A: Lệnh Đầu Tiên & Bộ Nhớ
**Chủ Đề**: Lệnh Slash + Bộ Nhớ
**Thời Gian**: 1-2 giờ
**Độ Phức Tạp**: ⭐ Người mới
**Mục Tiêu**: Tăng năng suất tức thì với các commands tùy chỉnh và ngữ cảnh lưu trữ
#### Bạn Sẽ Đạt Được
✅ Tạo custom slash commands cho các tasks lặp lại
✅ Thiết lập bộ nhớ dự án cho tiêu chuẩn team
✅ Cấu hình sở thích cá nhân
✅ Hiểu cách Claude tải ngữ cảnh tự động
#### Thực Hành
```bash
# Exercise 1: Cài đặt slash command đầu tiên của bạn
mkdir -p .claude/commands
cp ../01-slash-commands/optimize.md .claude/commands/
# Exercise 2: Tạo bộ nhớ dự án
cp ../02-memory/project-CLAUDE.md ./CLAUDE.md
# Exercise 3: Thử nghiệm
# Trong Claude Code, gõ: /optimize
```
#### Tiêu Chí Thành Công
- [ ] Gọi thành công command `/optimize`
- [ ] Claude nhớ tiêu chuẩn dự án của bạn từ CLAUDE.md
- [ ] Bạn hiểu khi nào dùng slash commands vs. bộ nhớ
#### Các Bước Tiếp Theo
Khi thoải mái, đọc:
- [../01-slash-commands/README.md](../01-slash-commands/README.md)
- [../02-memory/README.md](../02-memory/README.md)
> **Kiểm tra sự hiểu của bạn**: Chạy `/lesson-quiz slash-commands` hoặc `/lesson-quiz memory` trong Claude Code để kiểm tra những gì bạn đã học.
---
### Milestone 1B: Khám Phá An Toàn
**Chủ Đề**: Checkpoints + CLI Cơ Bản
**Thời Gian**: 1 giờ
**Độ Phức Tạp**: ⭐⭐ Người mới+
**Mục Tiêu**: Học thử nghiệm an toàn và sử dụng các commands CLI cốt
#### Bạn Sẽ Đạt Được
✅ Tạo và khôi phục checkpoints để thử nghiệm an toàn
✅ Hiểu mode tương tác vs. print mode
✅ Sử dụng flags và options CLI cơ bản
✅ Xử lý files qua piping
#### Thực Hành
```bash
# Exercise 1: Thử workflow checkpoint
# Trong Claude Code:
# Thực hiện một số thay đổi thử nghiệm, sau đó nhấn Esc+Esc hoặc dùng /rewind
# Chọn checkpoint trước thử nghiệm của bạn
# Chọn "Khôi phục code và conversation" để quay lại
# Exercise 2: Tương tác vs Print mode
claude "giải thích dự án này" # Mode tương tác
claude -p "giải thích hàm này" # Print mode (không-tương tác)
# Exercise 3: Xử lý nội dung file qua piping
cat error.log | claude -p "giải thích lỗi này"
```
#### Tiêu Chí Thành Công
- [ ] Đã tạo và hoàn nguyên về một checkpoint
- [ ] Đã sử dụng cả mode tương tác và print mode
- [ ] Đã pipe một file đến Claude để phân tích
- [ ] Hiểu khi nào dùng checkpoints để thử nghiệm an toàn
#### Các Bước Tiếp Theo
- Đọc: [../08-checkpoints/README.md](../08-checkpoints/README.md)
- Đọc: [../10-cli/README.md](../10-cli/README.md)
- **Sẵn Sàng Cho Level 2!** Tiếp tục [Milestone 2A](#milestone-2a-tự-động-hóa-skills--hooks)
> **Kiểm tra sự hiểu của bạn**: Chạy `/lesson-quiz checkpoints` hoặc `/lesson-quiz cli` để xác nhận bạn sẵn sàng cho Level 2.
---
## 🔵 Level 2: Trung Cấp — Xây Dựng Workflows
**Dành Cho**: Người dùng với 3-5 quiz checks
**Thời Gian**: ~5 giờ
**Tập Trung**: Tự động hóa, tích hợp, ủy quyền task
**Kết Quả**: Workflows tự động, tích hợp bên ngoài, sẵn sàng cho Level 3
### Kiểm Tra Điều Tiên Quyết
Trước khi bắt đầu Level 2, đảm bảo bạn thoải mái với các khái niệm Level 1 này:
- [ ] Có thể tạo và sử dụng slash commands ([../01-slash-commands/](../01-slash-commands/))
- [ ] Đã thiết lập bộ nhớ dự án qua CLAUDE.md ([../02-memory/](../02-memory/))
- [ ] Biết cách tạo và khôi phục checkpoints ([../08-checkpoints/](../08-checkpoints/))
- [ ] Có thể sử dụng `claude``claude -p` từ command line ([../10-cli/](../10-cli/))
> **Thiếu?** Xem lại các tutorials được liên kết ở trên trước khi tiếp tục.
---
### Milestone 2A: Tự Động Hóa (Skills + Hooks)
**Chủ Đề**: Skills + Hooks
**Thời Gian**: 2-3 giờ
**Độ Phức Tạp**: ⭐⭐ Trung cấp
**Mục Tiêu**: Tự động hóa workflows phổ biến và kiểm tra chất lượng
#### Bạn Sẽ Đạt Được
✅ Auto-invoke các khả năng chuyên biệt với YAML frontmatter (bao gồm các trường `effort``shell`)
✅ Thiết lập tự động hóa dựa trên sự kiện qua 25 hook events
✅ Sử dụng tất cả 4 hook types (command, http, prompt, agent)
✅ Thực thi tiêu chuẩn chất lượng code
✅ Tạo custom hooks cho workflow của bạn
#### Thực Hành
```bash
# Exercise 1: Cài đặt một skill
cp -r ../03-skills/code-review ~/.claude/skills/
# Exercise 2: Thiết lập hooks
mkdir -p ~/.claude/hooks
cp ../06-hooks/pre-tool-check.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/pre-tool-check.sh
# Exercise 3: Cấu hình hooks trong settings
# Thêm vào ~/.claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "~/.claude/hooks/pre-tool-check.sh"
}
]
}
]
}
}
```
#### Tiêu Chí Thành Công
- [ ] Code review skill tự động được gọi khi liên quan
- [ ] PreToolUse hook chạy trước khi thực thi tool
- [ ] Bạn hiểu skill auto-invocation vs. hook event triggers
#### Các Bước Tiếp Theo
- Tạo skill tùy chỉnh của riêng bạn
- Thiết lập additional hooks cho workflow của bạn
- Đọc: [../03-skills/README.md](../03-skills/README.md)
- Đọc: [../06-hooks/README.md](../06-hooks/README.md)
> **Kiểm tra sự hiểu của bạn**: Chạy `/lesson-quiz skills` hoặc `/lesson-quiz hooks` để kiểm tra kiến thức trước khi chuyển tiếp.
---
### Milestone 2B: Tích Hợp (MCP + Tác Nhân Con)
**Chủ Đề**: MCP + Tác Nhân Con
**Thời Gian**: 2-3 giờ
**Độ Phức Tạp**: ⭐⭐⭐ Trung cấp+
**Mục Tiêu**: Tích hợp services bên ngoài và ủy quyền tasks phức tạp
#### Bạn Sẽ Đạt Được
✅ Truy cập dữ liệu trực tiếp từ GitHub, databases, v.v.
✅ Ủy quyền công việc cho các tác nhân AI chuyên biệt
✅ Hiểu khi nào dùng MCP vs. tác nhân con
✅ Xây dựng workflows tích hợp
#### Thực Hành
```bash
# Exercise 1: Thiết lập GitHub MCP
export GITHUB_TOKEN="your_github_token"
claude mcp add github -- npx -y @modelcontextprotocol/server-github
# Exercise 2: Test tích hợp MCP
# Trong Claude Code: /mcp__github__list_prs
# Exercise 3: Cài đặt subagents
mkdir -p .claude/agents
cp ../04-subagents/*.md .claude/agents/
```
#### Exercise Tích Hợp
Thử workflow hoàn chỉnh này:
1. Sử dụng MCP để fetch một GitHub PR
2. Để Claude ủy quyền review cho code-reviewer subagent
3. Sử dụng hooks để chạy tests tự động
#### Tiêu Chí Thành Công
- [ ] Truy vấn thành công dữ liệu GitHub qua MCP
- [ ] Claude ủy quyền tasks phức tạp cho subagents
- [ ] Bạn hiểu sự khác biệt giữa MCP và subagents
- [ ] Kết hợp MCP + subagents + hooks trong một workflow
#### Các Bước Tiếp Theo
- Thiết lập additional MCP servers (database, Slack, v.v.)
- Tạo custom subagents cho domain của bạn
- Đọc: [../05-mcp/README.md](../05-mcp/README.md)
- Đọc: [../04-subagents/README.md](../04-subagents/README.md)
- **Sẵn Sàng Cho Level 3!** Tiếp tục [Milestone 3A](#milestone-3a-tính-năng-nâng-cao)
> **Kiểm tra sự hiểu của bạn**: Chạy `/lesson-quiz mcp` hoặc `/lesson-quiz subagents` để xác nhận bạn sẵn sàng cho Level 3.
---
## 🔴 Level 3: Nâng Cao — Power User & Team Lead
**Dành Cho**: Người dùng với 6-8 quiz checks
**Thời Gian**: ~5 giờ
**Tập Trung**: Công cụ team, CI/CD, tính năng enterprise, phát triển plugin
**Kết Quả**: Power user, có thể thiết lập workflows team và CI/CD
### Kiểm Tra Điều Tiên Quyết
Trước khi bắt đầu Level 3, đảm bảo bạn thoải mái với các khái niệm Level 2 này:
- [ ] Có thể tạo và sử dụng skills với auto-invocation ([../03-skills/](../03-skills/))
- [ ] Đã thiết lập hooks cho tự động hóa dựa trên sự kiện ([../06-hooks/](../06-hooks/))
- [ ] Có thể cấu hình MCP servers cho dữ liệu bên ngoài ([../05-mcp/](../05-mcp/))
- [ ] Biết cách sử dụng subagents để ủy quyền task ([../04-subagents/](../04-subagents/))
> **Thiếu?** Xem lại các tutorials được liên kết ở trên trước khi tiếp tục.
---
### Milestone 3A: Tính Năng Nâng Cao
**Chủ Đề**: Tính Năng Nâng Cao (Planning, Permissions, Extended Thinking, Auto Mode, Channels, Voice Dictation, Remote/Desktop/Web)
**Thời Gian**: 2-3 giờ
**Độ Phức Tạp**: ⭐⭐⭐⭐⭐ Nâng cao
**Mục Tiêu**: Làm chủ workflows nâng cao và công cụ power user
#### Bạn Sẽ Đạt Được
✅ Planning mode cho các tính năng phức tạp
✅ Kiểm soát permission chi tiết với 6 modes (default, acceptEdits, plan, auto, dontAsk, bypassPermissions)
✅ Extended thinking qua Alt+T / Option+T toggle
✅ Quản lý background tasks
✅ Auto Memory cho các sở thích đã học
✅ Auto Mode với bộ phân loại an toàn nền
✅ Channels cho workflows đa session có cấu trúc
✅ Voice Dictation để tương tác không cần tay
✅ Remote control, desktop app, và web sessions
✅ Agent Teams cho cộng tác multi-agent
#### Thực Hành
```bash
# Exercise 1: Sử dụng planning mode
/plan Triển khai hệ thống xác thực người dùng
# Exercise 2: Thử permission modes (6 có sẵn: default, acceptEdits, plan, auto, dontAsk, bypassPermissions)
claude --permission-mode plan "phân tích codebase này"
claude --permission-mode acceptEdits "refactor module auth"
claude --permission-mode auto "triển khai tính năng"
# Exercise 3: Bật extended thinking
# Nhấn Alt+T (Option+T trên macOS) trong session để toggle
# Exercise 4: Workflow checkpoint nâng cao
# 1. Tạo checkpoint "Trạng thái sạch"
# 2. Sử dụng planning mode để thiết kế một tính năng
# 3. Triển khai với ủy quyền subagent
# 4. Chạy tests trong background
# 5. Nếu tests thất bại, rewind về checkpoint
# 6. Thử cách tiếp cận thay thế
# Exercise 5: Thử auto mode (background safety classifier)
claude --permission-mode auto "triển khai trang cài đặt người dùng"
# Exercise 6: Bật agent teams
export CLAUDE_AGENT_TEAMS=1
# Hỏi Claude: "Triển khai tính năng X sử dụng cách tiếp cận nhóm"
# Exercise 7: Tasks định kỳ
/loop 5m /check-status
# Hoặc sử dụng CronCreate cho scheduled tasks tồn tại
# Exercise 8: Channels cho workflows đa session
# Sử dụng channels để tổ chức công việc qua sessions
# Exercise 9: Voice Dictation
# Sử dụng input giọng nói để tương tác không cần tay với Claude Code
```
#### Tiêu Chí Thành Công
- [ ] Đã sử dụng planning mode cho một tính năng phức tạp
- [ ] Đã cấu hình permission modes (plan, acceptEdits, auto, dontAsk)
- [ ] Đã toggle extended thinking với Alt+T / Option+T
- [ ] Đã sử dụng auto mode với background safety classifier
- [ ] Đã sử dụng background tasks cho operations dài
- [ ] Đã khám phá Channels cho workflows đa session
- [ ] Đã thử Voice Dictation cho input không cần tay
- [ ] Hiểu Remote Control, Desktop App, và Web sessions
- [ ] Đã bật và sử dụng Agent Teams cho các tasks cộng tác
- [ ] Đã sử dụng `/loop` cho tasks định kỳ hoặc monitoring theo lịch
#### Các Bước Tiếp Theo
- Đọc: [../09-advanced-features/README.md](../09-advanced-features/README.md)
> **Kiểm tra sự hiểu của bạn**: Chạy `/lesson-quiz advanced` để kiểm tra sự thành thạo của bạn về các tính năng power user.
---
### Milestone 3B: Team & Phân Phối (Plugins + CLI Mastery)
**Chủ Đề**: Plugins + CLI Mastery + CI/CD
**Thời Gian**: 2-3 giờ
**Độ Phức Tạp**: ⭐⭐⭐⭐ Nâng cao
**Mục Tiêu**: Xây dựng công cụ team, tạo plugins, làm chủ tích hợp CI/CD
#### Bạn Sẽ Đạt Được
✅ Cài đặt và tạo plugins được đóng gói hoàn chỉnh
✅ Làm chủ CLI để scripting và tự động hóa
✅ Thiết lập tích hợp CI/CD với `claude -p`
✅ Output JSON cho pipelines tự động
✅ Quản lý session và xử lý hàng loạt
#### Thực Hành
```bash
# Exercise 1: Cài đặt một plugin hoàn chỉnh
# Trong Claude Code: /plugin install pr-review
# Exercise 2: Print mode cho CI/CD
claude -p "Chạy tất cả tests và tạo báo cáo"
# Exercise 3: Output JSON cho scripts
claude -p --output-format json "liệt kê tất cả functions"
# Exercise 4: Quản lý session và tiếp tục
claude -r "feature-auth" "tiếp tục triển khai"
# Exercise 5: Tích hợp CI/CD với constraints
claude -p --max-turns 3 --output-format json "review code"
# Exercise 6: Xử lý hàng loạt
for file in *.md; do
claude -p --output-format json "tóm tắt cái này: $(cat $file)" > ${file%.md}.summary.json
done
```
#### Exercise Tích Hợp CI/CD
Tạo một script CI/CD đơn giản:
1. Sử dụng `claude -p` để review các files đã thay đổi
2. Output kết quả as JSON
3. Xử lý với `jq` cho các vấn đề cụ thể
4. Tích hợp vào GitHub Actions workflow
#### Tiêu Chí Thành Công
- [ ] Đã cài đặt và sử dụng một plugin
- [ ] Đã xây dựng hoặc sửa đổi một plugin cho team của bạn
- [ ] Đã sử dụng print mode (`claude -p`) trong CI/CD
- [ ] Đã tạo output JSON để scripting
- [ ] Đã tiếp tục một session trước đó thành công
- [ ] Đã tạo một script xử lý hàng loạt
- [ ] Đã tích hợp Claude vào một workflow CI/CD
#### Use Cases Thực Te Cho CLI
- **Tự Động Hóa Review Code**: Chạy code reviews trong pipelines CI/CD
- **Phân Tích Log**: Phân tích error logs và outputs hệ thống
- **Tạo Tài Liệu**: Tạo tài liệu hàng loạt
- **Thông Tin Testing**: Phân tích test failures
- **Phân Tích Hiệu Năng**: Review metrics hiệu năng
- **Xử Lý Dữ Liệu**: Chuyển đổi và phân tích files dữ liệu
#### Các Bước Tiếp Theo
- Đọc: [../07-plugins/README.md](../07-plugins/README.md)
- Đọc: [../10-cli/README.md](../10-cli/README.md)
- Tạo shortcuts CLI và plugins cho team
- Thiết lập scripts xử lý hàng loạt
> **Kiểm tra sự hiểu của bạn**: Chạy `/lesson-quiz plugins` hoặc `/lesson-quiz cli` để xác nhận sự thành thạo của bạn.
---
## 🧪 Kiểm Tra Kiến Thức Của Bạn
Repository này bao gồm hai skills tương tác bạn có thể sử dụng bất cứ lúc nào trong Claude Code để đánh giá sự hiểu của bạn:
| Skill | Command | Mục Đích |
|-------|---------|---------|
| **Self-Assessment** | `/self-assessment` | Đánh giá proficiency tổng thể của bạn qua tất cả 10 lĩnh vực tính năng. Chọn Quick (2 phút) hoặc Deep (5 phút) để nhận profile kỹ năng và learning path được cá nhân hóa. |
| **Lesson Quiz** | `/lesson-quiz [lesson]` | Kiểm tra sự hiểu của bạn về một bài học cụ thể với 10 câu hỏi. Sử dụng trước bài học (pre-test), trong khi (kiểm tra tiến độ), hoặc sau (xác nhận thành thạo). |
**Ví Dụ:**
```
/self-assessment # Tìm cấp độ tổng thể của bạn
/lesson-quiz hooks # Quiz về Bài 06: Hooks
/lesson-quiz 03 # Quiz về Bài 03: Skills
/lesson-quiz advanced-features # Quiz về Bài 09
```
---
## ⚡ Đường Dẫn Nhanh
### Nếu Bạn Chỉ Có 15 Phút
**Mục Tiêu**: Có chiến thắng đầu tiên
1. Sao chép một slash command: `cp ../01-slash-commands/optimize.md .claude/commands/`
2. Thử trong Claude Code: `/optimize`
3. Đọc: [../01-slash-commands/README.md](../01-slash-commands/README.md)
**Kết Quả**: Bạn sẽ có một slash command đang hoạt động và hiểu những điều cơ bản
---
### Nếu Bạn Có 1 Giờ
**Mục Tiêu**: Thiết lập các công cụ năng suất thiết yếu
1. **Slash commands** (15 phút): Sao chép và test `/optimize``/pr`
2. **Bộ nhớ dự án** (15 phút): Tạo CLAUDE.md với tiêu chuẩn dự án của bạn
3. **Cài đặt một skill** (15 phút): Thiết lập code-review skill
4. **Thử chúng cùng nhau** (15 phút): Xem chúng hoạt động hòa hợp như thế nào
**Kết Quả**: Tăng năng suất cơ bản với commands, bộ nhớ, và auto-skills
---
### Nếu Bạn Có Một Cuối Tuần
**Mục Tiêu**: Trở thành thành thạo với hầu hết các tính năng
**Sáng Thứ Bảy** (3 giờ):
- Hoàn thành Milestone 1A: Lệnh Slash + Bộ Nhớ
- Hoàn thành Milestone 1B: Checkpoints + CLI Cơ Bản
**Chiều Thứ Bảy** (3 giờ):
- Hoàn thành Milestone 2A: Skills + Hooks
- Hoàn thành Milestone 2B: MCP + Tác Nhân Con
**Chủ Nhật** (4 giờ):
- Hoàn thành Milestone 3A: Tính Năng Nâng Cao
- Hoàn thành Milestone 3B: Plugins + CLI Mastery + CI/CD
- Xây dựng một plugin tùy chỉnh cho team của bạn
**Kết Quả**: Bạn sẽ là một Claude Code power user sẵn sàng để đào tạo người khác và tự động hóa workflows phức tạp
---
## 💡 Mẹo Học Tập
### ✅ Nên Làm
- **Làm quiz trước** để tìm điểm khởi đầu của bạn
- **Hoàn thành hands-on exercises** cho mỗi milestone
- **Bắt đầu đơn giản** và thêm độ phức tạp dần dần
- **Kiểm tra từng tính năng** trước khi chuyển sang cái tiếp theo
- **Ghi chú** những gì hoạt động cho workflow của bạn
- **Tham khảo lại** các khái niệm trước đó khi học các chủ đề nâng cao
- **Thử nghiệm an toàn** sử dụng checkpoints
- **Chia sẻ kiến thức** với team của bạn
### ❌ Không Nên
- **Bỏ qua kiểm tra điều kiện tiên quyết** khi nhảy đến level cao hơn
- **Cố học tất cả cùng lúc** - sẽ quá tải
- **Sao chép cấu hình mà không hiểu** - bạn sẽ không biết cách debug
- **Quên test** - luôn xác minh tính năng hoạt động
- **Vội vàng qua milestones** - dành thời gian để hiểu
- **Bỏ qua tài liệu** - mỗi README có chi tiết quý giá
- **Làm việc cô lập** - thảo luận với teammates
---
## 🎓 Phong Cách Học
### Người Học Qua Hình Ảnh
- Nghiên các mermaid diagrams trong mỗi README
- Theo dõi flow thực thi command
- Vẽ workflow diagrams của riêng bạn
- Sử dụng learning path hình ảnh ở trên
### Người Học Thực Hành
- Hoàn thành mọi hands-on exercise
- Thử nghiệm với các biến thể
- Phá vỡ và sửa chữa (sử dụng checkpoints!)
- Tạo ví dụ của riêng bạn
### Người Học Đọc
- Đọc mỗi README một cách kỹ lưỡng
- Nghiên các ví dụ code
- Review các bảng so sánh
- Đọc các blog posts được liên kết trong resources
### Người Học Xã Hội
- Thiết lập sessions pair programming
- Dạy khái niệm cho teammates
- Tham gia discussions cộng đồng Claude Code
- Chia sẻ cấu hình tùy chỉnh của bạn
---
## 📈 Theo Dõi Tiến Độ
Sử dụng các checklists này để theo dõi tiến độ của bạn theo level. Chạy `/self-assessment` bất cứ lúc nào để nhận profile kỹ năng cập nhật, hoặc `/lesson-quiz [lesson]` sau mỗi tutorial để xác nhận sự hiểu của bạn.
### 🟢 Level 1: Người Mới
- [ ] Hoàn thành [../01-slash-commands/](../01-slash-commands/)
- [ ] Hoàn thành [../02-memory/](../02-memory/)
- [ ] Đã tạo slash command tùy chỉnh đầu tiên
- [ ] Thiết lập bộ nhớ dự án
- [ ] **Milestone 1A đạt được**
- [ ] Hoàn thành [../08-checkpoints/](../08-checkpoints/)
- [ ] Hoàn thành [../10-cli/](../10-cli/) cơ bản
- [ ] Đã tạo và hoàn nguyên về một checkpoint
- [ ] Đã sử dụng mode tương tác và print mode
- [ ] **Milestone 1B đạt được**
### 🔵 Level 2: Trung Cấp
- [ ] Hoàn thành [../03-skills/](../03-skills/)
- [ ] Hoàn thành [../06-hooks/](../06-hooks/)
- [ ] Đã cài đặt skill đầu tiên
- [ ] Thiết lập PreToolUse hook
- [ ] **Milestone 2A đạt được**
- [ ] Hoàn thành [../05-mcp/](../05-mcp/)
- [ ] Hoàn thành [../04-subagents/](../04-subagents/)
- [ ] Kết nối GitHub MCP
- [ ] Đã tạo subagent tùy chỉnh
- [ ] Kết hợp các tích hợp trong một workflow
- [ ] **Milestone 2B đạt được**
### 🔴 Level 3: Nâng Cao
- [ ] Hoàn thành [../09-advanced-features/](../09-advanced-features/)
- [ ] Đã sử dụng planning mode thành công
- [ ] Đã cấu hình permission modes (6 modes bao gồm auto)
- [ ] Đã sử dụng auto mode với safety classifier
- [ ] Đã sử dụng extended thinking toggle
- [ ] Đã khám phá Channels và Voice Dictation
- [ ] **Milestone 3A đạt được**
- [ ] Hoàn thành [../07-plugins/](../07-plugins/)
- [ ] Hoàn thành [../10-cli/](../10-cli/) sử dụng nâng cao
- [ ] Thiết lập print mode (`claude -p`) CI/CD
- [ ] Đã tạo output JSON để tự động hóa
- [ ] Tích hợp Claude vào pipeline CI/CD
- [ ] Đã tạo plugin team
- [ ] **Milestone 3B đạt được**
---
## 🆘 Thách Thức Học Phổ Biến
### Thách Thức 1: "Quá nhiều khái niệm cùng lúc"
**Giải Pháp**: Tập trung vào một milestone tại một thời điểm. Hoàn thành tất cả exercises trước khi chuyển tiếp.
### Thách Thức 2: "Không biết dùng tính năng nào khi nào"
**Giải Pháp**: Tham khảo [Use Case Matrix](../README.md#use-case-matrix) trong README chính.
### Thách Thức 3: "Cấu hình không hoạt động"
**Giải Pháp**: Kiểm tra phần [Troubleshooting](../README.md#troubleshooting) và xác minh vị trí files.
### Thách Thức 4: "Các khái niệm có vẻ trùng lặp"
**Giải Pháp**: Review bảng [Feature Comparison](../README.md#feature-comparison) để hiểu sự khác biệt.
### Thách Thức 5: "Khó nhớ mọi thứ"
**Giải Pháp**: Tạo cheat sheet của riêng bạn. Sử dụng checkpoints để thử nghiệm an toàn.
### Thách Thức 6: "Tôi có kinh nghiệm nhưng không chắc bắt đầu từ đâu"
**Giải Pháp**: Làm [Self-Assessment Quiz](#-tìm-cấp-độ-của-bạn) ở trên. Nhảy đến cấp độ của bạn và sử dụng kiểm tra điều kiện tiên quyết để xác định bất kỳ khoảng trống.
---
## 🎯 Tiếp Theo Sau Khi Hoàn Thành?
Khi bạn đã hoàn thành tất cả milestones:
1. **Tạo tài liệu team** - Tài liệu hóa thiết lập Claude Code của team
2. **Xây dựng custom plugins** - Đóng gói workflows của team
3. **Khám Phá Remote Control** - Điều khiển sessions Claude Code theo chương trình từ các công cụ bên ngoài
4. **Thử Web Sessions** - Sử dụng Claude Code qua interfaces dựa trên trình duyệt để phát triển từ xa
5. **Sử dụng Desktop App** - Truy cập các tính năng Claude Code qua ứng dụng desktop native
6. **Sử Dụng Auto Mode** - Để Claude làm việc tự động với bộ phân loại an toàn nền
7. **Tận Dụng Auto Memory** - Để Claude học các sở thích của bạn tự động theo thời gian
8. **Thiết Lập Agent Teams** - Phối hợp nhiều agents trên các tasks phức tạp, đa diện
9. **Sử Dụng Channels** - Tổ chức công việc qua workflows đa session có cấu trúc
10. **Thử Voice Dictation** - Sử dụng input giọng nói không cần tay để tương tác với Claude Code
11. **Sử Dụng Scheduled Tasks** - Tự động hóa các kiểm tra định kỳ với `/loop` và cron tools
12. **Đóng góp ví dụ** - Chia sẻ với cộng đồng
13. **Đào tạo người khác** - Giúp teammates học
14. **Tối ưu hóa workflows** - Cải tiến liên tục dựa trên usage
15. **Cập nhật** - Theo dõi các bản phát hành Claude Code và tính năng mới
---
## 📚 Tài Nguyên Thêm
### Tài Liệu Chính Thức
- [Tài Liệu Claude Code](https://code.claude.com/docs/en/overview)
- [Tài Liệu Anthropic](https://docs.anthropic.com)
- [Đặc Tả Giao Thức MCP](https://modelcontextprotocol.io)
### Blog Posts
- [Khám Phá Lệnh Slash Claude Code](https://medium.com/@luongnv89/discovering-claude-code-slash-commands-cdc17f0dfb29)
### Cộng Đồng
- [Anthropic Cookbook](https://github.com/anthropics/anthropic-cookbook)
- [Kho Repositories MCP Servers](https://github.com/modelcontextprotocol/servers)
---
## 💬 Feedback & Hỗ Trợ
- **Tìm thấy vấn đề?** Tạo issue trong repository
- **Có đề xuất?** Gửi pull request
- **Cần trợ giúp?** Kiểm tra tài liệu hoặc hỏi cộng đồng
---
**Cập Nhật Lần**: Tháng 3 năm 2026
**Được Duy Trì Bởi**: Những người đóng góp Claude How-To
**Giấy Phép**: Mục đích giáo dục, miễn phí sử dụng và điều chỉnh
---
[← Quay Lại README Chính](../README.md)

506
vi/QUICK_REFERENCE.md Normal file
View File

@@ -0,0 +1,506 @@
<picture>
<source media="(prefers-color-scheme: dark)" srcset="../resources/logos/claude-howto-logo-dark.svg">
<img alt="Claude How To" src="../resources/logos/claude-howto-logo.svg">
</picture>
# Ví Dụ Claude Code - Tham Khảo Nhanh
## 🚀 Lệnh Cài Đặt Nhanh
### Lệnh Slash
```bash
# Cài đặt tất cả
cp 01-slash-commands/*.md .claude/commands/
# Cài đặt cụ thể
cp 01-slash-commands/optimize.md .claude/commands/
```
### Bộ Nhớ
```bash
# Bộ nhớ dự án
cp 02-memory/project-CLAUDE.md ./CLAUDE.md
# Bộ nhớ cá nhân
cp 02-memory/personal-CLAUDE.md ~/.claude/CLAUDE.md
```
### Skills
```bash
# Skills cá nhân
cp -r 03-skills/code-review ~/.claude/skills/
# Skills dự án
cp -r 03-skills/code-review .claude/skills/
```
### Tác Nhân Con
```bash
# Cài đặt tất cả
cp 04-subagents/*.md .claude/agents/
# Cài đặt cụ thể
cp 04-subagents/code-reviewer.md .claude/agents/
```
### MCP
```bash
# Thiết lập thông tin xác thực
export GITHUB_TOKEN="your_token"
export DATABASE_URL="postgresql://..."
# Cài đặt cấu hình (phạm vi dự án)
cp 05-mcp/github-mcp.json .mcp.json
# Hoặc phạm vi người dùng: thêm vào ~/.claude.json
```
### Hooks
```bash
# Cài đặt hooks
mkdir -p ~/.claude/hooks
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
# Cấu hình trong settings (~/.claude/settings.json)
```
### Plugins
```bash
# Cài đặt từ ví dụ (nếu đã xuất bản)
/plugin install pr-review
/plugin install devops-automation
/plugin install documentation
```
### Checkpoints
```bash
# Checkpoints được tạo tự động với mọi prompt của người dùng
# Để quay lại, nhấn Esc hai lần hoặc sử dụng:
/rewind
# Sau đó chọn: Khôi phục code và cuộc hội thoại, Khôi phục cuộc hội thoại,
# Khôi phục code, Tóm tắt từ đây, hoặc Thôi
```
### Tính Năng Nâng Cao
```bash
# Cấu hình trong settings (.claude/settings.json)
# Xem 09-advanced-features/config-examples.json
# Chế độ lập kế hoạch
/plan Mô tả tác vụ
# Chế độ quyền (sử dụng cờ --permission-mode)
# default - Hỏi phê duyệt cho các hành động rủi ro
# acceptEdits - Tự động chấp nhận chỉnh sửa file, hỏi cho các hành động khác
# plan - Chỉ đọc phân tích, không sửa đổi
# dontAsk - Chấp nhận tất cả hành động trừ các hành động rủi ro
# auto - Bộ phân loại nền quyết định quyền tự động
# bypassPermissions - Chấp nhận tất cả hành động (yêu cầu --dangerously-skip-permissions)
# Quản lý phiên
/resume # Tiếp tục cuộc hội thoại trước
/rename "name" # Đặt tên cho phiên hiện tại
/fork # Fork phiên hiện tại
claude -c # Tiếp tục cuộc hội thoại gần nhất
claude -r "session" # Tiếp tục phiên theo tên/ID
```
---
## 📋 Bảng Cheat Sheet Tính Năng
| Tính Năng | Đường Dẫn Cài Đặt | Cách Sử Dụng |
|---------|-------------|-------|
| **Lệnh Slash (55+)** | `.claude/commands/*.md` | `/tên-lệnh` |
| **Bộ Nhớ** | `./CLAUDE.md` | Tự động tải |
| **Skills** | `.claude/skills/*/SKILL.md` | Tự động gọi |
| **Tác Nhân Con** | `.claude/agents/*.md` | Tự động ủy quyền |
| **MCP** | `.mcp.json` (dự án) hoặc `~/.claude.json` (người dùng) | `/mcp__server__action` |
| **Hooks (25 sự kiện)** | `~/.claude/hooks/*.sh` | Kích hoạt sự kiện (4 loại) |
| **Plugins** | Thông qua `/plugin install` | Gói tất cả |
| **Checkpoints** | Được tích hợp sẵn | `Esc+Esc` hoặc `/rewind` |
| **Chế Độ Lập Kế Hoạch** | Được tích hợp sẵn | `/plan <tác vụ>` |
| **Chế Độ Quyền (6)** | Được tích hợp sẵn | `--allowedTools`, `--permission-mode` |
| **Phiên Làm Việc** | Được tích hợp sẵn | `/session <lệnh>` |
| **Tác Vụ Nền** | Được tích hợp sẵn | Chạy trong nền |
| **Điều Khiển Từ Xa** | Được tích hợp sẵn | WebSocket API |
| **Phiên Web** | Được tích hợp sẵn | `claude web` |
| **Git Worktrees** | Được tích hợp sẵn | `/worktree` |
| **Tự Động Bộ Nhớ** | Được tích hợp sẵn | Tự động lưu vào CLAUDE.md |
| **Danh Sách Tác Vụ** | Được tích hợp sẵn | `/task list` |
| **Skills Được Gói (5)** | Được tích hợp sẵn | `/simplify`, `/loop`, `/claude-api`, `/voice`, `/browse` |
---
## 🎯 Trường Hợp Sử Dụng Phổ Biến
### Review Code
```bash
# Cách 1: Lệnh slash
cp 01-slash-commands/optimize.md .claude/commands/
# Sử dụng: /optimize
# Cách 2: Tác nhân con
cp 04-subagents/code-reviewer.md .claude/agents/
# Sử dụng: Tự động ủy quyền
# Cách 3: Skill
cp -r 03-skills/code-review ~/.claude/skills/
# Sử dụng: Tự động gọi
# Cách 4: Plugin (tốt nhất)
/plugin install pr-review
# Sử dụng: /review-pr
```
### Tài Liệu
```bash
# Lệnh slash
cp 01-slash-commands/generate-api-docs.md .claude/commands/
# Tác nhân con
cp 04-subagents/documentation-writer.md .claude/agents/
# Skill
cp -r 03-skills/doc-generator ~/.claude/skills/
# Plugin (giải pháp hoàn chỉnh)
/plugin install documentation
```
### DevOps
```bash
# Plugin hoàn chỉnh
/plugin install devops-automation
# Lệnh: /deploy, /rollback, /status, /incident
```
### Tiêu Chuẩn Đội
```bash
# Bộ nhớ dự án
cp 02-memory/project-CLAUDE.md ./CLAUDE.md
# Chỉnh sửa cho đội của bạn
vim CLAUDE.md
```
### Tự Động Hóa & Hooks
```bash
# Cài đặt hooks (25 sự kiện, 4 loại: command, http, prompt, agent)
mkdir -p ~/.claude/hooks
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
# Ví dụ:
# - Tests pre-commit: pre-commit.sh
# - Tự động định dạng code: format-code.sh
# - Quét bảo mật: security-scan.sh
# Chế độ Tự Động cho workflow hoàn toàn tự chủ
claude --enable-auto-mode -p "Refactor và test module auth"
# Hoặc chuyển đổi chế độ tương tác với Shift+Tab
```
### Refactor An Toàn
```bash
# Checkpoints được tạo tự động trước mỗi prompt
# Thử refactoring
# Nếu thành công: tiếp tục
# Nếu thất bại: nhấn Esc+Esc hoặc sử dụng /rewind để quay lại
```
### Triển Khai Phức Tạp
```bash
# Sử dụng chế độ lập kế hoạch
/plan Triển khai hệ thống xác thực người dùng
# Claude tạo kế hoạch chi tiết
# Xem xét và phê duyệt
# Claude triển khai có hệ thống
```
### Tích Hợp CI/CD
```bash
# Chạy ở chế độ headless (không tương tác)
claude -p "Chạy tất cả tests và tạo báo cáo"
# Với chế độ quyền cho CI
claude -p "Chạy tests" --permission-mode dontAsk
# Với Chế độ Tự Động cho tác vụ CI hoàn toàn tự chủ
claude --enable-auto-mode -p "Chạy tests và sửa lỗi thất bại"
# Với hooks để tự động hóa
# Xem 09-advanced-features/README.md
```
### Học & Thử Nghiệm
```bash
# Sử dụng chế độ kế hoạch để phân tích an toàn
claude --permission-mode plan
# Thử nghiệm an toàn - checkpoints được tạo tự động
# Nếu cần quay lại: nhấn Esc+Esc hoặc sử dụng /rewind
```
### Đội Tác Nhân
```bash
# Bật đội tác nhân
export CLAUDE_AGENT_TEAMS=1
# Hoặc trong settings.json
{ "agentTeams": { "enabled": true } }
# Bắt đầu với: "Triển khai tính năng X sử dụng cách tiếp cận đội"
```
### Tác Vụ Định Kỳ
```bash
# Chạy một lệnh mỗi 5 phút
/loop 5m /check-status
# Nhắc nhở một lần
/loop 30m "nhắc tôi kiểm tra deploy"
```
---
## 📁 Tham Khảo Vị Trí File
```
Dự Án Của Bạn/
├── .claude/
│ ├── commands/ # Lệnh slash đặt ở đây
│ ├── agents/ # Tác nhân con đặt ở đây
│ ├── skills/ # Skills dự án đặt ở đây
│ └── settings.json # Cài đặt dự án (hooks, v.v.)
├── .mcp.json # Cấu hình MCP (phạm vi dự án)
├── CLAUDE.md # Bộ nhớ dự án
└── src/
└── api/
└── CLAUDE.md # Bộ nhớ cụ thể thư mục
Home Người Dùng/
├── .claude/
│ ├── commands/ # Lệnh cá nhân
│ ├── agents/ # Tác nhân cá nhân
│ ├── skills/ # Skills cá nhân
│ ├── hooks/ # Script hooks
│ ├── settings.json # Cài đặt người dùng
│ ├── managed-settings.d/ # Cài đặt được quản lý (doanh nghiệp/tổ chức)
│ └── CLAUDE.md # Bộ nhớ cá nhân
└── .claude.json # Cấu hình MCP cá nhân (phạm vi người dùng)
```
---
## 🔍 Tìm Ví Dụ
### Theo Danh Mục
- **Lệnh Slash**: `01-slash-commands/`
- **Bộ Nhớ**: `02-memory/`
- **Skills**: `03-skills/`
- **Tác Nhân Con**: `04-subagents/`
- **MCP**: `05-mcp/`
- **Hooks**: `06-hooks/`
- **Plugins**: `07-plugins/`
- **Checkpoints**: `08-checkpoints/`
- **Tính Năng Nâng Cao**: `09-advanced-features/`
- **CLI**: `10-cli/`
### Theo Trường Hợp Sử Dụng
- **Hiệu Suất**: `01-slash-commands/optimize.md`
- **Bảo Mật**: `04-subagents/secure-reviewer.md`
- **Testing**: `04-subagents/test-engineer.md`
- **Tài Liệu**: `03-skills/doc-generator/`
- **DevOps**: `07-plugins/devops-automation/`
### Theo Độ Phức Tạp
- **Đơn Giản**: Lệnh slash
- **Trung Bình**: Tác nhân con, Bộ nhớ
- **Nâng Cao**: Skills, Hooks
- **Hoàn Chỉnh**: Plugins
---
## 🎓 Lộ Trình Học
### Ngày 1
```bash
# Đọc tổng quan
cat README.md
# Cài đặt một lệnh
cp 01-slash-commands/optimize.md .claude/commands/
# Thử dùng
/optimize
```
### Ngày 2-3
```bash
# Thiết lập bộ nhớ
cp 02-memory/project-CLAUDE.md ./CLAUDE.md
vim CLAUDE.md
# Cài đặt tác nhân con
cp 04-subagents/code-reviewer.md .claude/agents/
```
### Ngày 4-5
```bash
# Thiết lập MCP
export GITHUB_TOKEN="your_token"
cp 05-mcp/github-mcp.json .mcp.json
# Thử lệnh MCP
/mcp__github__list_prs
```
### Tuần 2
```bash
# Cài đặt skill
cp -r 03-skills/code-review ~/.claude/skills/
# Để nó tự động gọi
# Chỉ cần nói: "Review đoạn code này tìm lỗi"
```
### Tuần 3+
```bash
# Cài đặt plugin hoàn chỉnh
/plugin install pr-review
# Sử dụng tính năng được gói
/review-pr
/check-security
/check-tests
```
---
## Tính Năng Mới (Tháng 3/2026)
| Tính Năng | Mô Tả | Cách Sử Dụng |
|---------|-------------|-------|
| **Chế Độ Tự Động** | Vận hành hoàn toàn tự chủ với bộ phân loại nền | Cờ `--enable-auto-mode`, `Shift+Tab` để chuyển đổi chế độ |
| **Kênh** | Tích hợp Discord và Telegram | Cờ `--channels`, bot Discord/Telegram |
| **Nhập Liệu Giọng Nói** | Nói lệnh và bối cảnh cho Claude | Lệnh `/voice` |
| **Hooks (25 sự kiện)** | Hệ thống hook mở rộng với 4 loại | Các loại hook command, http, prompt, agent |
| **MCP Elicitation** | MCP servers có thể yêu cầu input người dùng tại runtime | Tự động nhắc khi server cần làm rõ |
| **WebSocket MCP** | Vận chuyển WebSocket cho kết nối MCP | Cấu hình trong `.mcp.json` với URL `ws://` |
| **Plugin LSP** | Hỗ trợ Language Server Protocol cho plugins | `userConfig`, biến `${CLAUDE_PLUGIN_DATA}` |
| **Điều Khiển Từ Xa** | Điều khiển Claude Code qua WebSocket API | `claude --remote` cho tích hợp bên ngoài |
| **Phiên Web** | Giao diện Claude Code trên trình duyệt | `claude web` để khởi động |
| **Ứng Dụng Desktop** | Ứng dụng desktop native | Tải từ claude.ai/download |
| **Danh Sách Tác Vụ** | Quản lý tác vụ nền | `/task list`, `/task status <id>` |
| **Tự Động Bộ Nhớ** | Tự động lưu bộ nhớ từ cuộc hội thoại | Claude tự động lưu bối cảnh chính vào CLAUDE.md |
| **Git Worktrees** | Không gian làm việc cô lập cho phát triển song song | `/worktree` để tạo không gian làm việc cô lập |
| **Chọn Mô Hình** | Chuyển đổi giữa Sonnet 4.6 và Opus 4.6 | `/model` hoặc cờ `--model` |
| **Đội Tác Nhân** | Phối hợp nhiều tác nhân trên tác vụ | Bật với biến môi trường `CLAUDE_AGENT_TEAMS=1` |
| **Tác Vụ Định Kỳ** | Tác vụ định kỳ với `/loop` | `/loop 5m /command` hoặc công cụ CronCreate |
| **Tích Hợp Chrome** | Tự động hóa trình duyệt | Cờ `--chrome` hoặc lệnh `/chrome` |
| **Tùy Chỉnh Bàn Phím** | Phím tắt tùy chỉnh | Lệnh `/keybindings` |
---
## Mẹo & Thủ Thuật
### Tùy Chỉnh
- Bắt đầu với ví dụ nguyên trạng
- Chỉnh sửa phù hợp nhu cầu của bạn
- Thử nghiệm trước khi chia sẻ với đội
- Sử dụng version control cho cấu hình của bạn
### Thực Hành Tốt Nhất
- Sử dụng bộ nhớ cho tiêu chuẩn đội
- Sử dụng plugins cho workflow hoàn chỉnh
- Sử dụng tác nhân con cho tác vụ phức tạp
- Sử dụng lệnh slash cho tác vụ nhanh
### Xử Lý Sự Cố
```bash
# Kiểm tra vị trí file
ls -la .claude/commands/
ls -la .claude/agents/
# Xác minh cú pháp YAML
head -20 .claude/agents/code-reviewer.md
# Kiểm tra kết nối MCP
echo $GITHUB_TOKEN
```
---
## 📊 Ma Trận Tính Năng
| Nhu Cầu | Sử Dụng Cái Này | Ví Dụ |
|------|----------|---------|
| Lối tắt nhanh | Lệnh Slash (55+) | `01-slash-commands/optimize.md` |
| Tiêu chuẩn đội | Bộ Nhớ | `02-memory/project-CLAUDE.md` |
| Workflow tự động | Skill | `03-skills/code-review/` |
| Tác vụ chuyên biệt | Tác Nhân Con | `04-subagents/code-reviewer.md` |
| Dữ liệu bên ngoài | MCP (+ Elicitation, WebSocket) | `05-mcp/github-mcp.json` |
| Tự động hóa sự kiện | Hook (25 sự kiện, 4 loại) | `06-hooks/pre-commit.sh` |
| Giải pháp hoàn chỉnh | Plugin (+ hỗ trợ LSP) | `07-plugins/pr-review/` |
| Thử nghiệm an toàn | Checkpoint | `08-checkpoints/checkpoint-examples.md` |
| Hoàn toàn tự chủ | Chế Độ Tự Động | `--enable-auto-mode` hoặc `Shift+Tab` |
| Tích hợp chat | Kênh | `--channels` (Discord, Telegram) |
| Pipeline CI/CD | CLI | `10-cli/README.md` |
---
## 🔗 Liên Kết Nhanh
- **Hướng Dẫn Chính**: `README.md`
- **Index Hoàn Chỉnh**: `INDEX.md`
- **Tóm Tắt**: `EXAMPLES_SUMMARY.md`
- **Hướng Dẫn Gốc**: `claude_concepts_guide.md`
---
## 📞 Câu Hỏi Phổ Biến
**Câu: Tôi nên dùng cái nào?**
Đáp: Bắt đầu với lệnh slash, thêm tính năng khi cần.
**Câu: Tôi có thể kết hợp tính năng không?**
Đáp: Có! Chúng hoạt động cùng nhau. Bộ Nhớ + Lệnh + MCP = mạnh mẽ.
**Câu: Làm sao chia sẻ với đội?**
Đáp: Commit thư mục `.claude/` vào git.
**Câu: Còn bí mật thì sao?**
Đáp: Sử dụng biến môi trường, không bao giờ hardcode.
**Câu: Tôi có thể sửa ví dụ không?**
Đáp: Chắc chắn rồi! Chúng là mẫu để tùy chỉnh.
---
## ✅ Checklist
Checklist bắt đầu:
- [ ] Đọc `README.md`
- [ ] Cài đặt 1 lệnh slash
- [ ] Thử lệnh đó
- [ ] Tạo `CLAUDE.md` dự án
- [ ] Cài đặt 1 tác nhân con
- [ ] Thiết lập 1 tích hợp MCP
- [ ] Cài đặt 1 skill
- [ ] Thử một plugin hoàn chỉnh
- [ ] Tùy chỉnh cho nhu cầu của bạn
- [ ] Chia sẻ với đội
---
**Bắt Đầu Nhanh**: `cat README.md`
**Index Hoàn Chỉnh**: `cat INDEX.md`
**Tham Khảo Này**: Giữ sẵn để tham khảo nhanh!

71
vi/README.md Normal file
View File

@@ -0,0 +1,71 @@
# Hướng Dẫn Claude Code
> **Làm chủ Claude Code trong một cuối tuần**
Đây là bản tiếng Việt của tài liệu [Claude Code How-To Guide](../README.md).
## 📖 Giới Thiệu
Tài liệu này giúp bạn:
- Hiểu và sử dụng Claude Code hiệu quả
- Tự động hóa các tác vụ phát triển phần mềm
- Tích hợp Claude Code vào workflow hàng ngày
## 🚀 Bắt Đầu Nhanh
### Yêu Cầu
- Claude Code đã được cài đặt
- Kiến thức cơ bản về dòng lệnh (terminal)
- Kiến thức cơ bản về lập trình
### Cài Đặt
```bash
# Clone repository này
git clone https://github.com/luongnv89/claude-howto.git
cd claude-howto
# Copy các lệnh slash vào project của bạn
mkdir -p .claude/commands
cp 01-slash-commands/*.md .claude/commands/
```
## 📚 Cấu Trúc Tài Liệu
Tài liệu được chia thành 10 modules theo trình tự học:
1. **[01 - Lệnh Slash](01-slash-commands/)** - Các lệnh tắt để tăng năng suất
2. **[02 - Bộ Nhớ](02-memory/)** - Lưu trữ context xuyên suốt các phiên
3. **[03 - Skills](03-skills/)** - Các khả năng có thể tái sử dụng
4. **[04 - Tác Nhân Con](04-subagents/)** - Các trợ lý AI chuyên biệt
5. **[05 - MCP](05-mcp/)** - Giao thức Model Context
6. **[06 - Hooks](06-hooks/)** - Tự động hóa dựa trên sự kiện
7. **[07 - Plugins](07-plugins/)** - Các tính năng được đóng gói
8. **[08 - Checkpoints](08-checkpoints/)** - Snapshot phiên làm việc
9. **[09 - Tính Nâng Cao](09-advanced-features/)** - Planning, thinking, backgrounds
10. **[10 - CLI](10-cli/)** - Tham chiếu dòng lệnh
## 🔗 Liên Kết
- [Bản tiếng Anh](../README.md)
- [Tài liệu Chính thức Claude Code](https://code.claude.com/docs)
- [GitHub Repository](https://github.com/luongnv89/claude-howto)
## 🤝 Đóng Góp
Xem [CONTRIBUTING.md](../CONTRIBUTING.md) để biết thêm chi tiết.
## 📝 Ghi Chú Dịch Thuật
Xem [TRANSLATION_NOTES.md](TRANSLATION_NOTES.md) để hiểu:
- Glossary thuật ngữ kỹ thuật
- Hướng dẫn phong cách dịch
- Quy tắc dịch code và commands
---
**Bản dịch đang được tiến hành.** Xem [TRANSLATION_QUEUE.md](TRANSLATION_QUEUE.md) để biết tiến độ chi tiết.
**Last Updated:** 2026-04-02
**Language:** Vietnamese (vi-VN)

82
vi/SECURITY.md Normal file
View File

@@ -0,0 +1,82 @@
# Chính Sách Bảo Mật / Security Policy
## Tổng Quan / Overview
Bảo mật của dự án Claude How To là quan trọng đối với chúng tôi. Tài liệu này phác thảo các thực hành bảo mật của chúng và mô tả cách báo cáo các lỗ hổng bảo mật một cách có trách nhiệm.
## Các Phiên Bản Được Hỗ Trợ / Supported Versions
Chúng tôi cung cấp các bản cập nhật bảo mật cho các phiên bản sau:
| Phiên Bản | Trạng Thái | Hỗ Trợ Đến |
|---------|--------|---------------|
| Mới nhất (main) | ✅ Hoạt Động | Hiện tại + 6 tháng |
| Bản phát hành 1.x | ✅ Hoạt Động | Đến phiên bản lớn tiếp theo |
**Lưu ý**: Là một dự án hướng dẫn giáo dục, chúng tôi tập trung vào việc duy trì các thực hành tốt nhất hiện tại và bảo mật tài liệu hơn là hỗ trợ phiên bản truyền thống. Các bản cập nhật được áp dụng trực tiếp vào nhánh chính.
## Thực Hành Bảo Mật / Security Practices
### Bảo Mật Code
1. **Quản Lý Dependency**
- Tất cả dependencies Python được pinned trong `requirements.txt`
- Cập nhật thường xuyên qua dependabot và review thủ công
- Quét bảo mật với Bandit trên mỗi commit
- Pre-commit hooks cho các kiểm tra bảo mật
2. **Chất Lượng Code**
- Linting với Ruff bắt các vấn đề phổ biến
- Kiểm tra kiểu với mypy ngăn các lỗ hổng liên quan đến kiểu
- Pre-commit hooks thực thi các tiêu chuẩn
- Tất cả các thay đổi được review trước khi gộp
3. **Kiểm Soát Truy Cập**
- Bảo vệ nhánh trên nhánh `main`
- Yêu cầu review trước khi gộp
- Các kiểm tra trạng thái phải pass trước khi gộp
- Quyền ghi hạn chế đến repository
### Bảo Mật Tài Liệu
1. **Không Secrets trong Ví Dụ**
- Tất cả API keys trong ví dụ là placeholders
- Credentials không bao giờ được hardcode
- Các file `.env.example` hiển thị các biến được yêu cầu
- Cảnh báo rõ về quản lý secret
2. **Thực Hành Bảo Mật Tốt Nhất**
- Các ví dụ minh họa các mẫu an toàn
- Cảnh báo bảo mật được làm nổi bật trong tài liệu
- Links đến các hướng dẫn bảo mật chính thức
- Xử lý credential được thảo luận trong các phần liên quan
3. **Review Nội Dung**
- Tất cả tài liệu được review cho các vấn đề bảo mật
- Các cân nhắc bảo mật trong hướng dẫn đóng góp
- Xác thực các liên kết và tham khảo bên ngoài
## Báo Cáo Một Lỗ Hổng Bảo Mật / Reporting a Vulnerability
### Vấn Đề Bảo Mật Chúng Tôi Quan Tâm
Chúng tôi đánh giá cao các báo cáo về:
- **Lỗ hổng code** trong scripts hoặc ví dụ
- **Lỗ hổng dependency** trong các gói Python
- **Vấn đề mật mã** trong bất kỳ ví dụ code nào
- **Lỗi Xác Thực/Ủy Quy** trong tài liệu
- **Rủi ro lộ dữ liệu** trong ví dụ cấu hình
- **Lỗ hổng tiêm nhiễm** (SQL, command, v.v.)
### Cách Báo Cáo / How to Report
Vui lòng báo cáo các lỗ hổng bảo mật một cách riêng tư:
- Gửi email đến: security@example.com
- Sử dụng tiêu đề email: [Security] Mô tả ngắn gọn
- Cung cấp đủ chi tiết để chúng tôi tái tạo và xác nhận vấn đề
Chúng tôi sẽ:
- Xác nhận nhận trong vòng 48 giờ
- Cung cấp timeline cho việc sửa
- Thông báo khi bản vá đã được phát hành
- Công khai thừa nhận báo cáo của bạn (nếu bạn muốn)

Some files were not shown because too many files have changed in this diff Show More