Claude Code prompt workflow for large repos without risking prod
Practical Claude Code prompt workflows for big monorepos: keep it on a local clone, separate scan/plan/edit/review, and avoid the 48k-file-deletion class of mistakes.
What you will set up with these Claude Code workflows
This guide shows how to run Claude Code on a large, long‑lived repo without ever giving it CI or production access. You will:
- Lock Claude Code to a local or disposable dev clone with no production credentials.
- Use a small library of prompt workflows that always separate scan → manifest → plan → narrow edits → review.
- Exploit Claude Code’s large‑repo features while avoiding catastrophic failures like the widely reported 48,000‑file deletion incident described by TechRadar.
- Control token cost by keeping most work on Claude Sonnet 5 and reserving Fable/Opus for small, high‑value review steps, using Anthropic’s current list pricing for each model as of the date you run these workflows.
The rest of this article is concrete: six reusable workflows with prompts, branch and git strategy, stop conditions, and context‑management checks tuned for big, long‑lived repositories. If you are still deciding whether Claude Code is the right agent for your stack, see the separate Claude Code review for 2026 builders for a feature‑level comparison against Cursor and Codex.
Claude Code’s role in a large repo: pair programmer on a leash
Anthropic positions Claude Code as an agentic coding tool that can search and read code, edit files, run tests, and use command‑line tools from a terminal or IDE extension, as described in the Claude 3.7 Sonnet and Claude Code launch and subsequent Claude Code documentation. The follow‑up announcement on autonomy explains that the upgraded terminal and VS Code extension are powered by Claude Sonnet 4.5 and are designed to take on longer, more complex development tasks more independently.
Those capabilities are useful but dangerous on a mission‑critical monorepo. The right mental model for this article is:
- Surface area of control: Claude Code is restricted to a local or disposable dev clone. It never gets CI tokens, production kubeconfigs, cloud credentials, or database URLs. For teams that do want CI‑side agents, use a sandboxed pattern like the safe AI coding agents in GitHub Actions workflow rather than giving Claude Code live CI credentials.
- Workflow structure: Claude Code never just “runs until done”. Every session follows a scripted sequence with explicit checkpoints and human approvals.
- Git authority: Claude Code can propose edits and even stage hunks, but you own the commits, branches and pull requests.
This approach follows the same direction as earlier terminal‑first guidance on this site, but here it is applied to large, long‑lived repos with explicit prompt workflows. For production‑facing setups where Claude Code needs limited access to shared repos, see the separate architecture article on safe Claude Code permissions for production repos.
Safety and cost foundations before you start prompting
All the workflows later in this article assume a baseline setup.
Step 1: lock Claude Code to a safe local surface
Before opening Claude Code:
- Create a dedicated dev clone:
- Clone via SSH or HTTPS to a non‑production machine, ideally a laptop or a dev VM.
- Ensure it points at
origin with fetch only; do not store personal access tokens with write scopes in the environment used by Claude Code.
- Strip secrets and production hooks:
- Remove or stub any
.env files containing production database URLs, API keys or cloud credentials.
- Disable scripts that auto‑deploy on
git push (e.g. Git hooks) in this clone.
- Run under a low‑privilege user:
- On Unix‑like systems, use a non‑sudo user so even a bad command cannot damage system files.
Reports of autonomous Claude Code runs deleting tens of thousands of files in seconds show what can happen when an agent is granted broad shell powers with weak guardrails. A local, low‑privilege dev clone containing only the repo sharply reduces blast radius. If you instead want agents to act directly in CI with hard isolation, use a sandboxed pattern like the AI SDK 7 HarnessAgent CI sandbox workflow rather than giving Claude Code live CI credentials.
Step 2: choose models and budget deliberately
As of late 2026, Anthropic’s pricing documentation lists Claude Sonnet 5 at $2 per 1M input tokens and $10 per 1M output tokens on the Claude Platform, and Claude Opus 5 at $5 per 1M input tokens and $25 per 1M output tokens on the Claude Platform, with all prices quoted in USD per million tokens and separate tables for different deployment platforms. Claude Fable 5.1 is positioned by Anthropic as a highest‑capability model for demanding coding and long‑running problem‑solving work; check your current Claude plan’s documentation to confirm whether Fable 5.1 and Claude Code are both included.
For large repos, the cost‑efficient pattern is:
- Use Sonnet 5 for broad scanning, manifest creation, and plan discussion.
- Optionally use Fable or Opus on a final, narrow diff+tests review when the input context is small.
| Model |
Recommended usage in these workflows |
Input price (USD / 1M tokens) |
Output price (USD / 1M tokens) |
| Sonnet 5 |
Repo scan, manifest, planning, everyday edits |
$2 (Claude Platform, as of late 2026) |
$10 (Claude Platform, as of late 2026) |
| Fable 5.1 |
Occasional deep analysis of complex changes |
Not publicly listed; see current pricing docs |
Not publicly listed; see current pricing docs |
| Opus 5 |
Final review of diffs and test logs only |
$5 (Claude Platform, as of late 2026) |
$25 (Claude Platform, as of late 2026) |
If a refactor burns 5M input and 1M output tokens during scanning and planning, then at Claude Platform list prices of $2 per 1M Sonnet 5 input tokens and $10 per 1M Sonnet 5 output tokens, that Sonnet run would cost 5 * $2 + 1 * $10 = $20. At Opus 5’s Claude Platform prices of $5 per 1M input and $25 per 1M output tokens, the same token volumes would cost 5 * $5 + 1 * $25 = $50. Always confirm current per‑model pricing on the official pricing page before relying on these example numbers. For a broader view of how Claude Code compares on price to Cursor and Codex across a team, see the separate breakdown on the real cost of running Cursor, Codex and Claude Code together.
Step 3: enforce manual git and branch discipline
Even though Claude Code can commit and push, Anthropic’s own guidance for large repos emphasises manifests and careful workflows in its large‑codebase best‑practices article. For long‑lived monorepos, treat git operations as human‑only:
- Create a work branch yourself for each workflow, e.g.
feat/upgrade-logger-v2, refactor/auth-cleanup.
- Tell Claude Code explicitly it must not run
git commit or git push. It can stage files at most.
- Commit in small, reviewable slices: one conceptual step per commit: “replace legacy logger in payment service”, “update tests for new logger”, “remove deprecated logger module”.
- Open PRs by hand and use Claude only to explain and review diff content. If you want a more formal pattern here, combine this with the separate article on a safe AI coding agent PR workflow.
Step 4: keep sessions short and stateful, not sprawling
Anthropic’s prompt‑engineering and compaction documentation notes that conversations can be compacted—summarising earlier turns to stay within token limits—and Claude Code builds on these mechanisms for long‑running coding sessions. Separate engineering analysis from April 2026 ties some Claude Code quality regressions to changes in how session state and reasoning history were managed, since fixed in version v2.1.116. Anthropic’s April 23, 2026 engineering postmortem on Claude Code quality reports ties user‑visible regressions to three product‑layer changes, including a caching bug that repeatedly cleared prior “thinking” and a verbosity prompt change, and states that all three were fixed as of version v2.1.116 on April 20, 2026—highlighting how sensitive behaviour is to context‑management changes in long, dense histories.
On large repos, that means:
- Prefer short, goal‑bounded sessions for each workflow: e.g. “modernise logging in payment service”.
- Write short human summaries between sessions that you paste into the next one so Claude does not rely on compacted history.
- Close and restart sessions if they drift or start forgetting earlier constraints.
The library: six Claude Code workflows for large repos
Each workflow below includes:
The Claude Code VS Code extension presents multi-file change sets with inline diffs, giving you a clear place to review and approve each edit before committing.
- A safety and setup preamble.
- Phased prompts for scan → manifest → plan → execution → verification.
- Explicit stop/exit conditions.
- Context‑management prompts that acknowledge compaction behaviour.
All prompts assume Claude Code is running in the terminal or VS Code extension on a local clone. Where dynamic workflows are referenced, the pattern mirrors Anthropic’s Introducing dynamic workflows in Claude Code design: Claude writes parameterised workflows that propose command sequences, show what they will run, and include an explicit first‑run confirmation step before executing commands. For a deeper dive on how to design repo‑level contracts that give any coding agent safe, layered context in a large repo, you can pair this guide with the separate article on designing coding agent context in large repositories.
Workflow 1: safe initial repo scan and manifest
Goal: give Claude Code a structured view of a huge repo without loading every file into context.
Safety setup:
- Create branch:
git switch -c chore/manifest-refresh.
- Confirm no production configs:
ls.env*, scrub as needed.
- Open Claude Code in the repo root and start a fresh session.
Step 1: establish constraints and purpose
System / first message to Claude Code
You are attached to a local git clone of our main monorepo.
Hard safety rules for this session:
- Do NOT run git commit or git push.
- Do NOT install global packages or use sudo.
- Do NOT modify or run deployment, CI, or infrastructure scripts.
- Ask for confirmation before running any command that writes to disk.
Goal of this session:
- Produce a high-level manifest of the repo structure and major subsystems.
- Identify 5–10 key entrypoints and shared libraries per domain.
Because the repo is large and your context may be compacted over time, you must:
- Work in phases (scan -> summarise -> manifest) and keep your own summaries short.
- At the end, output a single manifest file at ./docs/ai/manifest.md and then stop.
Step 2: let Claude propose a scan plan
User
Describe how you will scan this repo safely and efficiently.
List the exact commands you want to run (read-only first),
and what you expect to learn from each. Then wait for my approval.
Expected response: a plan featuring commands like ls, find. -maxdepth 3 -type d, language‑server queries, and ripgrep searches. It should explicitly avoid writes.
Step 3: approve only read‑only commands
User
You may run ONLY the read-only commands you listed.
Do not create or modify any files yet.
After running them, summarise the architecture in < 300 words.
Claude Code will run the commands and summarise. If it proposes any writes, stop and restate constraints.
Step 4: request manifest output
User
Now create ./docs/ai/manifest.md with:
- Top-level directories and their purposes.
- For each major app/service/package: primary entrypoint files.
- Shared libraries/utilities and their responsibilities.
Show the full file contents as a markdown code block before writing.
Wait for my approval before creating the file.
Check the manifest content. If acceptable:
User
Approved. Create or overwrite ./docs/ai/manifest.md with exactly the content you showed.
Verification and stop condition:
- Run
git status; confirm only the manifest and maybe IDE metadata changed.
- If unexpected files changed, inspect and revert before continuing.
- End the session once the manifest is written and summarised.
On future days, paste the last manifest into new sessions so Claude starts with a compressed, human‑curated view instead of relying on compacted history alone.
Workflow 2: targeted feature understanding in a large monorepo
Goal: quickly understand a feature that spans multiple packages without loading the entire repo into context.
Safety setup: same local‑only rules; no CI/infra scripts.
Step 1: focus Claude on a feature slice
User
We are going to understand the "billing subscriptions" feature across this repo.
Constraints (reminder):
- Do NOT modify files.
- Do NOT run tests or scripts.
Inputs you can use:
- The manifest at ./docs/ai/manifest.md.
- Language server / symbol search.
- ripgrep.
First, based on the manifest, propose 5–10 key files and directories that likely
implement or integrate with billing subscriptions. Then stop and wait.
Step 2: approve a narrow file set
Claude will list candidate files. Reply:
User
Narrow this to at most 20 files that give a good overview: entrypoints,
core domain models, key API handlers, and representative tests.
List them and stop.
Once the list is satisfactory:
User
For each of the 20 files, provide a 2–3 sentence summary:
- What it does.
- How it relates to subscriptions.
Keep total output < 600 words. Do not paste full file contents.
Step 3: build a reusable summary chunk
When Claude finishes, copy its summary into ./docs/ai/feature-billing-subscriptions.md manually, or let it write the file under similar “show first, then write” rules from Workflow 1.
Stop/exit condition: once the summary file exists and git status shows only documentation changes, commit as a doc‑only change and end the session. Future refactor workflows for this feature can paste this summary instead of re‑scanning the repo, reducing token use.
Workflow 3: small, scoped refactor without CI access
Goal: perform a concrete but localised refactor (e.g. migrate from LegacyLogger to StructuredLogger) across a limited slice of the repo.
Safety setup:
- Branch:
git switch -c refactor/logger-structured.
- Ensure tests can be run locally (unit/integration) without external CI.
Step 1: describe the change and guardrails
User
We are going to migrate from LegacyLogger to StructuredLogger
ONLY in the billing subscriptions code you previously summarised.
Hard constraints:
- Do NOT touch deployment, CI, or infra folders.
- Do NOT modify more than 30 files in this session.
- Do NOT run git commit or git push.
Change goals:
- Replace LegacyLogger imports and calls with StructuredLogger equivalents.
- Keep behaviour as close as possible, adjusting formats only when necessary.
- Update or add tests where needed.
Because the repo is large and your context will be compacted over time,
you must:
- Work on a clearly enumerated file list.
- After each batch of at most 10 files, summarise what changed in < 150 words.
First, propose:
- The concrete search queries you will run to find LegacyLogger usage.
- An ordered list of up to 30 files to modify.
- A batch plan (max 10 files per batch).
Then wait.
Step 2: approve a file list and batch plan
Check that the proposed files live in the targeted area. If needed, remove risky paths (e.g. infra/, .github/):
User
Remove any files under infra/, .github/, scripts/deploy, or similar.
Show me the final file list and batch plan. Then stop.
Step 3: batch execution with human review
For each batch:
User
Process batch 1 only.
For each file in batch 1:
- Show the diff as a unified patch in a code block.
- Explain why the change is safe.
Do not write to disk yet.
Review diffs in the Claude Code VS Code sidebar or directly in the editor. When satisfied:
User
Apply exactly the batch 1 changes you proposed.
Do not touch any other files.
After writing, list the files changed and summarise the behavioural impact in < 100 words.
Then run tests locally:
shell
# Example
pnpm test billing-subscriptions -- --runInBand
Paste failing test logs back into Claude:
User
Here are the failing test logs from batch 1. Diagnose and propose targeted fixes.
Keep all new edits within the existing batch 1 files.
Repeat for remaining batches, always limiting scope and reviewing diffs first.
Stop/exit conditions:
- The agreed file list has been fully processed.
- Local tests pass for the affected area.
git diff is understandable and limited to the described scope.
At that point, make 2–3 commits grouping related changes and open a PR. If you prefer a more formal PR‑first pattern that fits existing review processes, combine this with the separate safe AI coding agent PR workflow.
Workflow 4: dynamic workflows with dry runs and confirmation
Goal: use Claude Code’s dynamic workflows pattern for repeated operations (e.g. updating headers across hundreds of files) while retaining human control.
Anthropic’s “Introducing dynamic workflows in Claude Code” blog describes a pattern where Claude writes parameterised workflows that propose command sequences, show what they will run, and include an explicit first‑run confirmation step before executing commands. This is particularly important in large repos where a bad glob could touch thousands of files.
Example use case: add a standard licence header to certain source files.
Step 1: instruct Claude to define a dry‑run workflow
User
We need a reusable workflow to add a standard license header to
all .ts and .tsx files under apps/billing/ only.
Safety requirements:
- The workflow must support a DRY-RUN mode that only prints what it will change.
- On first run, it must show me all commands and wait for confirmation.
- It must never operate outside apps/billing/.
- It must never touch more than 200 files per run.
Design a dynamic workflow that:
- Accepts parameters: target_glob, dry_run (bool).
- Uses ripgrep or find to list candidate files.
- In dry_run mode, prints the file list and a sample patch for 2 files.
- In apply mode, uses a safe tool (e.g. sd/perl/node script) to
prepend the header if missing.
Describe the workflow in detail, including the exact commands.
Do NOT run anything yet.
Step 2: review and tighten the proposal
Scrutinise the proposed commands. Key things to look for:
- File glob scope (
apps/billing/**/*.ts, not **/*.ts).
- Use of
--max-count or batching to stay under file limits.
- No
rm or mv unless absolutely necessary.
Then reply:
User
Tighten scope to only:
- apps/billing/src/**/*.ts
- apps/billing/src/**/*.tsx
Show the exact final commands you will run in:
1) dry_run mode
2) apply mode
Then stop.
Step 3: run dry‑run mode only
User
Run the workflow in DRY-RUN mode now with:
- target_glob = "apps/billing/src/**/*.{ts,tsx}"
- dry_run = true
After running, output:
- Total files that WOULD be changed.
- First 20 file paths.
- A sample patch for 2 files.
Then stop and wait.
If the sample patches look correct and the file list is as expected, proceed.
Step 4: apply in limited batches
User
Apply the workflow in batches of at most 50 files.
After each batch:
- Show the list of files changed.
- Show one representative patch.
Stop after each batch and wait for my approval to continue.
After each batch, run git status and git diff locally and only then permit the next batch.
Stop/exit conditions:
- The total number of changed files matches Claude’s earlier dry‑run count (or is within an expected range).
- Randomly spot‑check a handful of files outside the target glob to confirm no accidental edits.
- Once all batches are done, stop using this workflow; do not leave it running unattended.
This pattern generalises to other bulk operations (e.g. simple codemods) and avoids the “48k files in seconds” class of risk by insisting on dry‑runs, first‑run confirmation, and explicit batch limits.
Workflow 5: large‑scope refactor sliced into per‑service runs
Goal: make a repo‑wide but conceptually unified change (e.g. API response envelope shape, feature flag system migration) without letting Claude operate across the entire monorepo at once.
Strategy: slice the work per service or package and treat each slice as a separate session with its own scan, plan, edit, and tests.
Step 1: human‑driven slicing
Using the manifest, choose a small number of services/packages per day. For example:
- Day 1:
apps/billing-api, apps/billing-worker.
- Day 2:
apps/web-frontend billing surfaces.
- Day 3: legacy cron jobs in
services/.
Each slice gets its own branch, e.g. refactor/billing-api-envelope, refactor/web-envelope.
Step 2: per‑slice workflow prompt
User
We are on branch refactor/billing-api-envelope.
Goal for THIS BRANCH ONLY:
- Update the billing API to return responses in the new envelope shape:
{ status: "ok" | "error", data: <payload>, error?: <details> }.
Scope for this session:
- Only files under apps/billing-api/ and shared DTOs/types used by that app.
- Do NOT touch other apps or services.
Constraints:
- Max 40 files changed.
- No git commit or push.
- Ask before writing any migration or helper scripts.
Because context may be compacted, you must:
- Start with a quick scan and summarise the current response shapes.
- Maintain a running summary of what you have changed so far.
First, propose:
- The files and directories you will inspect.
- A step-by-step plan with estimated files impacted per step.
Then stop.
Ensure the proposed plan stays within the slice; if it drifts, refine the constraints.
Step 3: enforce service‑local tests and summaries
For each step (e.g. “update handlers”, “update DTOs”, “update tests”):
User
Execute step 1 ONLY.
For each file you propose to change:
- Show the diff.
- Explain how it moves us toward the new envelope.
After applying step 1, run the billing-api test suite ONLY:
- commands: "cd apps/billing-api && pnpm test"
Paste only the failing test summaries here and propose fixes.
Limit this session to the billing API; frontend or other services should use new sessions with their own branches and constraints. This avoids partial migrations scattered across the repo.
Stop/exit conditions:
- All tests for the current service pass locally.
- A short human summary of the changes is written into
./docs/ai/refactors/envelope-billing-api.md.
- Commits on this branch are tagged with a clear prefix (e.g.
billing-api:).
Later, merge branches into a coordinating branch and run broader integration tests there, still without giving Claude direct CI access.
Workflow 6: Claude‑assisted review of Claude’s own changes
Goal: use a higher‑end model like Opus or Fable to review the diffs and test output produced by previous workflows, without re‑doing the heavy scanning.
Cost strategy: diffs and test logs are much smaller than full source, so using Opus at $5 input / $25 output per million tokens (Claude Platform, as of late 2026) is economically reasonable at this stage.
Step 1: prepare a compact diff and context bundle
From the local repo:
shell
git diff origin/main...HEAD > /tmp/current-diff.patch
# Optionally, re-run focused tests and save logs
pnpm test billing-subscriptions -- --runInBand > /tmp/billing-tests.log 2>&1
Open a new Claude Code (or Claude chat) session using Opus or Fable and paste in:
User
We are reviewing a diff produced by previous Claude Code workflows.
Context:
- Repo: large monorepo (details not important beyond what is in this diff).
- Branch: refactor/logger-structured.
- Tests: billing-subscriptions suite.
Task:
- Act as a senior reviewer.
- Identify risks, missing test coverage, and any places where behaviour may
have changed unintentionally.
I will now paste:
1) A high-level summary of the refactor.
2) The unified diff.
3) Relevant test logs.
You do NOT have access to the full repo, only this context.
First, acknowledge and wait until I have pasted all three parts.
Paste the human summary, diff, and truncated test logs, then ask:
User
Now review.
Output:
- 5–10 concrete review comments.
- A checklist of additional tests or manual checks we should run.
- Any refactor smells (e.g. partial migrations, inconsistent patterns).
Keep the output < 700 words.
This stage provides a second opinion on the change while keeping token use on the more expensive model proportionally small.
Managing context compaction and session drift explicitly
Anthropic’s prompt‑engineering and compaction documentation notes that conversations can be compacted—summarising earlier turns to stay within token limits—and separate engineering analysis from April 2026 ties some Claude Code quality regressions to changes in how session state and reasoning history were managed, since fixed in version v2.1.116.
The workflows above incorporate that guidance by design:
- Short sessions with explicit goals: each session handles a bounded task, not an open‑ended refactor across the whole repo.
- Model‑aware instructions: prompts tell Claude that context may be compacted and require it to maintain its own short running summaries.
- Externalised state: manifests and feature summaries live in
docs/ai/, outside the model’s ephemeral memory, and are re‑fed into new sessions.
Whenever Claude starts forgetting earlier constraints (e.g. trying to touch CI scripts after being told not to), treat that as a signal to end the session and start a new one with a fresh, concise summary.
When this Claude Code workflow approach is the wrong tool
The decision to treat Claude Code as a local, high‑context pair programmer with tight guardrails flips in a few scenarios.
- You want autonomous CI behaviour: if the requirement is for agents to mutate branches automatically inside GitHub Actions, build with a sandboxed CI harness such as HarnessAgent‑style patterns. Those architectures assume CI‑level permissions and use proof‑gated checks that this article explicitly avoids.
- Your repo is tiny and disposable: for small greenfield apps that fit easily in a single context window and carry low risk, the overhead of manifests, per‑service branches, and multi‑stage workflows may not pay off. Lighter inline tools like Cursor or GitHub Copilot can be faster.
- You mainly need inline completions: if most work is editor‑local micro‑edits, keep Cursor, Copilot or JetBrains AI Assistant as the primary tool and reserve Claude Code for episodic large‑scale changes using the workflows above.
- You need centralised audit logs: organisations that must log every AI action on core repos may prefer Claude Enterprise with API‑based harnesses and explicit logging, or an alternative like Amazon Q Developer for AWS‑centric workflows.
How these workflows reduce risk and cost in large repos
The workflows are designed around the following thesis: Claude Code is most useful on large, long‑lived codebases when it is constrained to a local surface and driven through repeatable phases rather than left to run open‑ended.
Anthropic’s Sonnet 5.5 model overview lists the official per‑million‑token pricing used in this article’s cost comparisons.
Anthropic’s large‑codebase guide emphasizes creating manifests and relying on language‑server‑based code intelligence, backing the recommendation to start every big‑repo session by refreshing a manifest.
- Risk reduction: By banning CI/production access, requiring manifest‑driven scanning, using dry‑run dynamic workflows, and limiting batch sizes, the chance of a catastrophic event like a mass file deletion drops sharply.
- Cost control: Front‑loading understanding on Sonnet and using short, goal‑bounded sessions avoids paying repeatedly to re‑prime long histories. Reserving Fable/Opus for final diff reviews leverages their strengths where the token volume is smallest.
- Large‑repo fit: Manifests, per‑feature summaries, and per‑service refactor slices compensate for context limits and the compaction behaviour Anthropic documents, making Claude Code practical in codebases that dwarf a single context window.
Used this way, Claude Code behaves less like an uncontrollable agent and more like a powerful but tightly supervised teammate, capable of handling wide‑ranging changes in large repos while staying inside a safety perimeter that can be trusted.