devHọc Dev

Week 1 - Day 3: Effective Workflows: Plan, TDD, Subagents, Hooks, Skills, MCP, CI

Week 1 – Day 3

This lesson combines 4 topics: Explore → plan → implement → test → review and TDD with Claude, Subagents and git worktrees for running in parallel, Extending Claude Code with hooks, skills and MCP, Headless mode and CI with GitHub Actions.

Learning Objectives

  • Apply the 5-step workflow explore → plan → implement → test → review to a real task
  • Use plan mode to approve a plan before Claude edits code
  • Do TDD with Claude: write tests first, confirm they fail, and only then implement
  • Understand what problems subagents solve (context isolation, tool restrictions) and write a custom subagent
  • Run several sessions in parallel safely with git worktrees (claude --worktree)
  • Distinguish CLAUDE.md, skills, hooks, MCP servers and subagents: which one to use for what
  • Write a PostToolUse hook that auto-formats and a PreToolUse hook that blocks edits to sensitive files
  • Create a skill for a recurring team workflow
  • Add an MCP server and understand the security risks that come with it
  • Run Claude Code non-interactively (claude -p) in scripts and CI with JSON output
  • Set up Claude Code GitHub Actions and know the points to control regarding permissions and cost

Part 1: Explore → plan → implement → test → review

1. Why you shouldn't just say "go do it"

Handing over a large task in one sentence and letting Claude run on its own often produces code that runs but rests on wrong assumptions, touches unrelated files, or correctly solves a different problem. The cause is not a weak model but a missing step to agree on understanding before writing code. The 5-step workflow fills exactly that gap:

┌──────────┐┌──────────┐┌──────────────┐┌──────────┐┌──────────┐│Explore│──▶│Plan│──▶│Implement│──▶│Test│──▶│Review││read,││human││smallsteps,││runreal││diff,││noedits││approves││commitoften││checks││2ndlook│└──────────┘└──────────┘└──────────────┘└──────────┘└──────────┘▲│└────────────────wrongassumptionfound:goback──────────────┘
StepPurposeSample prompt
ExploreClaude understands the existing code, you check that understanding"Read src/cart and src/pricing. Explain how the cart total is calculated today. Don't change anything yet."
PlanAgree on approach, scope, risks"Propose a plan to add membership-tier discounts: which files change, which tests to add, what risks."
ImplementWrite code according to the approved plan"Do steps 1 and 2 of the plan. Stop after step 2."
TestVerify with real tools"Run pnpm test -- pricing and pnpm typecheck, fix until they pass."
ReviewLook again with fresh eyes/review, or a new session: "Review the diff against main, focusing on edge cases."

Not every task needs all 5 steps. Fixing a typo or renaming a variable, just do it. A suggested rule: if you can't describe the expected diff in one sentence, start with a plan.

2. Plan mode

Plan mode lets Claude read files and run read-only commands to explore, but not edit source (per the docs, as of 11/2026). Ways to enter it:

  • Press Shift+Tab until the status bar shows Plan.
  • Type /plan add membership-tier discounts to enter plan mode and start right away with that description.
  • Start with claude --permission-mode plan.

When the plan is ready, Claude offers choices: approve and run in auto mode, approve and manually approve each edit, or keep planning. Press Ctrl+G to open the plan in your editor and edit it directly before Claude acts.

A good plan should include:

  • The list of files to change and why
  • The order of steps, each one verifiable
  • Tests to add or modify
  • The assumptions it relies on (so you can reject them if wrong)
  • What it will not do this time

Read the plan the way you read a colleague's design doc: fixing a wrong assumption at this step is far cheaper than fixing 600 lines of code later.

3. TDD with Claude

TDD is especially well suited to Claude because tests are an automated verification criterion: Claude can loop write → run → fix without you watching.

Process:

  1. Write the tests first, and say clearly that you are doing TDD:
    We're doing TDD. Write Vitest tests for the function applyMemberDiscount(cart, tier)
    according to the spec in docs/pricing.md section 4. Don't write the implementation
    yet, and don't create a mock implementation. Run the tests and confirm they FAIL for
    the right reason (the function doesn't exist / isn't correct yet), not because of a
    syntax error in the tests.
    
  2. You review the tests: do they express the spec correctly? Do they cover edge cases (empty cart, nonexistent tier, rounding of amounts)?
  3. Commit the tests so you have a fixed reference point.
  4. Implement:
    Write the implementation so the tests pass. Don't modify the test files. Run the
    tests after each change until they all pass, then run pnpm typecheck.
    
  5. Review the implementation and refactor if needed; the tests must still pass.

