Claude Code Configuration, Workflows, and Advanced Prompting Guide

Claude Code Configuration Architecture and the CLAUDE.md Hierarchy

Claude Code relies on hierarchical instruction files named CLAUDE.md to establish project standards, workflows, personal working styles, and architectural decisions. Rather than treating instructions as a single monolithic prompt, configuration is structured across a three-level hierarchy that cascades from the user level down to specific subdirectories.

The highest level is the user-level configuration located at ~/.claude/CLAUDE.md. This configuration applies strictly to an individual developer's environment, is never tracked or shared through Version Control Systems (VCS), and is designated for personal working style preferences and local overrides. The second tier is the project-level configuration, which exists either as .claude/CLAUDE.md or as a root-level CLAUDE.md. Managed and shared via VCS, the project-level file applies to every project contributor and defines repository-wide coding standards, testing standards, and high-level architectural decisions. A frequent operational error occurs when a new team member fails to receive project instructions because the conventions were placed in the user-level ~/.claude/CLAUDE.md instead of the project-level .claude/CLAUDE.md. The third tier consists of directory-level CLAUDE.md files placed in individual subdirectories. These files apply only when the agent works with files situated within that specific directory tree, making them ideal for housing subsystem-specific guidelines.

Modular Configuration and @path File Import Syntax

To prevent configuration files from becoming bloated and redundant, CLAUDE.md supports modular file imports using the @path syntax. Referencing external files directly exposes necessary project documentation, architectural constraints, and package definitions to the agent.

# Project CLAUDE.md

Coding standards are described in @./standards/coding-style.md
Test requirements are in @./standards/testing-requirements.md
Project overview is in @README.md and dependencies are in @package.json

This import mechanism provides a distinct resource advantage by furnishing an immediate conceptual map of project resources, API references, internal guides, and task summaries. Consequently, the agent does not need to execute costly exploratory tool calls simply to understand what context exists. Syntactically, the @ character must be placed immediately before the file path without an intervening space. The syntax accommodates both relative and absolute paths, resolving relative paths in relation to the specific file containing the import statement. To prevent circular dependencies and excessive context degradation, the maximum allowed import nesting depth is strictly set to 5. This modular design eliminates content duplication while ensuring each package or component inherits only the standards relevant to its operational context.

Scoped Rule Management via the .claude/rules/ Directory

The .claude/rules/ directory serves as an alternative to an unwieldy, monolithic CLAUDE.md by partitioning guidelines into discrete, topic-oriented markdown files. A typical organization includes dedicated rule sets for subsystems and protocols, such as testing.md for testing conventions, api-conventions.md for interface standards, deployment.md for deployment procedures, and react-patterns.md for UI framework patterns.

The core functionality of .claude/rules/ relies on YAML frontmatter incorporating a paths key to enable conditional rule loading. Rather than consuming tokens continuously, a given rule file is injected into the context window only when Claude Code edits a file matching the designated glob pattern:

---
paths: ["src/api/**/*"]
---

For API files, use async/await with explicit error handling.
Each endpoint must return a standard response wrapper.
---
paths: ["**/*.test.tsx", "**/*.test.ts"]
---

Tests must use describe/it blocks.
Use data factories instead of hardcoding.
Do not mock the database—use a test database.

Conditional rule loading saves substantial context-window capacity and reduces token expenditure by keeping non-relevant instructions unloaded. Glob patterns enable the agent to apply uniform standards across specific file extensions regardless of where they reside within the project directory structure, making it the ideal solution for globally distributed test suites. When choosing between .claude/rules/ with paths frontmatter and directory-level CLAUDE.md files, .claude/rules/ is best suited for cross-cutting conventions that span multiple directories (such as tests or database migrations), whereas directory-level CLAUDE.md files should be reserved for strict local rules tied exclusively to an isolated component.

Custom Slash Commands and Skills Architecture

Slash commands provide reusable, parameterized prompt templates invoked directly within a session via /name. While custom commands were historically stored in .claude/commands/ (such as review.md generating /review for standard code reviews and test-gen.md generating /test-gen for automated test suite creation), recent implementations unify custom commands with the skills framework housed under .claude/skills/. Both structural formats create functional /name commands, and legacy .claude/commands/ directories remain fully supported.

Project commands and skills defined in repository paths (.claude/commands/ or .claude/skills/) are committed directly to VCS. This distribution guarantees that every engineer cloning the codebase receives identical, reliable operational workflows. Conversely, user commands configured in home directories (~/.claude/commands/ or ~/.claude/skills/) remain uncommitted, personal templates tailored to individual developers. To prevent naming collisions or overwriting team workflows, personal commands should utilize distinct naming identifiers.

Skills enhance standard slash commands by introducing advanced frontmatter parameters in a SKILL.md file (such as .claude/skills/review/SKILL.md or .claude/skills/test-gen/SKILL.md):

---
context: fork
allowed-tools: ["Read", "Grep", "Glob"]
argument-hint: "Path to the directory to analyze"
---

Analyze the code structure in the specified directory.
Output a report on dependencies and architectural patterns.

