درس ۳ از ۵

ب — Course 2: Claude Code in Action (شانزده lecture)

این course همان مفاهیم course اول را روی کار واقعی پیاده می‌کند. ۱۶ lecture به سه گروه تقسیم می‌شوند: setup و basics (۱-۵)، editing و integration (۶-۹) و عمیق شدن در hook ها و SDK (۱۰-۱۶).

Lecture 2.1 — coding assistant چیست؟

عنوان اصلی: What is a coding assistant

هدف یادگیری: تمایز autocomplete (Copilot) ↔ chat assistant (Cursor chat) ↔ agentic assistant (Claude Code).

مفاهیم کلیدی: code completion, chat-based assistance, agentic execution, in-context vs. out-of-context tools.

یک coding assistant روی یکی از سه پله می‌نشیند: autocomplete یک خط را همزمان پیشنهاد می‌دهد؛ chat assistant به سوال درباره‌ی کدی که paste کرده‌اید پاسخ می‌دهد؛ agentic assistant مثل Claude Code action انجام می‌دهد (read، edit، run، commit) برای رسیدن به یک هدف. کلاس agentic چیزی است که task مثل «write tests for the auth module, run them, and fix any failures» را در یک prompt ممکن می‌کند.

اشتباهات رایج

  • استفاده از Claude Code برای کاری که autocomplete حل می‌کند. سراغ Claude Code بروید برای task هایی که چندفایلی هستند یا نیاز به run و verify کد دارند.

Lecture 2.2 — Claude Code در عمل

عنوان اصلی: Claude Code in action

هدف یادگیری: تماشای end-to-end یک feature واقعی.

مفاهیم کلیدی: agentic loop, tool execution, permission prompts, "Accept all" mode, diff approval.

Demo task: «add input validation to the user registration form.» Claude فایل را پیدا می‌کند، diff پیشنهادی نشان می‌دهد، اجازه می‌گیرد، edit انجام می‌دهد، test اجرا می‌کند و گزارش می‌دهد. تا زمانی که session در acceptEdits یا bypassPermissions نباشد، همیشه قبل از ویرایش فایل اجازه می‌گیرد. mode --permission-mode auto از یک classifier استفاده می‌کند که کارهای routine را تایید و کار risky را escalate می‌کند.

اشتباهات رایج

  • approve کردن کور هر diff. چند diff اول هر task را با دقت بخوانید تا مطمئن شوید Claude مسیر درست را گرفته؛ بعد می‌توانید به «Accept all» سوییچ کنید.

Lecture 2.3 — Setup

عنوان اصلی: Setup

هدف یادگیری: authenticate در برابر Pro/Max/Team/Enterprise، Console (API key) یا یک provider third-party.

مفاهیم کلیدی: /login, ANTHROPIC_API_KEY, Bedrock (CLAUDE_CODE_USE_BEDROCK=1), Vertex (CLAUDE_CODE_USE_VERTEX=1), Foundry (CLAUDE_CODE_USE_FOUNDRY=1), forceLoginMethod / forceLoginOrgUUID managed settings.

اولین اجرا /login می‌خواهد. برای Anthropic API، ANTHROPIC_API_KEY را set کنید (Claude Code یک workspace به نام «Claude Code» در Console برای cost tracking می‌سازد). برای enterprise، env var مربوطه را set و credential های cloud را config کنید.

مثال عملی

export ANTHROPIC_API_KEY=sk-ant-...
claude /login

اشتباهات رایج

  • commit کردن API key (هرگز).
  • نصب تیمی بدون قفل کردن managed settings — هر کسی می‌تواند با org/login دلخواه login کند.

Lecture 2.4 — Project setup

عنوان اصلی: Project setup

هدف یادگیری: Bootstrap یک پروژه با /init، تعیین ignore rule ها و افزودن یک CLAUDE.md اولیه.

مفاهیم کلیدی: /init, CLAUDE_CODE_NEW_INIT=1 (interactive multi-phase flow with subagent), .claudeignore, claudeMdExcludes.

از ریشه‌ی پروژه /init بزنید. Claude codebase را تحلیل می‌کند، build system و test framework را تشخیص می‌دهد و یک CLAUDE.md اولیه می‌نویسد. mode تعاملی جدید (CLAUDE_CODE_NEW_INIT=1) می‌پرسد چه artifact هایی setup شود (CLAUDE.md، skills، hooks)، با subagent explore می‌کند و یک پیشنهاد قابل review ارائه می‌دهد.