The sentence "don't modify the test files" is very important. When stuck, the model tends to "make the tests pass" by editing the tests or writing test-specific code (hard-coding the expected values). Committing the tests first lets you detect immediately if they were touched.

4. Habits that keep the workflow smooth

HabitBenefit
Commit after each green stepA return point more reliable than checkpoints
One session per task; /clear when switching tasksClean context, less noise
Say "stop after step N"You review piece by piece instead of one giant diff
Give Claude screenshots or mockups when working on UIA clear, comparable target
Correct course early: press Esc to stop Claude mid-wayDon't let a wrong direction run for long
Review with a new session or a subagentNot influenced by the assumptions of the session that wrote the code

Part 2: Subagents and git worktrees

1. What problems subagents solve

A subagent is a secondary Claude session that runs with its own context window, its own system prompt and its own set of tools. The main session delegates the task, the subagent does it, and only a summary comes back.

MainsessioncontextSubagentcontext┌──────────────────────────┐┌──────────────────────────┐│yourtask,plan,edits│──delegate─▶│reads40files,greps,││││runssearches││+shortsummary(2Ktok)│◀─summary───│(80Ktokensstayhere)│└──────────────────────────┘└──────────────────────────┘

Benefits:

  • Keeps the main context clean: token-heavy searches don't dilute the main session.
  • Restricts permissions: a review subagent only needs Read, Grep and Glob, not Edit or Bash.
  • Specialization: a dedicated system prompt for a reviewer, a test writer, a bug hunter.
  • Its own model choice: simple searches can use a faster, cheaper model.

Claude Code ships with some built-in subagents such as Explore (searching and analyzing the codebase, read-only), Plan (gathering context in plan mode) and general-purpose.

2. Writing a custom subagent

A subagent is a markdown file with YAML frontmatter, placed in .claude/agents/ (project, can be committed) or ~/.claude/agents/ (personal). Only name and description are required.

---
name: security-reviewer
description: Review the current diff for security vulnerabilities. Use after completing a change that touches auth, user input or database queries.
tools: Read, Glob, Grep
model: sonnet
---

You are the security reviewer for the acme-shop project.

When invoked:
1. Identify the files changed relative to the main branch.
2. For each change, check: injection (SQL, command), authz (the user ID must come
   from req.session, not from the body), secrets leaked in logs, unvalidated input.
3. Compare with sibling routes in src/routes to detect inconsistencies.

Report: file:line, severity (high/medium/low), reason, suggested fix.
Do not modify code.

Notes:

  • description decides when Claude delegates to the subagent on its own; describe the use cases clearly.
  • If tools is omitted, the subagent inherits all tools; list them explicitly to apply the principle of least privilege.
  • model accepts sonnet, opus, haiku, fable, a full model ID, or inherit.
  • Invoke explicitly: "Use the security-reviewer subagent to review the change I just made."

3. Running in parallel with git worktrees

Two Claude Code sessions editing the same directory will step on each other. A git worktree gives each session its own checkout, sharing the same git history.

Per the Worktrees docs (as of 11/2026):

# Terminal 1: work on a feature
claude --worktree feature-member-discount

# Terminal 2: fix a bug in parallel
claude --worktree fix-shipping-fee
  • The worktree is created at .claude/worktrees/<name>/ inside the repo, on a new branch worktree-<name>. You should add .claude/worktrees/ to .gitignore.
  • By default the worktree branches off the default branch on the remote, not the current HEAD; set worktree.baseRef to "head" if you want to branch off your work in progress.
  • A worktree is a fresh checkout: you must reinstall dependencies; gitignored files such as .env are not present (they can be declared in .worktreeinclude).
  • On exit, a clean worktree is removed automatically; for a worktree with changes, Claude asks whether to keep or delete it.
  • To manage it yourself: git worktree add ../acme-shop-feature -b feature-x, then cd into it and run claude.

Subagents can also run in their own worktree with isolation: worktree in the frontmatter, which fits when several subagents edit code at the same time.

