AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Software Engineers Use Claude Code in the Terminal to Navigate Large Codebases, Execute Multi-File Refactorings, and Fix Bugs Autonomously

白川裕亮 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

IDE sidebar assistants have hit a architectural ceiling. If you maintain a legacy monorepo or a service with hundreds of thousands of lines of code, you already know the routine: manually locating five interconnected files, copying stack traces into a tiny chat panel, begging the model not to hallucinate imports, and manually pasting diffs back into your editor. It is tedious context-shuttling disguised as modern AI assistance.

365Finds has evaluated AI development tooling across every major paradigm, and our position is unequivocal: for complex architectural work, chat sidebars are obsolete. Anthropic’s Claude Code shifts the entire locus of control to the local terminal. Operating directly inside your shell, Claude Code acts not as an autocomplete widget, but as an autonomous agentic harness. It navigates repository topology, plans multi-file edits, executes verification test suites, and commits clean git history without requiring you to act as a human copy-paste buffer.

Yet unleashing an agent with shell access in a massive production codebase without rigorous constraints invites catastrophe. Below is the operational playbook for engineering teams using Claude Code to explore massive trees, execute sweeping refactorings, and fix bugs autonomously—safely.


1. The Terminal Agent Harness: How Claude Code Actually Works

Most developers misunderstand Claude Code as another CLI wrapper around an LLM API. It is fundamentally different. Claude Code is an agentic harness running an adaptive loop across three tightly coupled phases:

  1. Context Gathering: Claude inspects directory structures, checks git status, evaluates project instructions, and uses file-search tools (Glob, Grep, and language server protocols) to map the codebase.
  2. Action Execution: Claude edits files in place, runs shell commands, generates boilerplate, or spawns subagents for isolated research.
  3. Dynamic Verification: Claude executes local build systems and test suites (npm test, pytest, cargo test), parses stderr and stack traces, determines if its modification solved the problem or broke downstream invariants, and self-corrects before handing control back to you.
+-------------------------------------------------------------+
|                     User Prompt / Goal                      |
+-------------------------------------------------------------+
                              |
                              v
                  +-----------------------+
            +---->|   Gather Context      |
            |     | (Glob, Grep, LSP, @)  |
            |     +-----------------------+
            |                 |
            |                 v
            |     +-----------------------+
            |     |   Take Action         |
            |     | (File Edit, Bash Run) |
            |     +-----------------------+
            |                 |
            |                 v
            |     +-----------------------+
            |     |   Verify Results      |
            +-----| (Test Suite, Linter)  |--[Fails / Incomplete]--+
                  +-----------------------+                        |
                              |                                    |
                       [Passes / Goal Met]                         |
                              |                                    |
                              v                                    v
                  +-----------------------+             [Iterate Agent Loop]
                  | Git Commit / PR / Done|
                  +-----------------------+

Because Claude operates in the terminal session, it shares your environment: environment variables, package managers, local database containers, and compiler toolchains.

At 365Finds, what impresses us most is that Claude Code is interruptible. You do not wait passively for a runaway agent. If you hit Esc, Claude instantly cancels the running tool call and yields control. If you type a correction while it works and press Enter, Claude queues your message, absorbs it immediately after the current tool execution, and alters its plan mid-flight.


2. Navigating Massive Codebases Without Context Window Rot

The biggest failure mode in large repositories is context pollution. A single naive recursive file read or grepping through a bundled vendor directory can instantly burn hundreds of thousands of tokens, triggering premature context compaction and degrading the model’s reasoning.

To navigate repositories with hundreds of packages or millions of lines, you must configure a strict context hierarchy.

Layered Architecture Guidance: The CLAUDE.md Hierarchy

Do not cram your entire team wiki into a 2,000-line root file. Claude Code automatically ingests CLAUDE.md (or AGENTS.md) at launch, appending its contents directly to initial prompt context. Anthropic recommends keeping the root file under 200 lines, reserved strictly for universal repo conventions:

# Repository Architecture & Core Rules
- Package Manager: Always run pnpm from workspace packages, never root.
- Commits: Follow Conventional Commits format (e.g., `feat(api): add auth token revoke`).
- Safety: Never touch files inside `packages/*/generated/`. Run `pnpm codegen` instead.
- Tests: Fast verification via `pnpm test:unit`. End-to-end suite requires `docker-compose up -d db`.

For large codebases and monorepos, layer secondary CLAUDE.md files inside specific directories (e.g., packages/api/CLAUDE.md and packages/web/CLAUDE.md). When you start Claude inside a subdirectory, it loads both the local and ancestor instructions. When started at the root, Claude loads subdirectory CLAUDE.md files on demand only when a tool call touches files in that folder.

