Claude Code Project Context for Safer, Faster Refactors

Dan Greer · · 6 min read

Part of the Claude Code guide. Start with Claude Code Doesn't Understand Your Codebase? How to Fix It

How to give Claude Code better project context for safer, faster refactors

A permission check can occupy three lines and still need a refactor plan that reaches into an API and the web app. In the captured cal.diy results below, checkAdminOrOwner appears in an auth utility, its callers include application services, and the impact query reaches two HTTP endpoints.

That's the project context I want before asking Claude Code to edit a shared helper. The definition is a start. I also need the rules around it, the callers that depend on its contract, the source revision those relationships describe, and a way to check the proposed change.

What project context needs to tell Claude

Claude Code can read source, search the checkout, run commands to investigate, and execute tests. Anthropic describes those capabilities in how Claude Code works.

For a refactor, I separate instructions from evidence. Instructions say which behavior must survive, where edits belong, which commands count as verification, and which boundaries need an explanation before crossing them. Evidence comes from inspecting the implementation and tracing its consumers.

An instruction to preserve a public signature helps. It doesn't establish who uses that signature.

For choosing between search, a source pack, or a graph, see how much repository context Claude needs.

CLAUDE.md: what belongs there, and where it stops

Anthropic's memory documentation describes CLAUDE.md as persistent instructions.

Those instructions are context, not enforced configuration.

Keep the operating rules close to the code

Put the actual build and test commands in the project instructions, explain the dependency boundaries your team enforces, identify generated files that need a generator rather than hand edits, and record corrections you keep having to repeat. Use commands copied from the repository's scripts or contributor documentation.

I wouldn't add a plausible-looking test command just to make the file feel finished. A command that names the wrong package wastes the verification step.

Claude loads instruction files from the working directory and its ancestors at launch. Nested instructions load when Claude reads, writes, or edits another file in that subtree, so a package-level file can carry its local conventions without repeating the root guidance. These files are combined; a nested file doesn't simply erase the parent's instructions.

Leave changing relationships out of the manual inventory

A hand-maintained caller list needs updating whenever those relationships change.

Anthropic's best-practices guide recommends concise CLAUDE.md files and excludes frequently changing information.

Keep the boundary rule in the file, then inspect the current imports and callers when the task needs them. If the rule says a package can't import another package, ask Claude to check that restriction against the proposed edits, explain any existing violation it encounters, and leave unrelated cleanup for a separate change.

Six steps before a refactor

1. Define the task boundary

Name the symbol or module and state what must stay true. For a permission helper, spell out whether the task may alter authorization behavior, change its arguments, affect type narrowing, or update consumers outside the owning package.

This is a suggested planning prompt, not a transcript of a completed change:

Prepare a refactor plan for checkAdminOrOwner.
Do not edit yet.
Preserve the current authorization behavior and type predicate.
Identify callers outside features/auth before proposing changes.
Separate required caller updates from optional cleanup.
Report unresolved references and the checks needed before editing.

If the proposed work changes who gets access, describe that behavior change explicitly. Don't hide it inside a cleanup request.

2. Load stable project rules

Check which instructions the session received before trusting a plan. Run /context and look under Memory files for the CLAUDE.md files loaded at launch.

A CLAUDE.md below the directory where you launched Claude loads on demand when Claude reads, writes, or edits a file there, and the terminal shows a Loaded line with its path. If two instructions conflict, settle which applies before editing, because Claude may otherwise pick one arbitrarily. Anthropic documents the command in its command reference.

claude starts an interactive session from the terminal. Launch it where you intend to work, name the allowed edits, keep distant consumers in the investigation, and explain when the change may cross a package boundary.

Record the verification commands before editing. If the repository has no documented command for an affected area, have Claude investigate that gap and report it.

3. Narrow the reading scope without losing consumers

Start with the target implementation and its local rules, follow references into the callers that matter, inspect those callers' assumptions, and expand the proposed edit scope only when the change requires it. Keep the distinction visible between files inspected and files you intend to modify.

In a cal.diy checkout, this searches the two source trees for the permission-check name:

rg -n 'checkAdminOrOwner' apps packages

rg searches text and can print matching line numbers. A match might occur in a definition, a re-export, a call, or a string, so open the matches before assigning them a role. The ripgrep documentation describes its search behavior.

For a rename, keep tests and string references in the investigation too. A production caller list and a list of files requiring a text update answer different questions.

The guide for working in a large repository or monorepo covers the wider scoping problem.

4. Inspect dependencies and blast radius before editing

I build Pharaoh, a hosted MCP service that supplies a structural repository map.

