Getting Started With Claude Code and Managing Context: Install, Writing CLAUDE.md and "Trim Until You Can't", Permission Modes, Plan Mode's "Explore, Then Plan, Then Write", /clear /compact /rewind, Giving Claude a Verifiable Check
Install Claude Code, write the first CLAUDE.md for your own project, learn Plan Mode's explore-then-plan flow, manage context with /clear /compact /rewind, and give Claude a check it can run on its own.
Today's Goals
- Install Claude Code and explain what belongs in CLAUDE.md and what doesn't
- Walk through explore, plan, and implement using Plan Mode, and switch to the right permission mode
- Manage context in a session with /clear /compact /rewind, and give Claude a verifiable check
For two days you have been talking to the teammate. Today it starts doing things: reading your files, running your commands, editing your code. A teammate with hands needs an even clearer briefing — and an onboarding handbook. Once you have read this and finished the lab, scroll back up and tick off the three goals.
Plain-Language Walkthrough
Install and first conversation: Claude Code is a teammate with hands
Claude in a chat window is like a consultant advising you through glass: you paste code in, it pastes suggestions back, and all the copying and pasting is on you. Claude Code brings that consultant into your terminal — it can ls for itself, cat for itself, edit files, run tests, read the error output, and try again. You stop being the copy-paste middleman and become the person who briefs the task and reviews the result.
Installing takes one command. Use the official installer on macOS / Linux / WSL, or the PowerShell equivalent on Windows; Homebrew and npm also work:
# macOS / Linux / WSL (recommended; self-updating)
curl -fsSL https://claude.ai/install.sh | bash
# or
brew install --cask claude-code
npm install -g @anthropic-ai/claude-code # needs Node 22+
# verify
claude --version
claude doctor # checks the health of the install and configurationThen go into any project directory and type claude. The first run asks you to log in (a Pro / Max / Team account, or ANTHROPIC_API_KEY set), after which you land in a conversation. Do not rush into changes — ask the questions you would ask a new colleague. How do you run the tests here? How is logging done? Which files do I touch to add a new endpoint? You will watch it go dig through files itself, read package.json, grep for keywords, and then answer with file paths. That is the first meaning of "with hands": it does the exploring, you do not have to feed it first.
The second meaning waits until it starts editing code — at which point two questions arrive immediately. How would it know our project's conventions? Does it have to ask me at every single step? The next two sections answer those in turn.
CLAUDE.md is the onboarding handbook: what to write, what not to, and trim until you cannot
On a new colleague's first day you do not narrate the entire codebase; you hand them one page: how to start the server, how to run the tests, which idioms we avoid, what format commit messages take. That page is CLAUDE.md — a Markdown file in the project root that Claude Code reads at the start of every session. It is the D1 business card in Claude Code form, except the card now comes from the project rather than from the product.
Let Claude draft it first: run /init in the project and it scans the codebase and produces a first pass covering build commands, how tests run, and directory conventions. That draft is the starting point, not the destination, because it will contain plenty of things Claude could have worked out by reading the code. What comes next is today's most important move — trim until you cannot trim any further. Ask every line the same question: if I delete this line, will Claude make a mistake? If not, delete it. The criteria:
| Keep | Delete |
|---|---|
Commands Claude cannot guess (pnpm test:db needs docker up first) | Script names visible in package.json |
| Style that departs from the default habit (we do not use default exports) | Ordinary idioms of the language itself |
| How to run tests and which part to run (single file only, never the whole suite) | File-by-file descriptions of what each does |
| Repository etiquette (branch naming, commit message format) | Filler like "write clean, maintainable code" |
| Project-specific architectural decisions and the reasons for them | Things that change often (this sprint's goals) |
| Environment quirks (a particular variable must be set) | Long stretches of API documentation (link to it) |
Why be this strict? Because CLAUDE.md enters the context window in full on every session — it is a fixed cost you pay on every request, and the longer it gets, the less it works: pile on rules and the few that matter get drowned, which the official documentation puts as a bloated CLAUDE.md making Claude ignore your real instructions. The rule of thumb is under 200 lines. If Claude keeps disobeying one rule, the first reaction should not be bold text but a look at whether the file has grown too long.
A few details about placement. Project level goes in ./CLAUDE.md or ./.claude/CLAUDE.md, travels with git, and is shared by the whole team; personal preferences go in ~/.claude/CLAUDE.md and apply to all your projects; anything that is yours alone and should not be committed goes in ./CLAUDE.local.md with an entry in .gitignore. A CLAUDE.md inside a subdirectory is not loaded up front — it comes in when Claude reads a file in that directory, which is how large repositories layer them. When you are done, run /context and check the Memory files list to confirm the file really loaded.
Permission modes: from asking at every step to running unattended, and how to pick among four
Once the teammate is editing files and running commands, do you want it to raise a hand every time or to get on with it? Claude Code turns that choice into a permission mode, cycled with Shift+Tab and shown in the status line:
- Manual (configuration value
default): asks before editing a file, running a command, or calling an external tool. The safest and the most tiring — by the tenth time you click Allow you are no longer reviewing, only clicking. - acceptEdits: file edits go through unasked, commands still ask. Suits "I trust its code, but I want to see the commands."
- plan: read-only. It can read files, run read-only commands, answer questions, and write a plan, but change nothing. The star of the next section.
- auto: does not ask you; instead a separate classifier model reviews every step and blocks what looks dangerous (scope creep, touching unknown infrastructure, actions driven by malicious content), letting the rest through. It is the default for interactive sessions on Pro / Max / Team plans.
Two more modes exist mainly for automation: dontAsk (anything not on the allowlist is refused, which suits a locked-down CI) and bypassPermissions (everything allowed, for isolated sandboxes only). We expand on those two on D5 when we get to CI.
More useful than picking a mode are two tools that reduce interruptions without giving up control: use /permissions to allowlist commands you trust (pnpm lint, git commit), and use /sandbox to turn on OS-level file and network isolation so Claude can run freely inside a fence. One example of allowlist syntax is worth memorizing: in Bash(git diff *) that space matters, because Bash(git diff*) without it would also admit git diff-index.
Plan Mode: explore, then plan, then write — walked through with the example task
Telling the teammate to start writing code immediately most often produces beautiful code that solves a different problem. Good collaboration has three steps: see the current state clearly, agree on an approach, then do the work. Plan Mode makes those three steps a switch: press Shift+Tab to reach plan, or start with claude --permission-mode plan — in this mode Claude can only read, so you can let it rummage anywhere.
Walk it through with the example task. Step one, explore, in plan mode:
Read src/routes/todos.ts and the test/ directory. Work out how POST /todos handles
the request body today, which test framework is used, and how tests are run.
Do not change anything yet.Step two, plan:
I want to add input validation to POST /todos (title required, 1-200 chars; dueAt
optional and must be an ISO date; clients may not send id or done) plus matching unit
tests. Which files change? What is the response shape on a validation failure?
Write a plan.It comes back with a plan carrying a file list and steps. At this point Ctrl+G opens that plan in your editor for direct edits — most of the time you will drop a step or two and rename something. Step three, implement: leave plan mode (approve the plan, or press Shift+Tab again), then:
Implement your plan. Write the failing tests first, then the validation, then run
pnpm test until everything passes.Step four, commit: "commit with a one-line descriptive message." Four steps, one pull request. The core change Claude ends up producing looks roughly like this in the two stacks:
import { Router } from 'express'
import { z } from 'zod'
// Declare only the fields a client may send; id and done are absent from the schema
const CreateTodo = z
.object({
title: z.string().trim().min(1).max(200),
dueAt: z.string().datetime().optional(),
})
.strict() // extra fields are a 400 rather than being silently ignored
export const router = Router()
router.post('/todos', (req, res) => {
const parsed = CreateTodo.safeParse(req.body)
if (!parsed.success) {
// Structured issues let the client show per-field errors and let tests assert precisely
return res.status(400).json({
error: 'invalid body',
issues: parsed.error.issues.map((i) => ({ path: i.path, message: i.message })),
})
}
const todo = { id: crypto.randomUUID(), done: false, ...parsed.data }
store.push(todo)
res.status(201).json(todo)
})from datetime import datetime
from uuid import uuid4
from fastapi import APIRouter
from pydantic import BaseModel, ConfigDict, Field
router = APIRouter()
class CreateTodo(BaseModel):
# Only fields a client may send; extra="forbid" turns id or done into a 422
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
title: str = Field(min_length=1, max_length=200)
dueAt: datetime | None = None # pydantic validates the ISO 8601 format
@router.post("/todos", status_code=201)
def create(body: CreateTodo):
# FastAPI validates before the function runs and returns a structured detail list on failure
todo = {"id": uuid4().hex, "done": False, **body.model_dump(exclude_none=True)}
store.append(todo)
return todoWhen should you not use Plan Mode? Fixing a typo, adding a log line, renaming a variable — for work whose diff you can describe in one sentence, just let it do the thing; a plan is pure overhead. The criterion is simple: if you are unsure of the approach, several files change, or you do not know this code, plan first; otherwise go straight in.
Context is the scarcest resource: /clear, /compact, and /rewind each do one job
D2 said the context window is the scarcest resource, and in Claude Code that becomes a daily physical sensation: every file it reads, the output of every command it runs, and every turn of your conversation all pile into the same window. One debugging session can burn tens of thousands of tokens, and the fuller the window, the more easily it forgets earlier instructions and the more mistakes it makes. Nearly every recommendation on the official best practices page derives from this one constraint.
So manage it deliberately. Three commands, one job each, and do not mix them up:
/clear— reset between tasks. Finish something unrelated and clear, so the next thing starts on a clean window. The most common failure mode is the grab-bag session: you fix A, ask about B along the way, then come back to A, and the window is full of unrelated debris. Another rule of thumb: if correcting the same problem twice has not worked,/clearand restart with a better prompt that absorbs the lesson — failed attempts left in the window keep polluting it./compact— compress mid-task. When one job has run long and the window is nearly full but the work is not done,/compacthas it summarize the history into a digest and free up room. You can steer it:/compact keep the API changes and the test commands. It also compacts automatically near the limit, but compacting deliberately lets you control what survives./rewind(orEsctwice) — go back to a checkpoint. Every prompt you send creates a checkpoint automatically, and file changes get snapshotted before they land. If a direction turns out wrong, open the rewind menu and restore the conversation only, the code only, or both; you can also summarize forward from a point — compacting just that stretch and keeping the rest. This is what makes "let it try a bold approach and back out if it fails" a normal way to work. Note that it only tracks changes made through Claude's edit tools; files changed by Bash commands are not covered, so it is no substitute for git.
Two smaller window-savers beyond those three: /btw asks a side question you do not want in the history, and its answer stays out of the context; and research work goes to a subagent that digs through files in its own window and brings back only the conclusion — D4 expands on that.
Giving Claude a verifiable check: it is done when the tests pass
The last section today is also the single most important idea of these five days. When the teammate says "done," how do you know it is done? If the only way to tell is to go look yourself, then you are its test suite, and every error waits for you to notice it — with you present it is a productivity tool, and with you absent it is a liability.
The fix is to give it a check it can run itself: a test suite, a build command, a lint, a script that diffs output against a fixture, a screenshot compared to a design. With that check in place the loop closes: it works, it runs the check, it reads the result, it fixes, until the check passes. You step out of the verification loop and become the person reviewing evidence — reading the test output it pasted is far faster than rerunning it yourself.
The difference in your prompt is one sentence long. "Add validation to POST /todos" is the version without a check. "Add validation to POST /todos, with these cases: empty title returns 400, over-long title returns 400, a valid request returns 201; then run pnpm test until everything passes" is the version with one. The same idea in CLAUDE.md is that definition-of-done section: which command must pass for the work to count.
If you want the check harder, there are three more rungs: put it in /goal, where a separate evaluator rechecks after every turn until the goal is met; write it as a Stop hook so a turn may not end while tests fail — that is a deterministic gate, and it is D4's subject; or have another subagent re-verify the conclusion in a fresh context, so the doer and the judge are not the same party — that is D5's adversarial review. Today, just get to "there is a check"; the remaining three days are about making that check progressively harder.
One counter-intuitive reminder: make it show evidence rather than announce success — paste the test output, the commands run and their return values, the screenshot. What you review is the evidence, not its confidence.
Source Reading
Hands-On Lab
This is a documentation-style lab whose deliverable is one CLAUDE.md. It is best done on a project you are actually working on — the course's TODO API is only an illustration; if you have nothing suitable, use the demo TODO API in the D4 lab directory. The template in starter/ has blanks and prompting questions alongside them, and solution/ holds a worked version for the TODO API plus a record of what got deleted and why.
- Install Claude Code, go to a project directory, run claude, and ask three questions a new colleague would ask, watching how it digs through files to answer.
- Run /init to generate the draft, read it through, and mark every line keep / delete / rewrite using the checklist in the starter.
- Rewrite it in the four-section structure: commands, style, etiquette, definition of done. Count the lines when you are done and keep trimming past 60.
- Run /context to confirm it appears under Memory files, switch to Plan Mode, and have Claude produce a plan from the example task prompt.
- Check the plan against the rules in your CLAUDE.md. For any rule it ignored, suspect vague wording or an over-long file first, then fix and try again.
Interview Questions
Today's 3 questions are in the question bank below, weighted toward the division of labor between CLAUDE.md and a skill, why the context window needs active management, and why a verifiable check is the watershed. Expand each one and read the analysis before the key points — practicing the derivation beats memorizing bullets. The high-frequency labels for the domestic and overseas markets are there so you can pick by target market.
Checklist and Tomorrow
- Install Claude Code and explain what belongs in CLAUDE.md and what doesn't
- Walk through explore, plan, and implement using Plan Mode, and switch to the right permission mode
- Manage context in a session with /clear /compact /rewind, and give Claude a verifiable check
- Name at least three of the five common failure modes and the fix for each
- All 5 acceptance criteria of the lab pass
- Answer at least 2 of the 3 interview questions without looking at the key points
Tomorrow (D4) we answer a question today leaves open: CLAUDE.md says "run the tests before committing," and Claude will comply most of the time — but most of the time is not always. Turning that into always takes hooks, which are a gate rather than a suggestion. You will also learn to package a repeatable workflow as a skill, send research work off to a subagent, and wire in MCP servers and CLI tools that other people already built. We learn to write the handbook before we learn to install the gate, because you have to know which rules get ignored sometimes before you know which ones deserve a hard constraint.
Interview questions
How do CLAUDE.md and skills divide responsibilities, what goes where, and what goes wrong when CLAUDE.md grows to 500 lines?CLAUDE.md 和 skill 的分工是什么?什么内容该放哪边?一份 CLAUDE.md 写到 500 行会出什么问题?
Common in ChinaCommon overseasBasic#claude-md#skills#contextHow to reason about it · think before answering
- This tests context-cost awareness. 'CLAUDE.md holds rules, skills hold procedures' is the conclusion; derive it from how each is loaded.
- Start from load timing: CLAUDE.md enters context in full every session — a fixed cost; a skill keeps only its one-line description resident and loads its body on invocation — a variable cost. Hence short facts that always apply go in CLAUDE.md, occasional multi-step procedures go in skills.
- Give the table: commands, non-default style, repo etiquette, environment quirks, and the definition of done belong in CLAUDE.md; deployment runbooks, issue-fixing steps, document generators belong in skills. Multi-step procedures in CLAUDE.md or always-on rules inside a skill are both misplacements.
- At 500 lines the failure is dilution, not capacity: important rules drown, adherence drops, and every turn pays for the bloat. Fixes: prune ruthlessly (would removing this cause a mistake?), move occasional content to skills, split path-scoped rules into .claude/rules/ so they load only when matching files are touched.
- Follow-ups: a rule that keeps being ignored — prune, then disambiguate, then emphasize; anything that must run every time should be a hook, not a sentence.
分析过程 · 先想清楚再作答
- 这题考的是「上下文成本意识」。答成「CLAUDE.md 放规则、skill 放流程」只是结论,面试官想听你从加载方式推出这个结论。
- 拆法从加载时机入手:CLAUDE.md 每次会话整份进入上下文,是固定成本;skill 只有描述那一行常驻,正文在被触发(模型判断相关或用户输入 /name)时才加载,是按需成本。所以「每次都成立的短事实」放 CLAUDE.md,「偶尔才用、一用就是多步」的流程放 skill。
- 给判据表:命令、风格差异、仓库礼仪、环境怪癖、完成的判据进 CLAUDE.md;部署流程、修 issue 的固定步骤、某类文档的生成方法进 skill。反过来,CLAUDE.md 里出现了多步流程,或 skill 里放了「每次都要遵守」的规则,都是放错了。
- 500 行的问题不是「太长跑不动」,而是稀释:重要规则被淹没,模型的遵守度反而下降,还白白吃掉每轮的窗口。对策是「删到不能再删」(删掉会不会让它犯错?不会就删)、把偶尔用的挪进 skill、按路径拆进 .claude/rules/ 只在碰到匹配文件时加载。
- 可预期的追问:「规则它老是不听怎么办」——先删再改再强调;「必须每次执行」的动作根本不该靠 CLAUDE.md,要改成 hook。
Key points
- CLAUDE.md loads in full every session — fixed cost; a skill keeps one line resident and loads on demand
- CLAUDE.md: short always-true facts — commands, style deltas, etiquette, definition of done; skills: occasional multi-step procedures
- Bloat dilutes: key rules drown, adherence drops, every turn pays
- Fixes: prune, move occasional content to skills, split path-scoped rules; must-run actions become hooks
答题要点
- CLAUDE.md 每次会话整份加载,是固定成本;skill 只常驻一行描述,正文按需加载
- CLAUDE.md 放每次都成立的短事实:命令、风格差异、规矩、完成判据;skill 放偶尔用的多步流程
- 写长的后果是稀释:重要规则被淹没、遵守度下降、每轮白付窗口
- 对策:删到不能再删、偶尔用的进 skill、按路径拆进 rules;必须每次做的改成 hook
Why does the context window need active management in Claude Code, and when do you use /clear, /compact, and /rewind respectively?在 Claude Code 里为什么上下文窗口需要主动管理?/clear、/compact、/rewind 分别在什么时候用?
Common in ChinaCommon overseasIntermediate#context-window#claude-codeHow to reason about it · think before answering
- The keyword is active. Waiting for auto-compaction works, but the interviewer wants to hear that performance degrades before the window is full.
- Why: every file read, command output, and turn lands in one window; a single debugging pass can be tens of thousands of tokens; as it fills the model forgets earlier instructions and errs more, so the discipline is controlling what enters from the start.
- Then the three commands, keyed on whether the history is still useful: switching tasks with useless history — /clear; mid-task with useful history but a filling window — /compact, optionally with instructions on what to keep; wrong direction — /rewind (Esc Esc) to restore conversation or code to a checkpoint, or summarize just one span.
- Two rules of thumb: after two failed corrections, /clear and rewrite the prompt — failed attempts keep polluting; use /btw for side questions that shouldn't enter history; delegate research to a subagent with its own window.
- Follow-ups: when should context accumulate? While deep in one problem where history is still referenced. Limits of rewind: it tracks only edits made through Claude's editing tools, not Bash-driven changes, and is no substitute for git.
分析过程 · 先想清楚再作答
- 题眼是「主动」。被动等自动压缩也能用,面试官想知道你是否理解「窗口填满之前性能就已经在下降」。
- 先说为什么:Claude Code 读的每个文件、跑的每条命令输出、每轮对话都进同一个窗口,一次调试就是几万 token;窗口越满模型越容易忘掉早先的指令、越容易出错,所以不是满了才处理,而是从一开始就控制进什么。
- 再分三个命令,判据是「这段历史还有没有用」:任务切换且历史无用——/clear 清零;任务未完但窗口快满、历史有用——/compact 压缩成摘要,可带指令指定保留什么;走错了方向、想回到某个点——/rewind(Esc Esc)恢复对话或代码到检查点,也能只对某一段做摘要。
- 补两条经验规则:同一问题纠正两次还不对就 /clear 重开,失败的尝试留在窗口里只会继续污染;旁枝问题用 /btw,答案不进历史;查资料派给 subagent,让它在自己的窗口里翻。
- 可预期的追问:什么时候应该让上下文积累?深挖一个复杂问题、历史仍在被引用时;判据是下一步还会不会用到这段历史。再追问 rewind 的边界:只追踪 Claude 用编辑工具做的改动,Bash 改的文件不在其中,不替代 git。
Key points
- Every read, output, and turn shares one window; fullness degrades adherence, so control inputs from the start
- /clear between unrelated tasks or after two failed corrections
- /compact mid-task when history matters but space runs low; pass instructions on what to keep
- /rewind to a checkpoint for conversation or code, or summarize a span; not a git replacement
答题要点
- 所有文件读取、命令输出、对话都进同一窗口;越满越容易忘指令、出错,要从一开始控制
- /clear:切换任务、历史无用时清零;两次纠正无效也清
- /compact:任务未完、历史有用但窗口快满;可带指令指定保留内容
- /rewind:回到检查点恢复对话或代码,或只对一段做摘要;不替代 git
Why is 'give Claude a check it can run' the dividing line for using agents well, and what levels of enforcement can that check have?为什么说「给 Claude 一个可验证的检查」是用好 Agent 的分水岭?检查可以有哪几档硬度?
Common in ChinaCommon overseasIntermediate#verification#agent-loopHow to reason about it · think before answering
- This tests understanding of the agent loop. 'Tests matter' is common sense; explain where the loop closes without a check.
- Chain: an agent works in a do–observe–adjust loop and stops on 'looks done'. Without a runnable check, 'looks done' is the only signal and the verification step falls on you — every mistake waits to be noticed; present, it is a tool, absent, it is a risk. With a check (tests, build exit code, lint, diff-against-fixture, screenshot compare) the loop closes inside the machine: it works, runs, reads, and iterates to green while you review evidence.
- Four levels: in the prompt ('run the tests until they pass') — usable today; as a /goal — an independent evaluator re-checks every turn; as a Stop hook — the turn cannot end until the check passes, deterministic; as a reviewer subagent — the one who did the work is not the one grading it. Each step trades setup for attention.
- Production nuance: demand evidence, not claims — test output, commands and return values, screenshots; reviewing evidence beats re-running.
- Follow-up: can the check itself be gamed? Yes — the model might edit tests to pass. Counter with a deny rule on the test directory or a reviewer specifically checking for test tampering.
分析过程 · 先想清楚再作答
- 这题考对 Agent 循环的理解。答成「测试很重要」是常识;要说清没有检查时循环在谁那里闭合。
- 推导:Agent 在「做、看结果、改」的循环里工作,停下来的信号是「看起来做完了」。没有可运行的检查,「看起来做完了」是唯一信号,验证环落在人身上——每个错误都要等你注意到,你在场它是工具,你不在场它是风险。有了检查(测试、构建退出码、lint、比对脚本、截图对照),循环在机器里闭合:它做、它跑、它读结果、它改到通过,你只审证据。
- 硬度分四档:写进提示词(「实现后跑 pnpm test 直到全过」)——今天就能用;设为 /goal——独立评估器每轮复核直到达成;写成 Stop hook——测试不过不允许结束,确定性门禁;交给另一个 subagent 复核——做的人和判的人分开。每升一档多一点配置,换来少一点盯着。
- 生产视角:要求展示证据而不是宣布成功——贴测试输出、贴命令与返回值、贴截图;审证据比自己重跑快。
- 可预期的追问:检查本身会不会被绕过?会——模型可能改测试让它过。对策是把测试目录放进禁改清单,或让 reviewer subagent 专门核对「有没有为了过而改测试」。
Key points
- Without a check the loop closes on you; with one it closes inside the machine
- A check is anything with a pass/fail signal: tests, build, lint, fixture diff, screenshot compare
- Four levels: prompt instruction, /goal re-evaluation, Stop hook gate, independent reviewer subagent
- Demand evidence over claims; guard against test tampering with deny rules or a dedicated reviewer
答题要点
- 没有检查时循环在人身上闭合,每个错误都等你发现;有检查时循环在机器里闭合
- 检查可以是测试、构建、lint、比对脚本、截图对照,任何能产生通过/失败信号的东西
- 四档硬度:提示词里要求、/goal 每轮复核、Stop hook 确定性门禁、subagent 独立复核
- 要证据不要宣言;防止改测试作弊要靠禁改清单或专门的复核