Aggressive Read Denials and Exclusions

Never allow Claude to read generated code, build artifacts, or vendored dependencies. While Claude Code respects .gitignore for content searches, explicit Read deny rules in .claude/settings.json prevent Claude from opening massive files that exhaust context:

{
  "permissions": {
    "deny": [
      "Read(./**/dist/**/*)",
      "Read(./**/build/**/*)",
      "Read(./**/*.generated.*)",
      "Read(./**/vendor/**/*)",
      "Read(./**/*.min.js)"
    ]
  },
  "claudeMdExcludes": [
    "**/packages/legacy-crm/**"
  ]
}

Ending directory patterns with /**/* ensures Claude can still inspect directory structure (ls dist) without dumping binary or bundled blobs into the token stream.

Language Server Plugins vs. Brute-Force Grep

In codebases with thousands of modules, finding symbol definitions via regex scanning is slow and token-expensive. Claude Code supports native Language Server Protocol (LSP) plugins through its official plugin marketplace:

claude
# Inside session:
/plugin install typescript-lsp@claude-plugins-official

With code intelligence active, Claude jumps straight to symbol declarations, callers, and interface implementations across packages using exact compiler symbols, reducing file-read token overhead by up to 80% during architecture discovery.

Delegating Reconnaissance to Subagents

When you need an answer to an exploratory question—such as "How does the session invalidation pipeline propagate to Redis across all backend workers?"—do not let Claude run raw file reads in your main context.

Instruct Claude explicitly:

use a subagent to trace session invalidation from the API gateway to Redis, and report back only the architectural summary and file list

The subagent spins up an isolated context window, reads dozens of files, performs searches, and returns a concise brief to your main session. Your primary context stays pristine.


3. Executing Multi-File Refactorings Without Regressions

Refactoring legacy systems across ten or fifteen interconnected files is where single-file LLM assistants consistently fail: they introduce subtle signature mismatches, break transitive type dependencies, or hallucinate imports.

Claude Code provides the exact mechanical workflow required for multi-file surgical refactoring.

Phase 1: Enforce Plan Mode

Never let an autonomous agent modify files on disk during initial analysis. Before initiating a refactoring, enter Plan Mode:

claude --permission-mode plan

(Or press Shift+Tab inside an active session until ⏸ plan mode on appears in your status bar.)

In Plan Mode, Claude has full access to search and read tools, but any disk modification is hard-blocked. Provide your refactoring directive:

We are migrating our legacy database access layer from raw SQL strings in packages/api/src/repositories/ to Prisma clients.
1. Identify all repository files using raw queries.
2. Formulate a step-by-step refactoring plan maintaining existing interface signatures.
3. List all files requiring edits and potential breaking changes in shared types.

Claude will inspect the files, draft a comprehensive sequence of edits, highlight risks, and present the plan. You can edit the plan directly or instruct Claude to adjust details before writing a single line of code.

Phase 2: Atomic Execution with File Snapshots

Once you approve the plan, switch the permission mode (Shift+Tab to Manual or Auto). Claude executes edits across the target files sequentially.

Crucially, Claude Code maintains native checkpoints. Prior to editing any file on disk, Claude takes a local filesystem snapshot independent of git. If an edit sequence goes sideways or Claude hallucinates an unwanted architectural change:

Phase 3: Parallel Sessions via Git Worktrees

If you are undertaking a multi-hour refactor but still need to handle an urgent bugfix on main, do not context-switch your working directory. Claude Code integrates natively with git worktrees:

claude --worktree refactor-prisma-migration

Claude creates an isolated branch and worktree directory. For monorepos where checking out every package is expensive, configure sparse checkout paths in .claude/settings.json:

{
  "worktree": {
    "sparsePaths": [
      ".claude",
      "packages/api",
      "packages/shared"
    ],
    "symlinkDirectories": [
      "node_modules"
    ]
  }
}

This checks out only the relevant subtrees and symlinks node_modules, keeping disk consumption negligible while ensuring parallel Claude sessions never clobber each other's unstaged files.


4. Autonomous Bug Fixing with Test-Driven Verification (TDD)

The true differentiator between a chatbot and an engineering agent is closed-loop dynamic verification. Anyone can generate code that looks plausible; an engineering agent must prove it compiles and passes tests before claiming victory.

The Standard TDD Debugging Directive

When troubleshooting a production defect or failing test, 365Finds recommends providing Claude Code with the exact reproduction command rather than describing the bug abstractly:

