Best Practices for Professional Developers
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
This closing lesson pulls the module together into the habits that separate people who get steady value from Claude Code from people who fight it. Almost all of it comes from one idea in Anthropic's own best-practices page: tell Claude what it can't see, give it a check to run, and enforce the rules that can't have exceptions. We'll turn that into a short, concrete setup you can commit to a team repository, plus a linter that keeps it healthy.
What you'll learn
- The three ideas behind most good sessions, and how each maps to a Claude Code feature.
- A team setup: what to commit, what to keep personal, what to enforce.
- How to steer a session and keep its cost down.
- A checklist for work you leave running unattended.
- How to lint the whole configuration in CI.
Before you start
- The rest of this module. This lesson refers back to each part.
Three ideas that do most of the work
Anthropic notes that, in most cases, your first plain prompt in a fresh session already does the right thing. The page is about what to do when defaults aren't enough, which happens when your project has knowledge or constraints Claude can't see from the code. They sort into three groups.
1. Tell Claude what it can't see
- Specific prompts. Name the file, describe the symptom, say what fixed looks like. "Follow the pattern in
HotDogWidget.php and build a calendar widget; no new libraries" beats "add a calendar widget".
- A short
CLAUDE.md holding only what the code can't tell Claude: the exact commands to verify work, misleading places in the code, decisions that aren't in the repository, things you've corrected twice. Aim for under 200 lines (lesson 5.4).
- Scoped rules in
.claude/rules/ for part of the codebase (lesson 5.5).
- Skills for team procedures, so a multi-step process costs nothing until used (lesson 5.6).
- Connected tools through MCP, for the systems Claude would otherwise guess about (lesson 5.3).
The same page lists things you can stop doing, because they were workarounds for older models. Don't describe your architecture and file layout in CLAUDE.md (Claude reads the repository). Don't add IMPORTANT or ALL CAPS to lines Claude misses (it mostly makes Claude over-apply the rule; shorten the file or enforce it). Don't use "think harder" phrases (effort is the control). And don't tell Claude to keep going and not be lazy; current models usually carry on, and a check to pass is what actually helps.
2. Give Claude a check to run
"Claude stops when the work looks done. If it has nothing to run that tells it whether the work actually is done, 'looks done' is all it has to go on." Anthropic lists the options from loosest to strictest:
- In the prompt: "run the auth tests after, and keep going until they pass".
- As a goal with
/goal: a separate model checks the condition after every turn.
- As a
Stop hook: enforced by Claude Code, so the turn doesn't end until the check passes (lesson 5.7).
- By someone who didn't write the code:
/code-review, or a read-only reviewer subagent.
Whichever you choose, ask for evidence: the command it ran and its output. After Claude says it's done, /verify has it build and run the app and look at the result, which catches what tests and typechecks miss.
3. Enforce the rules that can't have exceptions
Every instruction is either non-deterministic (a prompt, CLAUDE.md, a skill: Claude decides) or deterministic (a hook, a deny rule, managed settings: Claude Code decides). Most of the time you want Claude to decide. For rules with no exceptions, use deny rules for what it may touch and hooks for what must happen, and use the sandbox for operating-system-level limits. Keep the enforced set small: every hook and deny rule fires wrongly sometimes, and someone has to maintain it. If you find yourself at forty, most are probably preferences Claude could weigh itself.
A team setup
Where a setting lives decides who it applies to, so split deliberately:
| Put it in | For |
CLAUDE.md, .claude/rules/, .claude/skills/, .claude/agents/, .mcp.json (committed) | Shared guidance and tools for everyone |
.claude/settings.json (committed): deny and ask rules, hooks | Team enforcement. Deny rules apply immediately; allow rules wait until each person trusts the folder. |
CLAUDE.local.md, .claude/settings.local.json (gitignored) | Your own preferences and exceptions |
~/.claude/settings.json | Personal defaults across projects |
| Managed settings | Security policy no individual can override |
The example project from this module is exactly that split, and all of it is lintable. Keep the default permission posture sensible: Manual mode is safe but trains you to approve without reading after the tenth prompt, and bypassPermissions only makes sense in a disposable container. Auto mode sits between them, and Anthropic is clear that it's a classifier making judgment calls, so your "never" rules belong in deny rules or hooks, not in it.
Steering a session
Anthropic's own advice: watch the first minute, press Esc the moment Claude drifts, and after two failed corrections run /clear and write a better prompt instead of a third. Know four controls by heart: Esc (stop, keeping everything so far), /rewind or Esc twice (roll back code, conversation or both), /clear (start over) and /btw (a side question that adds nothing to the history). Rename long-running work with /rename so claude --resume name finds it.
Keeping cost under control
- Check
/usage first. It breaks usage down by skill, subagent, plugin and MCP server.
/clear between unrelated tasks. It's free, and the next task stops paying for the last one's history.
/compact with a focus rather than letting an automatic pass guess.
- Watch background work:
/loop, goal checks and subagents all keep sending requests while you aren't typing.
- Use a small model for simple subagents and short summaries back from them.
Before you leave something running
Anthropic's five questions work as a checklist. For the specific task, answer all five:
- Does it know what done looks like? A goal, a spec file, a failing test to turn green.
- Can it check its own work? The test suite, a
Stop hook, a review step.
- What's it allowed to touch? Permission rules,
dontAsk, the sandbox, a worktree, one branch.
- What stops it?
--max-turns, --max-budget-usd with -p, a spend limit.
- Where does the result go, and who signs off? A PR, then a person approving the merge or the deploy.
While you're watching, a missing piece of context is cheap, because you notice within a message or two. Overnight, nobody tells Claude, and you find out the next morning that it spent the night building on a wrong assumption.
Lint the whole thing
Most of what this module configures fails silently: a misspelled frontmatter field, a rule scoped to the wrong path, a hook script that isn't executable, a CLAUDE.md that grew to 400 lines. So here's a small linter for the example project's layout. It checks settings.json (valid JSON, rule syntax, hook events and types, script paths and execute bits), CLAUDE.md (length, shouting, broken imports), skills, subagents, .claude/rules frontmatter, .mcp.json (including literal credentials in headers) and .gitignore.
#!/usr/bin/env python3
"""Lint a project's Claude Code configuration for mistakes the docs warn about.
It checks form, not wisdom: a clean report does not mean your instructions are good. Field lists come from the
Claude Code docs checked on 15 Nov 2026; a field this script does not know is reported as INFO, because Claude Code
itself ignores unknown frontmatter fields without any error, so a typo is silent.
"""
import json
import os
import re
import stat
import sys
from pathlib import Path
import yaml
HOOK_EVENTS = {
"SessionStart", "Setup", "UserPromptSubmit", "UserPromptExpansion", "PreToolUse", "PermissionRequest",
"PermissionDenied", "PostToolUse", "PostToolUseFailure", "PostToolBatch", "Notification", "MessageDisplay",
"SubagentStart", "SubagentStop", "TaskCreated", "TaskCompleted", "Stop", "StopFailure", "TeammateIdle",
"InstructionsLoaded", "ConfigChange", "CwdChanged", "DirectoryAdded", "FileChanged", "WorktreeCreate",
"WorktreeRemove", "PreCompact", "PostCompact", "PreModelSwitch", "PostModelSwitch", "Elicitation",
"ElicitationResult", "SessionEnd",
}
HOOK_TYPES = {"command", "http", "mcp_tool", "prompt", "agent"}
SKILL_FIELDS = {"name", "description", "when_to_use", "argument-hint", "disable-model-invocation", "user-invocable",
"allowed-tools", "context", "paths", "arguments"}
AGENT_FIELDS = {"name", "description", "tools", "disallowedTools", "permissionMode", "maxTurns", "skills",
"mcpServers", "hooks", "memory", "effort", "isolation", "color", "model", "omitClaudeMd"}
RULE_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]*(\(.*\))?$", re.S)
EMPHASIS = re.compile(r"\b(IMPORTANT|CRITICAL|NEVER|ALWAYS|MUST)\b")
class Report:
def __init__(self):
self.items: list[tuple[str, str, str]] = []
def add(self, level: str, where: str, msg: str):
self.items.append((level, where, msg))
def count(self, level: str) -> int:
return sum(1 for lvl, _, _ in self.items if lvl == level)
def render(self) -> str:
return "\n".join(f"{lvl:5} {where}: {msg}" for lvl, where, msg in sorted(self.items)) or "No findings."
def load_json(path: Path, rep: Report):
try:
return json.loads(path.read_text())
except json.JSONDecodeError as e:
rep.add("ERROR", str(path), f"invalid JSON ({e.msg} at line {e.lineno}). Claude Code settings files are strict JSON: no comments, no trailing commas.")
except OSError:
pass
return None
def frontmatter(path: Path):
text = path.read_text()
m = re.match(r"^---\n(.*?)\n---\n", text, re.S)
if not m:
return None, text
return yaml.safe_load(m.group(1)) or {}, text[m.end():]
def check_settings(root: Path, rep: Report):
path = root / ".claude" / "settings.json"
data = load_json(path, rep)
if data is None:
return
perms = data.get("permissions", {})
for kind in ("allow", "ask", "deny"):
for rule in perms.get(kind, []):
where = f"settings.json permissions.{kind}"
if not isinstance(rule, str) or not RULE_RE.match(rule):
rep.add("ERROR", where, f"malformed rule {rule!r}; use Tool or Tool(specifier).")
continue
if rule.startswith("mcp__") and "(" in rule:
rep.add("ERROR", where, f"{rule!r}: Claude Code skips mcp__ rules that have parentheses.")
if re.match(r"^(Bash|PowerShell)\(command:", rule):
rep.add("ERROR", where, f"{rule!r}: matching the command parameter this way is ignored; use Bash(pattern).")
if kind == "allow" and rule in ("Bash", "Bash(*)"):
rep.add("WARN", where, "allows every shell command. Prefer specific patterns, and keep deny rules for secrets.")
allow_keys = set(perms.get("allow", []))
for rule in perms.get("deny", []):
if rule in allow_keys:
rep.add("WARN", "settings.json permissions", f"{rule!r} is both allowed and denied; deny wins, so the allow rule does nothing.")
if perms.get("defaultMode") in ("bypassPermissions", "auto"):
rep.add("WARN", "settings.json permissions.defaultMode", "this value does not take effect from a project settings file; set it in user or managed settings.")
hooks = data.get("hooks", {})
for event, entries in hooks.items():
if event not in HOOK_EVENTS:
rep.add("ERROR", f"settings.json hooks.{event}", "unknown hook event name. Claude Code skips it with a warning.")
continue
for entry in entries:
if not isinstance(entry, dict) or "hooks" not in entry:
rep.add("ERROR", f"settings.json hooks.{event}", "each entry needs a 'hooks' list.")
continue
for h in entry["hooks"]:
t = h.get("type")
if t not in HOOK_TYPES:
rep.add("ERROR", f"settings.json hooks.{event}", f"unknown hook type {t!r}.")
if t == "command":
check_hook_script(root, h.get("command", ""), event, rep)
def check_hook_script(root: Path, command: str, event: str, rep: Report):
m = re.search(r'"?\$CLAUDE_PROJECT_DIR"?/([^\s"]+)', command)
if not m:
return
script = root / m.group(1)
where = f"hook {event}"
if not script.exists():
rep.add("ERROR", where, f"script {m.group(1)} does not exist.")
elif not os.access(script, os.X_OK) and not (script.stat().st_mode & stat.S_IXUSR):
rep.add("ERROR", where, f"script {m.group(1)} is not executable. Run chmod +x.")
elif script.read_text().startswith("#!") is False:
rep.add("WARN", where, f"script {m.group(1)} has no shebang line.")
def check_claude_md(root: Path, rep: Report):
for rel in ("CLAUDE.md", ".claude/CLAUDE.md"):
path = root / rel
if not path.exists():
continue
text = path.read_text()
lines = text.count("\n") + 1
if lines > 200:
rep.add("WARN", rel, f"{lines} lines. Anthropic recommends under 200; longer files reduce adherence. Move area-specific rules to .claude/rules/.")
shouting = len(EMPHASIS.findall(text))
if shouting >= 4:
rep.add("WARN", rel, f"{shouting} capitalised emphasis words. If a rule truly cannot have exceptions, enforce it with a hook or a deny rule instead.")
stripped = re.sub(r"```.*?```|`[^`]*`", "", text, flags=re.S)
for ref in re.findall(r"(?<![\w`])@([\w./~-]+)", stripped):
target = Path(ref).expanduser() if ref.startswith("~") else (path.parent / ref)
if "." in Path(ref).name and not target.exists():
rep.add("WARN", rel, f"imports @{ref}, which does not exist.")
if len(text.strip().splitlines()) < 3:
rep.add("INFO", rel, "very short. Add the commands Claude needs to check its own work.")
if not (root / "CLAUDE.md").exists() and not (root / ".claude/CLAUDE.md").exists():
rep.add("INFO", "CLAUDE.md", "no project CLAUDE.md found. Run /init to generate a starting point.")
def check_frontmatter_files(root: Path, rep: Report):
for skill in sorted((root / ".claude" / "skills").glob("*")):
md = skill / "SKILL.md"
if skill.is_dir() and not md.exists():
rep.add("ERROR", f"skills/{skill.name}", "directory has no SKILL.md.")
continue
if not md.exists():
continue
fm, body = frontmatter(md)
where = f"skills/{skill.name}/SKILL.md"
if fm is None:
rep.add("WARN", where, "no YAML frontmatter, so Claude has no description to decide when to use it.")
continue
if not fm.get("description"):
rep.add("WARN", where, "no description. Claude decides when to apply a skill from its description.")
for key in fm:
if key not in SKILL_FIELDS:
rep.add("INFO", where, f"field {key!r} is not in the documented list; unknown fields are ignored silently, so check for a typo.")
if len(str(fm.get("description", "")) + str(fm.get("when_to_use", ""))) > 1536:
rep.add("WARN", where, "description plus when_to_use is over 1,536 characters and will be truncated.")
if len(body.splitlines()) > 500:
rep.add("INFO", where, "long skill body; it stays in context once loaded. Move reference material to supporting files.")
for agent in sorted((root / ".claude" / "agents").glob("*.md")):
fm, _ = frontmatter(agent)
where = f"agents/{agent.name}"
if fm is None or not fm.get("name") or not fm.get("description"):
rep.add("ERROR", where, "a subagent needs frontmatter with name and description.")
continue
if ":" in str(fm["name"]):
rep.add("ERROR", where, "the name cannot contain ':'.")
for key in fm:
if key not in AGENT_FIELDS:
rep.add("INFO", where, f"field {key!r} is not in the documented list; unknown fields are ignored silently, so check for a typo (fields are camelCase, e.g. disallowedTools).")
if "tools" not in fm:
rep.add("INFO", where, "no tools list, so it inherits every tool. Restrict a reviewer to Read, Grep, Glob.")
def check_rules(root: Path, rep: Report):
for rule in sorted((root / ".claude" / "rules").glob("**/*.md")):
where = f"rules/{rule.relative_to(root / '.claude' / 'rules')}"
text = rule.read_text()
if text.startswith("---"):
try:
fm, _ = frontmatter(rule)
except yaml.YAMLError as e:
rep.add("ERROR", where, f"frontmatter is not valid YAML ({e.__class__.__name__}); Claude Code then loads the rule with no paths.")
continue
if fm is None:
rep.add("ERROR", where, "frontmatter is not closed with a second ---.")
continue
for key in fm:
if key != "paths":
rep.add("WARN", where, f"field {key!r} is ignored. 'paths' is the only frontmatter field a rule reads.")
paths = fm.get("paths")
if paths is not None and not isinstance(paths, (list, str)):
rep.add("ERROR", where, "paths must be a YAML list or a comma-separated string.")
if len(text.splitlines()) > 200:
rep.add("WARN", where, "over 200 lines; split it or trim it.")
def check_mcp(root: Path, rep: Report):
path = root / ".mcp.json"
if not path.exists():
return
data = load_json(path, rep)
if data is None:
return
for name, server in data.get("mcpServers", {}).items():
where = f".mcp.json {name}"
if "url" not in server and "command" not in server:
rep.add("ERROR", where, "needs a url (http) or a command (stdio).")
for header, value in (server.get("headers") or {}).items():
if re.search(r"(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{12,}", str(value)) and "${" not in str(value):
rep.add("ERROR", where, f"header {header} contains what looks like a literal credential. Use ${{VAR}} so the secret is not committed.")
def check_gitignore(root: Path, rep: Report):
gi = (root / ".gitignore")
text = gi.read_text() if gi.exists() else ""
for needed in ("CLAUDE.local.md", ".claude/settings.local.json"):
if needed not in text:
rep.add("INFO", ".gitignore", f"does not list {needed}. Personal files should stay out of the repository.")
def lint(root: str | Path) -> Report:
root = Path(root)
rep = Report()
check_settings(root, rep)
check_claude_md(root, rep)
check_frontmatter_files(root, rep)
check_rules(root, rep)
check_mcp(root, rep)
check_gitignore(root, rep)
return rep
if __name__ == "__main__":
report = lint(sys.argv[1] if len(sys.argv) > 1 else ".")
print(report.render())
sys.exit(1 if report.count("ERROR") else 0)
Be clear about what it is. It checks form, not wisdom. A clean report doesn't mean your instructions are good, and a field it doesn't recognise is reported as information, because Claude Code ignores unknown fields without any error. The skill and subagent field lists come from the documentation we checked, and Claude Code adds features often, so treat "not in the documented list" as a prompt to look, not a verdict.
What we verified: 10 tests pass, covering invalid JSON and comments, malformed and contradictory permission rules, an unknown hook event, a missing or non-executable hook script, an oversized CLAUDE.md with a broken import, misspelled skill and agent fields, bad rule frontmatter and a literal secret in .mcp.json; the example project produces no findings; and the script exits non-zero on errors so CI can fail. We also compared its list of hook events with the one printed by the installed Claude Code (version 2.1.319) and the two match exactly: 33 events, none missing and none extra. To run it on every change to your Claude configuration:
name: Claude Code config
on:
pull_request:
paths:
- "CLAUDE.md"
- ".claude/**"
- ".mcp.json"
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install pyyaml
- name: Lint Claude Code configuration
run: python tools/claude_config_lint.py .
The workflow file is valid YAML, and it's a standard GitHub Actions layout, but we haven't run it on GitHub.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A five-person agency adopts Claude Code across client projects. They agree one repository template: a 40-line CLAUDE.md, two path-scoped rules, a new-endpoint skill, a read-only reviewer agent and four hooks. Deny rules cover .env and destructive commands. Everyone keeps personal preferences in gitignored files. The config linter runs on pull requests that touch those files. Within a month the most useful result is boring: when a new teammate's session behaves oddly, they run claude doctor and the linter before asking anyone, and the problem is usually a typo.
Mistakes to avoid
- A giant
CLAUDE.md and no enforcement.
- Hooks and deny rules for things that are merely preferences.
- No way for Claude to verify its work.
- Reviewing with the session that wrote the code.
- Accepting the trust prompt for repositories you haven't read.
- Treating auto mode as a security boundary.
- Leaving long runs unattended without a cap or a sign-off.
Security notes
- Protect secrets with
Read deny rules and the sandbox, not with a sentence in CLAUDE.md.
- Review
.claude/ and .mcp.json changes in pull requests like code: they define what runs on every contributor's machine.
- Only connect MCP servers you trust. Servers that fetch external content can expose you to prompt injection.
- Only use
bypassPermissions in an isolated container or VM.
- Rules match tool calls, not intent. A
Read deny catches cat .env but not a script that opens the file, so layer the sandbox on top.
Cost and speed
The biggest levers are the cheapest ones: a focused context (/clear between tasks), a short CLAUDE.md, small models for simple subagents and a clear spec so you aren't paying for rounds of correction. Run /usage regularly rather than guessing.
Key takeaways
- Tell Claude what it can't see; give it a check to run; enforce the rules with no exceptions.
- Keep
CLAUDE.md short and concrete; put procedures in skills and hard rules in hooks and deny rules.
- Commit shared config, gitignore personal config, and lint it, because most of it fails silently.
- For unattended runs, define done, provide a check, limit access, cap spend and require a human sign-off.
Lesson recap: three habits, the team setup, and the unattended-run checklist.
Quick quiz
- What are the three ideas at the centre of Anthropic's best-practices page?
- Why is a reviewer subagent better than asking the same session to review its own work?
- Where do you put a rule that must hold in every permission mode?
- Name three of the five questions to answer before an unattended run.
- Why lint your Claude Code configuration?
Answers and explanations
- Tell Claude what it can't see, give it a check to run, and enforce the rules that can't have exceptions.
- It hasn't seen the reasoning or the implementation, so it isn't swayed by them and may spot what the author overlooked.
- In a deny rule or a
PreToolUse hook. Both hold even in auto and bypassPermissions modes.
- Any three of: what done looks like, can it check its work, what may it touch, what stops it, who signs off.
- Much of the configuration fails silently: misspelled fields are ignored, rules can be scoped wrongly and scripts can be non-executable. A linter finds these before they cost you a confusing session.
Official references and further reading
Related tutorials