When parallelism pays off: tasks that are independent in terms of files (feature A in src/cart, bug B in src/shipping). When it doesn't: tasks that touch the same files or depend on each other; you'll spend more time resolving conflicts than you save.


Part 3: Extending Claude Code: hooks, skills, MCP

1. Choosing the right mechanism

MechanismWhat it isUse whenEnforced?
CLAUDE.mdInstructions loaded every sessionConventions, commands, architectureNo
Permission rulesAllow/ask/deny per toolRestricting permissionsYes
HooksShell commands run at lifecycle pointsThings that must always happen: formatting, blocking, notificationsYes
SkillsBundle of instructions + supporting files, invoked with /name or used by Claude on its ownRecurring workflows: release, review, deployNo
SubagentsSecondary sessions with their own context and toolsContext-heavy tasks, tasks needing restricted permissionsPartly (tool restrictions)
MCP serversConnect external tools and dataIssue tracker, database, internal docs, browserNo

The deciding question: "Must this happen 100% of the time, or should it just happen?" If it must happen, use a hook or a permission. If it should happen, use CLAUDE.md or a skill.

2. Hooks

A hook is a shell command that Claude Code runs at specific events. Some of the events (per the Hooks guide, as of 11/2026):

EventWhen it runs
SessionStartA session starts or resumes
UserPromptSubmitWhen a prompt is submitted, before Claude processes it
PreToolUseBefore a tool runs; can block
PermissionRequestWhen a tool needs a permission decision
PostToolUseAfter a tool runs successfully
NotificationWhen Claude Code sends a notification (e.g. it is waiting for you)
StopWhen Claude finishes responding
SubagentStopWhen a subagent finishes

Example 1: auto-format after every file edit (.claude/settings.json, following the sample in the docs):

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | xargs -I{} npx prettier --write \"{}\""
          }
        ]
      }
    ]
  }
}

The hook receives the event data as JSON via stdin; here jq extracts the path of the file just edited and passes it to Prettier (-I{} and the double quotes keep paths containing spaces correct).

Example 2: blocking edits to sensitive files. The script .claude/hooks/protect-files.sh:

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

PROTECTED_PATTERNS=(".env" "pnpm-lock.yaml" ".git/" "prisma/migrations/")

for pattern in "${PROTECTED_PATTERNS[@]}"; do
  if [[ "$FILE_PATH" == *"$pattern"* ]]; then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0

Registration:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
          }
        ]
      }
    ]
  }
}

Note the scope: this hook only runs for the Edit|Write tools; Bash commands such as sed -i, a > redirect or a script that writes files itself will not go through it. For files that need absolute protection, the main barrier is an Edit(...) deny rule (which also covers the file commands Claude Code recognizes inside Bash); the hook is an extra layer, for example to give Claude a clear explanation of why.

Exit code conventions to remember:

  • Exit 2: blocks the action; stderr content is sent to Claude as feedback so it can adjust.
  • Exit 0 from PreToolUse: the action proceeds into the normal permission flow. Exit 0 does not mean auto-approval.
  • Other codes (without valid JSON): for most events, the action still proceeds.

Security note: a hook is code running on your machine with your privileges. Hooks in an unfamiliar repo's .claude/settings.json only run after you trust the folder; with claude -p there is no trust dialog, so be careful when running headless on a repo that isn't yours (Part 4).

3. Skills

A skill is a directory containing SKILL.md, placed at .claude/skills/<name>/SKILL.md (project) or ~/.claude/skills/<name>/SKILL.md (personal). A skill is invoked with /name, or Claude loads it on its own when the description matches the task at hand. Old-style custom commands in .claude/commands/ have been merged into skills and still work.

Example release skill for acme-shop:

---
name: release-notes
description: Draft release notes from the commits since the latest tag. Use when preparing a release.
disable-model-invocation: true
---

Draft release notes for version $ARGUMENTS:

1. Find the latest tag with `git describe --tags --abbrev=0`.
2. List the commits from that tag to HEAD with `git log --oneline <tag>..HEAD`.
3. Group them into: Features, Bug fixes, Maintenance. Skip commits that only change CI.
4. Each line: a description for end users, no internal jargon.
5. Write it at the top of CHANGELOG.md, following the format of the existing entries.

disable-model-invocation: true means Claude does not trigger this skill on its own; it only runs when you type /release-notes 2.4.0. Use it for workflows with side effects (deploy, commit, publish).