The payment webhook handler is intermittently dropping Stripe checkout events.
1. Run `pnpm test packages/api/src/webhooks/__tests__/stripe.test.ts` to inspect current assertions.
2. Write a new failing test case reproducing dropped events when `event.data.object.metadata` is undefined.
3. Inspect `stripeHandler.ts`, implement the fix to handle missing metadata safely, and verify that all tests pass.
4. Run the full linter and type-checker: `pnpm check`.

Claude executes the test suite, parses the failure, opens the relevant handler, injects defensive deserialization, and re-runs the test suite. If the test still fails, Claude reads the new error message, revises its implementation, and loops autonomously until the suite greenlights.

Safe Execution Governance: Permission Whitelisting

By default, Claude Code pauses to ask for terminal execution approval. Approving twenty consecutive pnpm test calls destroys developer flow; conversely, enabling unconditional shell execution without safeguards is dangerous.

Configure permission allowlists in .claude/settings.json:

{
  "permissions": {
    "allow": [
      "Bash(pnpm test*)",
      "Bash(pnpm lint)",
      "Bash(pnpm check)",
      "Bash(git status)",
      "Bash(git diff*)"
    ]
  }
}

Safe, read-only, and verification commands execute automatically without interruption. Any destructive action—rm -rf, schema migrations, branch deletions, or pushing to remote—triggers an explicit prompt or gets intercepted by Claude Code's background safety classifier.


5. Clean Git Hygiene and Pull Request Automation

A persistent engineering anxiety regarding AI tools is "git pollution"—sloppy commits, noisy diffs, and AI attribution tags cluttering commit histories. Claude Code provides complete configuration over git workflows.

Structured Conventional Commits

Once verification passes, Claude can draft atomic commits respecting team style:

Review git status and git diff, stage only the modified files in packages/api, and commit with a clean Conventional Commit message explaining the root cause of the webhook bug.

If you prefer to disable Claude Code’s default attribution footers (Co-Authored-By: Claude <noreply@anthropic.com>) or internal git instructions, add these settings to .claude/settings.json:

{
  "attribution": false,
  "includeGitInstructions": false
}

Pull Request Generation and Session Linking

Claude Code interfaces with GitHub CLI (gh) and GitLab CLI (glab). Once your branch is tested and committed:

create a pr against main with a comprehensive summary of changes, breaking risk assessment, and verification steps

Claude pushes the branch and invokes gh pr create. When your teammate reviews the PR and requests adjustments, you can resume that exact Claude Code context days later using the PR number:

claude --from-pr 412

Claude reopens the session tied to the PR, loads the prior conversation, and allows you to address reviewer comments with complete architectural memory intact.


6. Comparison: Traditional IDE Assistant vs. Terminal Claude Code

DimensionIDE Sidebar Assistant (e.g., Copilot Chat)Terminal Agent Harness (Claude Code)
Context ScopeCurrent active editor tab + manual @-mentionsEntire repository topology, git state, and environment
Command ExecutionNone or sandboxed chat snippets requiring manual runFull interactive terminal execution with permission rules
Multi-File RefactoringGenerates disconnected code blocks for manual copy-pasteAutonomously edits multiple files sequentially with checkpoints
Verification LoopPassive; user must paste errors back into chatActive; agent runs tests, parses stack traces, and self-corrects
Context ManagementStatic window; prone to truncation on large pastesDynamic subagents, layered CLAUDE.md, and auto-compaction
Safety & ReversibilityManual IDE undo (Ctrl+Z) per fileNative double-Esc file checkpoints independent of git

7. The 365Finds Institutional Verdict

365Finds does not recommend Claude Code as an everyday syntax autocompleter. If you just need a boilerplate TypeScript interface or a quick regex helper while typing, an inline editor completion model is faster and causes less friction.

Claude Code is an engineering workstation. It is built for the tasks that senior engineers dread: modernizing an unmaintained subpackage, refactoring a cross-service authentication interface across 14 files, chasing a flaky concurrency bug through integration tests, or auditing architectural drift in a massive monorepo.

To adopt Claude Code effectively:

  1. Never skip CLAUDE.md: Run /init on day one, curate it under 200 lines, and split subsystem rules into subdirectory files.
  2. Never refactor without Plan Mode: Formulate the sequence before touching disk.
  3. Always give Claude a test command: An agent without automated verification is just an opinionated text generator.

In 365Finds' assessment, teams that treat Claude Code not as a magical code generator, but as a junior systems engineer operating inside a strictly bounded, test-driven terminal sandbox, achieve a 3x to 5x reduction in cycle time on legacy maintenance and architectural migrations.

Claude Code requires Node.js 18+ or the standalone installer (curl -fsSL https://claude.ai/install.sh | bash), and an authenticated Anthropic account with console API credits or a Claude Pro/Team/Enterprise subscription.

References