Claude Code Directory Architecture: .claude, Rules & Subagents
Claude Code embeds an autonomous reasoning engine directly into your terminal and IDE workflows. However, scaling an agent across a team requires a structured configuration architecture. Without clear project conventions, agents suffer from context rot, instructional drift, and unauthorized tool execution.
The .claude/ directory structure and associated configuration files (CLAUDE.md, .mcp.json, settings.json, rules/, skills/, agents/, workflows/, and agent-memory/) establish the foundational operating environment for Claude Code. For foundational concepts, explore our Claude Code overview guide and Claude Code concepts guide. This architectural reference explores every configuration layer, explaining how project-level and global configurations interact, how path-gated rules optimize context consumption, and how to structure reusable skills, subagents, and memory systems for deterministic engineering.
Project-Level (.claude/) vs. Global (~/.claude/) Configuration Hierarchy
Claude Code employs a layered configuration system that strictly separates team-shared repository standards from individual developer preferences. Understanding this boundary is essential for maintaining consistent CI/CD pipelines and team conventions while preserving local flexibility.
The Two Configuration Spheres
1. Project-Level Configuration (<project-root>/.claude/ and root files):
- Shared Source of Truth: Committed directly to version control (git), ensuring every engineer and CI runner shares identical project rules, allowed tools, MCP servers, and subagent capabilities.
- Files: CLAUDE.md, .mcp.json, .worktreeinclude, .claude/settings.json, .claude/rules/, .claude/skills/, .claude/agents/, .claude/workflows/, and .claude/agent-memory/.
- Local Overrides: .claude/settings.local.json remains gitignored, allowing developers to configure machine-specific paths, private tokens, or custom permission bypasses without polluting team settings.
2. Global Configuration (~/.claude/ in the user's home directory):
- Personal Machine Environment: Applies universally across all projects on a developer's workstation. These settings configure global keyboard shortcuts, UI themes, custom output styles, and personal utility skills.
- Files: ~/.claude/CLAUDE.md, ~/.claude/settings.json, ~/.claude/keybindings.json, ~/.claude/themes/, ~/.claude/output-styles/, ~/.claude/skills/, ~/.claude/agents/, and ~/.claude/workflows/.
Precedence and Resolution Order
When Claude Code executes a task, configuration settings are resolved using a specific hierarchy where more specific local scopes take precedence over broad global defaults:
Local Overrides (.claude/settings.local.json) $\rightarrow$ Project Settings (.claude/settings.json) $\rightarrow$ Global Settings (~/.claude/settings.json) $\rightarrow$ Built-in Engine Defaults.
Quick reference
- Project files committed to git ensure deterministic agent behavior across team members and automated CI environments.
- Use .claude/settings.local.json for sensitive keys, absolute environment paths, or temporary local debug flags.
- Global ~/.claude/ configurations are strictly machine-local and never checked into project source control.
- Settings precedence merges JSON structures hierarchically, with project-level values overriding global values on key collisions.
Remember this
Commit project standards to .claude/ for team consistency, keep personal preferences in ~/.claude/, and use settings.local.json for untracked local overrides.
Core Configuration Files: CLAUDE.md, .mcp.json, .worktreeinclude, and settings.json
At the foundation of every Claude Code project are four critical configuration files that govern instruction injection, protocol connectivity, git worktree isolation, and execution permissions.
1. CLAUDE.md: Project Memory and Conventions
CLAUDE.md sits at the project root (or inside .claude/) and is loaded into the agent's context window on every session initialization. It acts as the project constitution, establishing technology choices, coding standards, prohibited practices, and build verification commands:
1# Architecture & Technology Standards2- Framework: Next.js 16 App Router (RSC by default; leaf Client Components)3- Language: TypeScript 5.x with strict mode enabled4- Styling: Tailwind CSS v4 using CSS variable tokens in OKLCH5 6# Verification Commands7- Build: npm run build8- Unit Tests: npm run test9- Lint: npm run lint10 11# Prohibited Patterns12- Do not use Pages Router APIs (getStaticProps/getServerSideProps)13- Do not prefix private credentials with NEXT_PUBLIC_14- Never commit unformatted code or bypass ESLint2. .mcp.json: Model Context Protocol Servers
.mcp.json defines external tool integrations using the Model Context Protocol (MCP). It allows Claude to interface with databases, GitHub APIs, cloud infrastructure, or custom enterprise services:
1{2 "mcpServers": {3 "postgres": {4 "command": "npx",5 "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost:5432/db"]6 },7 "github": {8 "command": "npx",9 "args": ["-y", "@modelcontextprotocol/server-github"],10 "env": {11 "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"12 }13 }14 }15}3. .worktreeinclude: Multi-Worktree Isolation
When running parallel agents across multiple git worktrees, .worktreeinclude specifies which untracked or gitignored files (such as .env.local, local database sqlite files, or compiled binaries) must be copied into new worktrees during creation:
1.env.local2.env.development3prisma/dev.db4. settings.json: Permissions and Hooks
.claude/settings.json controls security guardrails, auto-approved commands, bash sandboxing, and execution lifecycle hooks (pre-commit, post-execution verification):
Quick reference
- CLAUDE.md is loaded on every session; keep it concise (< 300 lines) to preserve token budget for actual codebase reasoning.
- .mcp.json centralizes team toolchains so new contributors instantly inherit database and API inspection tools.
- .worktreeinclude prevents runtime crashes when spawning subagents into isolated git worktrees that need local environment files.
- settings.json enforces execution boundaries, preventing destructive terminal commands from running without human confirmation.
Remember this
CLAUDE.md defines coding standards, .mcp.json connects external toolchains, .worktreeinclude enables isolated worktrees, and settings.json locks down security permissions.
Modular Rules and Path Gating (.claude/rules/)
As codebases grow, packing every architectural requirement into a monolithic CLAUDE.md causes severe context rot—wasting thousands of prompt tokens on irrelevant rules and diluting the agent's attention.
Claude Code resolves this with Modular Rules located in .claude/rules/. Each rule is a standalone markdown file targeting a specific subsystem. Crucially, rules support Path Gating via YAML frontmatter: the rule is dynamically injected into the agent's context window only when the agent reads or modifies files matching specified glob patterns.
Structure of a Path-Gated Rule
Create .claude/rules/database-mutations.md:
1---2name: database-mutations3description: Strict rules for writing database migrations and queries4globs:5 - "src/lib/db/**/*"6 - "prisma/**/*"7 - "migrations/**/*"8---9 10# Database Mutation Rules111. All schema migrations must be backward-compatible (expand-and-contract pattern).122. Never execute raw DELETE statements without an explicit WHERE clause.133. Always create an index on foreign key columns.144. Sensitive credentials must never appear in migration scripts.How Path Gating Works in the Engine
When Claude works on a frontend React component (src/components/Header.tsx), the database rule remains inactive, saving prompt tokens. The moment Claude reads src/lib/db/users.ts or creates a migration, the engine automatically loads database-mutations.md into active context.
Quick reference
- Path gating eliminates context pollution by loading subsystem instructions only when relevant files are touched.
- Rule frontmatter supports array glob syntax (globs: ["src/app/", "src/routes/"]).
- Rules without glob frontmatter act as universal rules, loaded across all sessions.
- Use rules for specific concerns: API route design, security sanitization, test authoring conventions, and styling tokens.
Remember this
Path-gated rules in .claude/rules/ dynamically load subsystem instructions based on file paths, eliminating context rot while enforcing strict architectural boundaries.
Skills, Commands, and Orchestration Workflows
Claude Code provides three distinct mechanisms for packaging reusable prompts, deterministic procedures, and multi-step agent orchestrations: Skills, Commands, and Workflows.
1. Skills (.claude/skills/)
Skills are encapsulated capability bundles defined in subdirectories under .claude/skills/<skill-name>/SKILL.md. They contain YAML frontmatter, execution instructions, reference templates, and helper scripts. Users or agents invoke them on-demand via slash commands (e.g. /content-pipeline or /database-audit):
1---2name: api-contract-test3description: Generates and executes end-to-end integration tests for REST API endpoints4---5 6# API Contract Testing Workflow71. Inspect endpoint contract in src/app/api/82. Validate OpenAPI schema conformity93. Generate mock payload and assert HTTP status codes (200, 400, 401, 404, 500)104. Execute test suite via npm run test:api2. Commands (.claude/commands/ - Legacy)
Commands are single-file prompt templates (e.g. .claude/commands/refactor.md). While still supported for backward compatibility, modern Claude Code workflows prioritize Skills because skills support auxiliary reference documentation, test fixtures, and executable helper scripts alongside SKILL.md.
3. Workflows (.claude/workflows/)
Workflows are automated multi-phase procedures that orchestrate complex engineering tasks. Unlike single prompts, workflows execute structured state machines—directing subagents through planning, execution, verification, and rollback stages with deterministic exit gates.
Quick reference
- Skills support multi-file directory packaging (SKILL.md, reference.md, examples.md, and helper scripts).
- Skills can be invoked explicitly by users (/skill-name) or selected autonomously by reasoning subagents.
- Prefer skills over legacy commands for rich capability extensions.
- Workflows link multiple skills and subagents into structured, multi-phase delivery pipelines.
Remember this
Skills bundle reusable capabilities with helper assets, legacy commands provide single-file prompts, and workflows orchestrate multi-agent execution pipelines.
Subagents (.claude/agents/) and Persistent Memory (agent-memory/)
Large-scale software engineering tasks quickly saturate an agent's context window. Attempting to plan architecture, write code, run linters, and audit security within a single conversational thread leads to catastrophic context degradation.
Claude Code solves this with Subagents (.claude/agents/) and Persistent Memory (.claude/agent-memory/).
Subagents with Isolated Context Windows
Subagents are specialized child agents spawned to execute bounded tasks in clean, isolated context windows. Each subagent is defined in .claude/agents/<agent-name>.md with dedicated tool allowances and specialized system prompts:
1---2name: security-auditor3description: Scans pull requests and modified code for OWASP vulnerabilities and secret leaks4tools:5 - ReadFile6 - GrepSearch7 - RunCommand8---9 10You are an expert AppSec security engineer. Your sole task is auditing code changes for SQL injection, XSS, SSRF, broken authentication, and plaintext credential leaks. Output findings as a structured markdown audit report.When the primary agent delegates a security review, the security-auditor executes in a fresh context window, performs the scan, and returns a concise report to the primary agent—consuming almost zero main-thread context tokens.
Persistent Agent Memory (.claude/agent-memory/)
While subagents operate in isolated contexts, they often uncover insights that should persist across sessions (e.g. discovered database schema quirks, undocumented API rate limits, or slow test suites). .claude/agent-memory/ provides a durable, structured markdown storage layer where subagents read and write persistent domain knowledge across task lifecycles.
Quick reference
- Subagents prevent context window saturation by offloading deep specialized tasks to clean child threads.
- Tool scoping on subagents enforces least-privilege security (e.g. a reviewer agent cannot execute write or deploy commands).
- Agent memory (.claude/agent-memory/) enables long-term knowledge retention across independent agent executions.
- Subagents report structured summaries back to the orchestrator, preserving high-level context clarity.
Remember this
Subagents provide isolated context execution with least-privilege tool access, while agent-memory/ stores durable domain knowledge across sessions.
Production Best Practices, Security Boundaries, and Checklist
Deploying Claude Code across an engineering organization requires disciplined configuration management, strict security boundaries, and reliable git workflows.
Production Architecture Checklist
| Configuration Area | Recommended Practice | Failure Mode if Ignored |
| :--- | :--- | :--- |
| CLAUDE.md Size | Keep under 300 lines; offload specific rules to .claude/rules/ | Context window bloat, instructional dilution, higher token cost |
| Secret Management | Store secrets in .env.local; never inline credentials in .mcp.json | Accidental credential leakage in git history |
| Permission Scoping | Require manual approval for destructive commands (rm -rf, DROP TABLE) in settings.json | Irreversible production data loss during autonomous refactoring |
| Worktree Isolation | Use .worktreeinclude for parallel branches | Missing environment files causing failed local builds in subagent worktrees |
| Rule Path Gating | Define targeted globs in .claude/rules/*.md | Irrelevant subsystem instructions degrading prompt attention |
Production Failure Scenario: The Monolithic Context Collapse
- Trigger Event: An engineering team places all project documentation, backend rules, frontend conventions, DB schemas, and deployment guides into a single 2,500-line root
CLAUDE.md. - Direct Symptom: Claude Code sessions consume 45,000 prompt tokens before the first user query, triggering early auto-compaction and frequent instructional amnesia.
- Root Cause: Excessive initial context volume crowds out reasoning capacity and dilutes attention on specific active files.
- Prevention & Mitigation: Decompose
CLAUDE.mdinto high-level standards (< 200 lines) and migrate specific domain guidelines into path-gated.claude/rules/and on-demand.claude/skills/.
Quick reference
- Audit .claude/ directory periodically to prune stale rules and obsolete skill definitions.
- Never commit settings.local.json or plaintext API keys to repository history.
- Use subagent isolation for heavy exploratory tasks to prevent main-thread context bloat.
- Integrate automated validation scripts in CI to verify that rules, skills, and configuration files remain syntactically valid.
Remember this
Keep CLAUDE.md lean, use path-gated rules, isolate subagents, protect credentials with environment variables, and commit team configurations to version control.
Key takeaway
The .claude/ directory structure transforms Claude Code from a basic conversational assistant into an enterprise-ready, deterministic engineering partner. By separating team-shared standards in .claude/ from personal environments in ~/.claude/, you guarantee consistent execution across engineering teams and CI pipelines.
As your codebase scales, avoid context rot by decomposing monolithic instructions into modular, path-gated .claude/rules/. Bundle reusable capabilities into .claude/skills/, delegate heavy exploratory workflows to isolated .claude/agents/, and capture long-term system insights in .claude/agent-memory/. This structured configuration architecture gives your team maximum velocity while keeping full architectural control.
Polo Khan
Lead Author & Systems ArchitectSoftware engineer and distributed systems architect specializing in backend scalability, cloud-native infrastructure, databases, and AI engineering workflows. Author and maintainer of Core Concept Learning.
Related Articles
Explore this topic