Skills help standardize how the team works with Claude: instead of everyone writing their own different release prompt, the whole team uses one skill that is reviewed through PRs.

4. MCP servers

Model Context Protocol (MCP) is an open standard for connecting AI to external tools and data: issue trackers, databases, design documents, browsers.

Adding a server (per the MCP docs, as of 11/2026):

# Remote HTTP server
claude mcp add --transport http docs-search https://mcp.example.com/mcp

# Local stdio server; the -- separates Claude's options from the server command
claude mcp add --transport stdio --env DB_URL=postgres://readonly@localhost/acme local-db -- npx -y some-postgres-mcp-server
ScopeStored inShared
local (default)~/.claude.jsonNo
project.mcp.json at the repo rootYes, via git
user~/.claude.jsonNo, but used for all projects

Choose the scope with --scope (or -s). View and manage connections with /mcp.

Security risks (covered in depth on Day 7):

  • An MCP server is third-party code or a third-party service with access to your data. Only use servers you trust.
  • Servers that fetch external content (web, issues, email) can bring prompt injection into the context.
  • In interactive sessions, Claude Code asks before using servers declared in the project's .mcp.json. With claude -p and the Agent SDK (when settingSources includes project, which is the default), there is no such dialog, so the servers are loaded right away.
  • Each MCP server adds tool names to the context; too many servers waste context and make Claude worse at picking tools. Enable what you need, disable what you don't use.

Part 4: Headless mode and CI

1. claude -p: Claude Code as a Unix command

The -p (or --print) flag runs non-interactively: it takes a prompt, does the work, prints the result, and exits with exit code 0 on success (per the Headless docs, as of 11/2026).

# Quick question
claude -p "What does the auth module do?"

# Pipe data in
cat build-error.txt | claude -p "briefly explain the root cause of this build error" > explain.txt

# Allow some tools without asking
claude -p "Run the test suite and fix the failing tests" --allowedTools "Bash,Read,Edit"

# Set the base permission mode
claude -p "Apply lint fixes" --permission-mode acceptEdits

Commonly used flags:

FlagEffect
--output-format text / json / stream-jsonOutput format; json includes result, session_id, total_cost_usd...
--json-schema '<schema>'With --output-format json, output following the schema is in the structured_output field
--allowedTools "..."List of tools usable without asking, in permission rule syntax
--permission-mode <mode>acceptEdits, dontAsk, auto...
--continue, --resume <id>Continue a previous conversation
--append-system-prompt "..."Append instructions to the default system prompt
--max-turns <n>Limit the number of turns, preventing endless runs
--bareSkip auto-discovery of hooks, skills, subagents, plugins, MCP, auto memory, CLAUDE.md; recommended for CI and scripts

Example script that reviews commits with structured output:

#!/bin/bash
set -euo pipefail

git diff origin/main...HEAD | claude --bare -p \
  "You are a reviewer. List the correctness and security issues in this diff." \
  --output-format json \
  --json-schema '{"type":"object","properties":{"issues":{"type":"array","items":{"type":"object","properties":{"file":{"type":"string"},"severity":{"type":"string","enum":["high","medium","low"]},"message":{"type":"string"}},"required":["file","severity","message"]}}},"required":["issues"]}' \
  | jq '.structured_output.issues'

Notes from the docs:

  • If Claude cannot produce valid output, structured_output is absent; the script must check before using it.
  • --bare does not read OAuth or the keychain; it needs ANTHROPIC_API_KEY in the environment (or Bedrock, Google Cloud or Foundry credentials).
  • Without --bare, claude -p still runs the hooks in .claude/settings.json and connects to the servers in the project's .mcp.json without asking for trust. When running on a repo that isn't yours, use --bare or --setting-sources user.
  • With --allowedTools, mind the space before *: Bash(git diff *) allows git diff ..., whereas Bash(git diff*) also matches git diff-index.

2. Claude Code GitHub Actions

Claude Code GitHub Actions runs Claude Code in your repo's workflows. Two modes:

  • Interactive: no prompt input; Claude responds when someone mentions @claude in an issue or PR comment.
  • Automation: has a prompt input; runs on events (PR opened, cron schedule...).

Quick setup: run /install-github-app in Claude Code (requires a logged-in GitHub CLI and repo admin rights). Manual setup: install the Claude GitHub App, add the ANTHROPIC_API_KEY secret, copy the workflow.