مثال عملی

/init

اشتباهات رایج

  • در نظر گرفتن /init به‌عنوان فایل نهایی. این یک نقطه‌ی شروع است؛ روی مرور زمان با چیزهایی که Claude نمی‌تواند از کد infer کند (build commands، env vars، quirks) refine کنید.

Lecture 2.5 — افزودن context

عنوان اصلی: Adding context

هدف یادگیری: تغذیه‌ی Claude با context درست: @-references، image، URL، piped data، MCP server.

مفاهیم کلیدی: @filename, drag-and-drop screenshots, /permissions URL allowlist, stdin pipe, MCP tools.

پنج مسیر context: (۱) @path/to/file برای ارجاع، (۲) paste/drag image برای spec بصری، (۳) URL (Claude با WebFetch می‌گیرد)، (۴) cat data.csv | claude -p "..." برای pipe stdin، (۵) MCP tool ها برای کشیدن داده از Notion / Linear / Postgres.

اشتباهات رایج

نقل قول مستقیم: «Reference files with @ instead of describing where code lives. Claude reads the file before responding.» — این روش یک tool call و یک رفت‌وبرگشت context را صرفه‌جویی می‌کند.

Lecture 2.6 — اعمال تغییرات

عنوان اصلی: Making changes

هدف یادگیری: هدایت Claude در ویرایش‌های atomic با verification در هر گام.

مفاهیم کلیدی: Edit tool, Write tool, MultiEdit, diff approval, test-first prompting.

Edit نیاز به یک old_string یکتا دارد تا location دقیق را بیابد. Write فایل را overwrite می‌کند (Claude باید قبلش Read کرده باشد به‌عنوان safety check). بهترین نتیجه وقتی است که به Claude بگویید چگونه تایید کند: «after editing, run npm test and fix anything that fails.»

مثال عملی

refactor src/auth.ts to use async/await instead of callbacks.
after each function, run `npm test -- auth` and confirm it passes
before moving to the next.

اشتباهات رایج

  • skip کردن گام verification. توصیه‌ی Anthropic: «If you can't verify it, don't ship it.»

Lecture 2.7 — Custom commands

عنوان اصلی: Custom commands