Its knowledge-graph explanation covers the representation. Here I want a result that points to the next source file to inspect.

This pre-refactor walkthrough combines saved hosted-tool results for cal.diy, the Pharaoh-so/cal.diy fork, at revision 54343aa6, without claiming an execution order. Whole lines were trimmed from the capture. The remaining lines are unchanged.

search_functions locates the declaration:

# Search Results: "checkAdminOrOwner" (showing 1-5)

- function checkAdminOrOwner(role: MembershipRole | null | undefined): role is "OWNER" | "ADMIN" [exported, complexity: 2]
  packages/features/auth/lib/checkAdminOrOwner.ts:3-5 (features/auth)

get_unused_code, queried for this function, returns an entry path:

# Reachability in cal.diy

- checkAdminOrOwner (packages/features/auth/lib/checkAdminOrOwner.ts): reachable: getAtomEventTypeApp → getEventTypesAppIntegration → checkAdminOrOwner

That path gives the refactor a concrete consumer to investigate. Open the controller and service, inspect how the role reaches the helper, check what the caller assumes after the predicate succeeds, and decide whether the proposed edit preserves those assumptions.

The depth-three get_blast_radius result also reaches other consumers. This trimmed excerpt retains the original total-callers heading, while showing only selected caller lines:

# Blast Radius: checkAdminOrOwner (function, 3 hops)
## Affected Callers (14)
### api/v2
- apps/api/v2/src/modules/atoms/controllers/atoms.event-types.controller.ts: AtomsEventTypesController.getAtomEventTypeApp (2 hops)
- apps/api/v2/src/modules/atoms/services/event-types-atom.service.ts: EventTypesAtomService.getEventTypesAppIntegration
### app-store/_utils
- packages/app-store/_utils/getConnectedApps.ts: getConnectedApps
## Affected Endpoints (2)
- GET /v2/atoms/conferencing
- GET /v2/atoms/event-types-app/:appSlug

The query identifies an inspection scope. Whether a caller needs an edit depends on what you change.

The permission-check change-impact study follows the longer investigation and reports its measurement limits. For a refactor, use the blast-radius guide to walk each caller group, mark the files you plan to edit, note the consumers you only need to verify, and keep uninspected paths visible in the plan.

There are limits to carry into the plan. Pharaoh's interactive graph describes its last completed default-branch map, it doesn't cover uncommitted edits, it doesn't cover an unmerged branch, and blast-radius results exclude test-file callers. Compare the map with the checkout before relying on a returned path, then investigate tests separately.

5. Give Claude a verification loop

Choose checks from the affected behavior. For this permission-check example, ask for cases covering the accepted roles, a rejected role, a missing role, and the callers' type assumptions before deciding which existing tests to run or extend. These are proposed checks, not results from the captured investigation.

Require Claude to report the command and result for each check it runs.

Anthropic's verification advice recommends giving the agent checks it can execute, including tests and builds.

rg can help locate test references that the production blast-radius query leaves out. Read those tests before treating their existence as coverage of the behavior you're changing.

The broader code impact-analysis workflow covers selecting checks across consumers.

Keep the final report explicit about failures and checks that weren't run.

6. Compact or reset when the session drifts

Before starting a separate refactor, save the agreed scope, the relevant source paths, the map revision if you used one, and the unresolved verification work. That gives you something concrete to compare with the next plan.

Run /compact with focus instructions that name the details you want preserved, then read the summary it leaves and compare it with your task notes.

Use /clear for a fresh conversation with empty context. Both commands appear in Anthropic's command reference.

Neither command establishes that an earlier dependency assumption is still correct. Recheck the evidence when the code has changed.

Connect the map when relationship tracing is the work

For supported TypeScript, JavaScript, Python, C and C++ repositories, Pharaoh maps repository structure and makes it available to the agent over MCP. JavaScript files are included within its TypeScript support.

After installing the GitHub App, the Claude Code setup command is:

npx @pharaoh-so/mcp

Use the setup command to connect Claude Code and sign in with GitHub. npx runs the package's command.

The Claude Code connection guide covers the flow. npm documents how npx executes package commands.

claude mcp list shows configured servers and their status. Use /mcp inside the session to inspect connection status.

claude mcp get <name> displays details for a configured server. Anthropic's MCP documentation covers these commands.

A live repository re-maps after pushes to its default branch. Use pharaoh_account to request a refresh when needed.

The graph holds structural metadata rather than source-file bodies. A free workspace has one live repository.

To try the process, connect one repository, pick a helper you already intend to refactor, ask for its callers, and follow a returned path in source before writing down the checks it requires.

More in Claude Code

← Back to blog