A workflow that responds to @claude (following the sample in the docs, as of 11/2026):

name: Claude Code
on:
  issue_comment:
    types: [created]
  pull_request_review_comment:
    types: [created]
jobs:
  claude:
    if: contains(github.event.comment.body, '@claude')
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
      issues: write
      id-token: write
      actions: read
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 1
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          claude_args: "--max-turns 10"

After merging the workflow, comment on a PR:

@claude the checkout.spec.ts test is failing on CI, find the cause and propose a fix

Controls you need:

RiskMitigation
API key leakStore it only in GitHub Secrets; never commit it
Outsiders triggering runs that cost moneyBy default the action only runs when the triggering user has write access; don't widen allowed_non_write_users unless needed
Bots triggering each other in a loopBy default the action rejects bot actors, unless listed in allowed_bots
Runs that take too long or cost too much--max-turns in claude_args, timeout-minutes for the job, GitHub concurrency
Overly broad permissionsGrant only the permissions needed; a review workflow only needs read for contents
Code pushed by Claude skipping reviewRequire PR review just like code written by people
Issue/PR content containing prompt injectionDon't grant dangerous tools to workflows that respond to public content (Day 7)

3. What to use when in CI

NeedChoice
Automatically review every PR without writing your own workflowThe built-in Code Review
Respond to @claude, turn issues into PRsanthropics/claude-code-action@v1
A check step in an existing pipeline (typo linting, log analysis)claude --bare -p ... --output-format json
Custom agent logic, running outside GitHubAgent SDK (Day 6)

Review Questions

  1. Why should there be a plan step before implementing a large task? What does a good plan include?

    Show answer

    The most expensive mistake is a wrong assumption: Claude correctly solves a different problem or touches unrelated files. The plan step surfaces the assumptions so you can reject them early, when fixing them costs a few lines of text instead of hundreds of lines of code. A good plan has: the files to change and why, verifiable steps, tests to add, the assumptions it relies on, and what it will not do this time.

  2. In TDD with Claude, why must you confirm the tests fail before implementing, and why say "don't modify the test files"?

    Show answer

    Tests failing for the right reason prove that they really check the new behavior; tests that pass from the start may be empty or check the wrong thing. "Don't modify the test files" blocks the tendency to make tests pass by changing the expected values or hard-coding results. Committing the tests before implementing lets you detect immediately if they were touched.

  3. How does a subagent help keep the main session's context clean?

    Show answer

    A subagent runs in its own context window. Every file it reads and every search result stays in its context; only a short summary comes back to the main session. The main session is therefore not flooded with tens of thousands of tokens of content that was only needed to answer one question.

  4. Write the frontmatter for a subagent that may only read code to find where a function is called, using a fast model.

    Show answer

    Example: name: call-finder, description: Find every place a function or symbol is called in the repo. Use when you need to assess the impact of changing a signature., tools: Read, Glob, Grep, model: haiku. Key points: the description states clearly when to use it, tools are limited to reading, and a small model because the task is simple.

  5. What is the problem with two Claude Code sessions running in the same repo directory? How does claude --worktree solve it?

    Show answer

    Two sessions editing the same working tree overwrite each other's changes, one session's tests run against the other's half-finished code, and git status gets mixed up. claude --worktree <name> creates a separate git worktree at .claude/worktrees/<name>/ on a new branch, sharing git history but with independent files. Note that you must reinstall dependencies, and gitignored files such as .env are not present.

  6. "Every TypeScript file must be formatted with Prettier after editing." Should this rule go in CLAUDE.md or a hook? Why?

    Show answer

    A PostToolUse hook with the matcher Edit|Write. This must happen 100% of the time and can be fully automated with a single command. CLAUDE.md is only an instruction, which Claude may forget or ignore; a hook runs reliably and costs no tokens for Claude to remember to run Prettier.

  7. A PreToolUse hook exits 0. Is the tool automatically allowed?

    Show answer

    No. Exit 0 from PreToolUse only means the hook does not block; the tool call still goes through the normal permission flow (rules, mode). To block, exit 2 and write the reason to stderr. For finer-grained control, return structured JSON as described in the hooks reference.

  8. When should you set disable-model-invocation: true on a skill?

    Show answer

    When the skill has side effects you don't want Claude to trigger on its own based on the description: deploy, commit, publish, send notifications, create a release. Such a skill only runs when the user types /name. A skill that only provides knowledge or conventions (e.g. how to write a migration) should be left for Claude to load automatically when appropriate.

  9. Distinguish the local, project and user scopes when adding an MCP server. Which scope should a server accessing the production database use?

    Show answer

    local (default): only the current project, only you, stored in ~/.claude.json. project: stored in .mcp.json in the repo, shared via git. user: all your projects, stored in ~/.claude.json. A server accessing the production database should not be committed to .mcp.json for the whole team; if you really need it, use local, a read-only account, and think carefully about whether an agent should have access to production at all.

  10. Why do the docs recommend --bare for CI?