هدف یادگیری: ساخت command های قابل استفاده مجدد تیمی به‌صورت skill (یا legacy .claude/commands/*.md).

مفاهیم کلیدی: .claude/commands/<name>.md (legacy), .claude/skills/<name>/SKILL.md (recommended), $ARGUMENTS, argument-hint, disable-model-invocation: true, !`shell` dynamic context.

هر دو شکل دستور /name می‌سازند؛ skill ها توصیه‌ی رسمی هستند چون از پوشه‌ی فایل‌های جانبی پشتیبانی می‌کنند. disable-model-invocation: true را برای action های side-effect (مثل /deploy) استفاده کنید تا Claude نتواند به‌صورت خودکار trigger کند.

مثال عملی

---
name: fix-issue
description: Fix a GitHub issue
disable-model-invocation: true
---
Fix GitHub issue $ARGUMENTS following our coding standards.
1. Read the issue description
2. Understand the requirements
3. Implement the fix
4. Write tests
5. Create a commit

اشتباهات رایج

  • نگذاشتن disable-model-invocation: true روی command با side-effect مثل /deploy، /commit، /send-slack-message. خطر این است که Claude به این نتیجه برسد «کد آماده است» و خودش deploy کند.

Lecture 2.8 — MCP servers با Claude Code

عنوان اصلی: MCP servers with Claude Code

هدف یادگیری: افزودن و استفاده از MCP server ها؛ درک transport و scope.

مفاهیم کلیدی: stdio / HTTP / SSE / WebSocket; claude mcp add, claude mcp list; project vs user vs local scope; MCP registry; mcp__<server>__<tool> matcher syntax.

سه use case پرچم‌دار: خواندن design از Figma، query یک Postgres DB، driving یک browser با Playwright. UI /mcp برای OAuth flow.

مثال عملی

claude mcp add github --transport http --url https://api.githubcopilot.com/mcp/
claude mcp add postgres -- npx @modelcontextprotocol/server-postgres "$DATABASE_URL"
claude mcp list

اشتباهات رایج

  • approve خودکار MCP server های project-scoped (.mcp.json) بدون review. اولین load پروژه permission می‌خواهد — server را قبل از تایید بررسی کنید.

Lecture 2.9 — یکپارچگی با GitHub

عنوان اصلی: GitHub integration

هدف یادگیری: راه‌اندازی @claude در PR و issue؛ انتخاب بین Code Review action و Action workflow.

مفاهیم کلیدی: anthropics/claude-code-action@v1, @claude mention, prompt: و claude_args:, ANTHROPIC_API_KEY secret, GitHub Code Review (auto on every PR).

برای install، /install-github-app بزنید. Action نسخه‌ی v1 خودش تشخیص می‌دهد که تعاملی اجرا شود (پاسخ به @claude در comment ها) یا automation mode (اجرای فوری با prompt).

Gotcha مهم — تغییرات breaking در v1: نسبت به v0: - mode حذف شده است (auto-detect جایگزین شده) - direct_prompt به prompt تبدیل شده - max_turns به داخل claude_args رفته است

مثال عملی

name: Code Review
on:
  pull_request:
    types: [opened, synchronize]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: "Review this PR for code quality, correctness, and security."
          claude_args: "--max-turns 5"

اشتباهات رایج

  • نگذاشتن --max-turns — runaway iteration می‌تواند هزینه‌ی API را بالا ببرد.
  • اجرای موازی چندین run روی همان PR؛ concurrency: اضافه کنید.

Lecture 2.10 — Hooks: مقدمه

عنوان اصلی: Hooks (intro)

هدف یادگیری: درک case برای automation deterministic حول رویدادهای ابزار.

مفاهیم کلیدی: advisory (CLAUDE.md, skill instructions) vs. deterministic (hook).

نقل قول رسمی: «Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.» استفاده برای کارهایی که must-always-happen هستند: format on save، block write به .git/، audit-log هر فراخوانی Bash.

Lecture 2.11 — Hooks: تعریف schema

عنوان اصلی: Hooks: define

هدف یادگیری: خواندن schema: event → matcher → handler با type, command, if, timeout.

مفاهیم کلیدی: نام رویدادها، matcher regex (با کاراکترهای امن به‌عنوان exact match)، handler types (command / http / mcp_tool / prompt / agent).

مثال عملی

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate.sh",
            "if": "Bash(git *)",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

اشتباهات رایج

  • matcher هایی که فقط letter/digit/_/| دارند exact match هستند؛ هر کاراکتر دیگری آنها را تبدیل به JS regex می‌کند. ^Notebook regex است؛ Edit|Write exact alternation است.

Lecture 2.12 — Hooks: پیاده‌سازی

عنوان اصلی: Hooks: implement

هدف یادگیری: نوشتن یک hook script در bash که JSON از stdin می‌خواند و JSON decision می‌نویسد.

مفاهیم کلیدی: stdin JSON (session_id, cwd, tool_name, tool_input), jq parsing, permissionDecision: "allow|deny|ask", exit code 2 = blocking.

مثال عملی (block rm -rf)

#!/bin/bash
COMMAND=$(jq -r '.tool_input.command' < /dev/stdin)
if echo "$COMMAND" | grep -q 'rm -rf'; then
  jq -n '{
    hookSpecificOutput: {
      hookEventName: "PreToolUse",
      permissionDecision: "deny",
      permissionDecisionReason: "Destructive command blocked"
    }
  }'
  exit 0
fi
exit 0

اشتباهات رایج

  • چاپ هر چیزی غیر از JSON روی stdout وقتی structured output می‌خواهید. یک echo "Starting..." اضافی JSON parse را خراب می‌کند.

Lecture 2.13 — Hooks: gotcha ها

عنوان اصلی: Hooks: gotchas

هدف یادگیری: پرهیز از foot-gun های رایج.

مفاهیم کلیدی: PostToolUse نمی‌تواند block کند (already executed)؛ JSON parse error؛ shell profile noise؛ matcher بیش‌از حد permissive .*؛ managed-settings disableAllHooks.

PostToolUse فقط observability است نه enforcement — برای block باید از PreToolUse استفاده کنید. به‌جای regex وسیع، if: "Bash(git *)" استفاده کنید تا scope کنید. SessionStart hook روی هر session اجرا می‌شود — سریع نگهش دارید.

اشتباهات رایج

  • matcher .* که هر چیزی را trigger می‌کند.
  • ارجاع به env var در HTTP header بدون whitelist در allowedEnvVars.

Lecture 2.14 — Hooks مفید (۱): Auto-format on edit

عنوان اصلی: Hooks: useful #1 — Auto-format on edit

مثال عملی

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          { "type": "command", "command": "prettier --write \"$CLAUDE_PROJECT_DIR\"/$(jq -r '.tool_input.file_path')" }
        ]
      }
    ]
  }
}

اشتباهات رایج

  • استفاده از path نسبی به‌جای $CLAUDE_PROJECT_DIR — تا زمانی که cwd عوض شود hook خراب می‌شود.

Lecture 2.15 — Hooks مفید (۲): SessionStart context

عنوان اصلی: Hooks: useful #2 — Inject SessionStart context (git status, branch)

مثال عملی

#!/bin/bash
BRANCH=$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "unknown")
MODIFIED=$(git status -s | wc -l)
jq -n \
  --arg branch "$BRANCH" \
  --arg modified "$MODIFIED" \
  '{
    hookSpecificOutput: {
      hookEventName: "SessionStart",
      additionalContext: "Current branch: \($branch)\nUncommitted changes: \($modified) files"
    }
  }'

اشتباهات رایج

  • نوشتن additionalContext بزرگ‌تر از سقف ۱۰٬۰۰۰ کاراکتر — بقیه truncate می‌شود.

Lecture 2.16 — Claude Agent SDK + Quiz

عنوان اصلی: Claude Code SDK + Quiz

هدف یادگیری: ساخت یک agent برنامه‌نویسی‌شده در Python یا TypeScript با Claude Agent SDK (نام قبلی: Claude Code SDK).

مفاهیم کلیدی: query() async iterator, ClaudeAgentOptions (allowed_tools, max_turns, model, permission_mode, hooks, mcp_servers, agents, resume), ClaudeSDKClient, HookMatcher / HookCallback, AgentDefinition, session resume.

Gotcha بسیار مهم — rename: «The Claude Code SDK has been renamed to the Claude Agent SDK.» package جدید: claude-agent-sdk (Python) / @anthropic-ai/claude-agent-sdk (TypeScript). اگر کد قدیمی با claude-code-sdk دارید، migrate کنید.

این SDK همان agent loop، tools و context management ابزار CLI را به‌صورت یک library در Python یا TypeScript عرضه می‌کند. tool های built-in (Read, Write, Edit, Bash, Glob, Grep, WebSearch, WebFetch, Monitor, AskUserQuestion) خودبه‌خود کار می‌کنند. hook ها به Python callable ها تبدیل می‌شوند؛ MCP server ها inline config می‌شوند؛ subagent ها از طریق AgentDefinition declare می‌شوند. session ها به‌صورت JSONL روی filesystem نگه داشته می‌شوند و با session_id capture شده می‌توان resume کرد.

مثال عملی — Python

import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    async for message in query(
        prompt="Find and fix the bug in auth.py",
        options=ClaudeAgentOptions(allowed_tools=["Read", "Edit", "Bash"]),
    ):
        print(message)

asyncio.run(main())

مثال عملی — TypeScript

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Find and fix the bug in auth.ts",
  options: { allowedTools: ["Read", "Edit", "Bash"] }
})) {
  console.log(message);
}

نصب

pip install claude-agent-sdk
# یا
npm install @anthropic-ai/claude-agent-sdk

اشتباهات رایج

  • استفاده از login claude.ai یا rate limit مشترک برای end user های نهایی روی SDK — Anthropic این را برای partner ها ممنوع کرده است. باید از API key (Anthropic / Bedrock / Vertex / Foundry) استفاده کنید.
  • استفاده از مدل‌های جدید (Opus 4.7 به بالا، از جمله Opus 4.8) با SDK نسخه‌ی قدیم؛ برای Opus 4.7 حداقل v0.2.111 لازم بود و برای مدل‌های جدیدتر همیشه آخرین نسخه‌ی SDK را نصب کنید.

Quiz coverage

سوالات quiz روی این موارد متمرکز است: لیست tool های built-in، رویدادهای hook، چهار location config برای CLAUDE.md، تفاوت subagent با skill، و breaking changes نسخه‌ی v1 GitHub Action (mode حذف، direct_prompt → prompt، max_turns → claude_args).