The context: fork parameter runs the execution of the skill inside an isolated subagent so that lengthy, verbose tool outputs do not flood the main conversational session. The allowed-tools parameter restricts the subagent to an explicit tool whitelist, serving as a critical security boundary that prevents unauthorized side effects such as unintended file modifications or deletions. The argument-hint parameter prompts the user for required inputs when the command is called without explicit parameters. Architecturally, skills are employed for on-demand execution of specialized, episodic tasks (code review, architectural reporting, code generation), while CLAUDE.md is reserved for persistent, always-active project standards.

Execution Strategies: Planning Mode versus Direct Execution

Complex tasks require distinct cognitive strategies to avoid catastrophic regressions. Claude Code provides two primary execution modalities: Planning Mode and Direct Execution.

In Planning Mode, the model explores the codebase without making destructive changes or writing to the disk. By deploying read-only discovery tools—specifically Read, Grep, and Glob—the agent performs deep contextual reconnaissance and constructs an end-to-end implementation plan that must be explicitly reviewed and approved by the developer. This mode provides a risk-free exploration vector designed for large initiatives spanning dozens of files, decisions regarding microservice boundaries, framework selections, architectural refactors, unfamiliar codebases, or complex library migrations affecting 45 or more files.

Direct Execution bypasses exploratory planning in favor of immediate code alteration. It is optimal for unambiguous tasks with low blast radiuses, such as single-file bug fixes with explicit stack traces or the addition of straightforward validation assertions. In practice, mature development workflows utilize a combined approach: initiating planning mode for architectural reconnaissance and solution design, obtaining developer sign-off on the generated specification, and transitioning to direct execution for implementation. Context preservation is further augmented by the Explore Subagent, which conducts extensive codebase inquiries in isolation and returns only an executive summary, preserving context-window limits across multi-phase workflows.

Context Lifecycle and Session Memory Commands

Long-running engineering sessions inevitably accumulate substantial tool execution history, which degrades model performance and consumes the context window. Claude Code incorporates two native commands to regulate conversational memory: /compact and /memory.

The /compact command compresses session context by condensing conversation logs, clearing obsolete tool outputs, and freeing up tokens. While invaluable during protracted debugging sessions, /compact presents the risk of losing exact numerical figures, critical dates, and fine-grained codebase specifics during aggressive summarization.

The /memory command governs cross-session persistence by providing interactive access to edit CLAUDE.md. Notes, project conventions, frequently referenced terminal commands, user preferences, and evolving working context recorded through /memory persist across disconnected sessions and are automatically loaded upon process startup. This capability removes the requirement to manually repeat global instructions at the beginning of each interactive session.

Headless Automation and CI/CD Pipeline Integration

Claude Code supports non-interactive execution within continuous integration and continuous deployment (CI/CD) pipelines using the headless execution flag -p (or --print). When invoked with -p, Claude processes the provided prompt, outputs the result to standard output (stdout), and terminates immediately without pausing for interactive terminal input:

claude -p "Analyze this pull request for security issues"

To integrate headless runs into automated verification pipelines, output can be formatted and validated against a schema using --output-format json alongside --json-schema:

claude -p "Review this PR" --output-format json --json-schema '{"type":"object",...}'

Emitting machine-readable JSON permits downstream scripts to parse the payload and automatically post inline pull request comments. From an architectural perspective, automated reviews must enforce session context isolation. A Claude session that generated a given pull request should never review that same pull request; the model retains its own reasoning traces and exhibits bias against challenging its own output. Employing a freshly instantiated, independent instance ensures rigorous code review. Furthermore, when re-evaluating pull requests across subsequent commits, historical review outputs must be supplied in the context with explicit instructions to report only unresolved or newly introduced deficiencies, avoiding duplicate commentary.

Session Persistence and State Branching

State persistence across developer workflows is managed through session resumption and session branching. A named working session can be retrieved using the --resume flag:

claude --resume investigation-auth-bug

Resuming a named session allows developers to maintain investigative continuity across multiple working sessions. However, resuming carries the risk of stale tool outputs if the underlying codebase has experienced local file edits or Git branch switches since the last execution. If substantial file alterations have occurred or context quality has degraded, developers should start a new session initialized with a brief synthetic summary of prior discoveries rather than resuming against outdated state.

Session branching is accomplished via the fork_session primitive. Branching clones the entire conversation history up to the execution point, providing identical context to two separate tracks that diverge independently:

Codebase investigation
       |
  fork_session
   /        \
Approach A: Approach B:
 Redux       Context API

This architecture empowers developers to branch an investigation into competing implementation strategies—such as evaluating state management using Redux versus the Context API—without polluting the original session context or cross-contaminating alternative approaches.

Advanced Prompt Engineering: Few-Shot Prompting

Few-shot prompting involves injecting 2 to 4 concrete input/output demonstration pairs directly into a prompt before requesting execution on a target task. Rather than relying entirely on descriptive system instructions, examples demonstrate the exact expected behavior, formatting, and structural output.

Few-shot examples consistently outperform abstract text instructions. Vague guidance (such as requesting that the model "be more precise") leaves room for subjective interpretation and inconsistent formatting. Presenting concrete demonstration pairs removes ambiguity, anchoring the model's output schema, tone, and underlying decision logic to the reference examples.