Show answer

Without --bare, claude -p auto-discovers and loads hooks, skills, subagents, plugins, MCP servers, auto memory and CLAUDE.md from the directory and ~/.claude, just like an interactive session. On CI that makes the results depend on the machine running them, and on an untrusted repo the repo's hooks and MCP servers run without going through the trust dialog. --bare gives reproducible results; any needed context is passed explicitly via flags.

  1. A script uses claude -p ... --output-format json --json-schema ... and then reads .structured_output. What case must it handle?
Show answer

The case where structured_output is absent, for example when Claude refuses the request or the run ends without producing valid output. The script must check that the field is present before using it, check the exit code, and decide whether to fail the pipeline or skip.

  1. List 4 controls to put in place when enabling Claude Code GitHub Actions for your team's repo.
Show answer

Store the API key in GitHub Secrets; keep the default that only users with write access can trigger it; limit --max-turns and timeout-minutes; grant minimal permissions per workflow; review PRs created by Claude like code written by people; don't grant dangerous tools to workflows that respond to public content, since they can be hit by prompt injection.

  1. When does running 3 sessions in parallel with worktrees actually slow you down?
Show answer

When the tasks touch the same files or depend on each other: you have to resolve conflicts and rebase, and one session's results break the other's assumptions. Also, you are still the one reviewing all 3 diffs; if your review capacity is the bottleneck, more sessions only add to the queue. Parallelism pays off for tasks that are independent in terms of files and have automated verification criteria.

Hands-on Exercises

Exercise 1: The 5-step workflow

Pick a small real feature in your project (or acme-shop: add membership-tier discounts). Go through all 5 steps: explore in plan mode, edit the plan with Ctrl+G, implement step by step with commits, run the tests, review with /review.

Expected output: the edited plan; the list of commits; notes on which wrong assumptions were caught at the plan step.

Exercise 2: TDD

Do TDD for a pure function (e.g. formatVnd(amount: number): string handling negative numbers, large numbers, rounding). Write the tests first, commit, then have Claude implement with the constraint "don't modify the test files".

Expected output: separate test and implementation commits; git diff <commit-test> -- <file test> is empty.

Exercise 3: Review subagent

Create the security-reviewer subagent from the sample in Part 2, adapted to your project. Deliberately write a route that takes the user ID from the body, and ask the subagent to review it.

Expected output: the subagent detects the authz bug and points to a sibling route that does it correctly; if it doesn't, edit the description and system prompt and run it again.

Exercise 4: Two hooks

Add a post-edit format hook and a hook that blocks lockfile edits to a test repo. Ask Claude to edit a .ts file and to edit pnpm-lock.yaml.

Expected output: the .ts file gets formatted; the lockfile edit is blocked with the message from stderr; a note on how Claude changed course after being blocked.

Exercise 5: A skill for the team

Write a skill for a recurring workflow of your team (writing a migration, preparing a PR, updating the changelog). Set disable-model-invocation appropriately.

Expected output: a SKILL.md under 40 lines; 2 trial runs; notes on adjustments after the first run.

Exercise 6: Headless in a script

Write a script scripts/review-diff.sh that uses claude --bare -p with --output-format json and --json-schema to list issues in the diff against main. The script must exit 1 if there are high severity issues, and handle the case where structured_output is absent.

Expected output: a working script; tried on a diff with an obvious bug and on a clean diff.

Exercise 7 (optional): GitHub Actions

On a personal repo, install Claude Code GitHub Actions. Open an issue describing a small bug and comment @claude asking for a fix.

Expected output: a PR created by Claude; notes on cost (check usage in the Console) and run time; the permissions and --max-turns settings you chose.

References


Next lesson →