System Prompts and Persistent Context
Beyond Individual Prompts
Everything we have covered so far focuses on single prompts -- one request, one response. But the most productive developers using AI tools do not start from scratch every session. They configure their AI environment with persistent context that carries across every interaction: project conventions, coding standards, preferred patterns, and domain-specific knowledge.
This is the difference between a junior developer who asks the same questions every morning and a senior developer who has internalized the team's practices. System prompts and persistent context files let you build that institutional knowledge into your AI tools.
CLAUDE.md as a System Prompt
Claude Code reads CLAUDE.md files from your project directory and treats them as persistent instructions. This is your most powerful tool for consistent AI behavior across sessions.
A CLAUDE.md file at your project root is automatically loaded every time you start a Claude Code session in that directory. It shapes every response, every code generation, and every refactoring the AI performs.
What to Include
# Project: E-Commerce API
## Tech Stack
- Express.js 4 with TypeScript 5 (strict mode)
- Prisma ORM with PostgreSQL 15
- Vitest for testing
- Zod for input validation
- Pino for structured logging
## Code Conventions
- Use async/await, never raw callbacks or .then() chains
- Error handling: throw AppError subclasses, never plain Error
- Naming: camelCase for variables/functions, PascalCase for types/classes
- File structure: one exported class/function per file
- Imports: use path aliases (@/services, @/utils, @/routes)
## Patterns to Follow
- Services: constructor injection for dependencies
- Routes: thin handlers that delegate to services
- Validation: Zod schemas in src/schemas/, used in route middleware
- Tests: factories for test data, mocks in __mocks__/ directory
## Patterns to Avoid
- Do NOT use any/unknown types without explicit justification
- Do NOT install new packages without asking first
- Do NOT use console.log (use the logger from src/lib/logger.ts)
- Do NOT write SQL directly (use Prisma)
## Common Commands
- npm test -- run all tests
- npm run test:watch -- run tests in watch mode
- npx prisma migrate dev -- run database migrations
- npm run lint -- run ESLint
What NOT to Include
Do not put secrets, API keys, or credentials in CLAUDE.md. This file is part of your project and may be committed to version control. Do not include verbose explanations or documentation -- keep it concise. The AI reads this on every session start, so long files waste context window space.
Do not include temporary instructions or session-specific tasks. Those belong in your prompt, not in the persistent configuration.
The Context Hierarchy
AI tools that support persistent context files use a hierarchy of specificity. Understanding this hierarchy lets you configure behavior at the right level.
Level 1 -- Global preferences (applies to all projects):
In Claude Code, this is ~/.claude/CLAUDE.md. Set preferences that apply everywhere:
# Global Preferences
- Always respond in English
- Use conventional commits: feat:, fix:, refactor:, docs:, test:
- Prefer TypeScript with strict mode
- Use async/await, never callbacks
Level 2 -- Project conventions (applies to one project):
This is your project root CLAUDE.md. Set project-specific standards:
# Project: Mobile App API
- Framework: Fastify (NOT Express)
- ORM: Drizzle (NOT Prisma)
- Testing: Vitest with Testing Library
Level 3 -- Directory-specific instructions (applies to files in a directory):
You can place CLAUDE.md files in subdirectories for area-specific rules:
# src/services/CLAUDE.md
- All services use constructor injection
- Services must have a corresponding .test.ts file
- Services should not import from routes/ or middleware/
Level 4 -- Task-specific instructions (applies to one prompt):
These are your individual prompts. They override everything above for the current task.
When instructions conflict, more specific levels override less specific ones. A task prompt saying "use console.log for debugging" overrides a project CLAUDE.md that says "never use console.log."
Custom Instructions for Different Roles
You can direct the AI to adopt a specific perspective by defining a role. This changes what the AI pays attention to and what kind of output it produces.
Security Reviewer
For this session, act as a security reviewer. When I show you code:
- Focus exclusively on security vulnerabilities
- Check for: SQL injection, XSS, CSRF, authentication bypasses, insecure
deserialization, path traversal, sensitive data exposure
- Rate each finding as Critical, High, Medium, or Low
- For each finding, show the vulnerable code and a fixed version
- Ignore code style, performance, and readability issues entirely
Performance Optimizer
For this session, act as a performance engineer. When reviewing code:
- Focus on runtime performance and resource usage
- Identify: N+1 queries, unnecessary re-renders, memory leaks, blocking
operations, unindexed queries, large bundle imports
- Quantify impact where possible (e.g., "this N+1 query will make
100 database calls for a list of 100 items")
- Suggest fixes with before/after comparison
- Ignore security, documentation, and code style issues
Code Reviewer
For this session, act as a senior developer performing code review. When I
share diffs:
- Check for correctness first (logic errors, missing edge cases)
- Then check for maintainability (naming, complexity, coupling)
- Then check for consistency with our project patterns
- Flag anything that would be hard to change later (schema changes,
public API surface)
- Format as PR comments: file, line, severity (must-fix, should-fix, nit),
comment
Temperature and Creativity
Different tasks benefit from different levels of AI creativity. While most developer tools do not expose temperature controls directly, you can influence the output style through your prompts.
When you want deterministic, predictable output (code generation, bug fixes, tests):
Generate the exact implementation based on the spec. Do not add extra
features, optimizations, or alternatives. Follow the patterns in our codebase
exactly. If something is ambiguous, ask rather than guessing.
When you want creative, exploratory output (architecture, brainstorming, problem-solving):
Propose multiple approaches. Include unconventional solutions. Explain the
tradeoffs of each. I am in exploration mode -- I want to see the full
solution space before narrowing down.
The key is being explicit about which mode you are in. The AI defaults to being conservative with code (which is usually correct), but sometimes you want it to think broadly.
Model Selection for Different Tasks
Different AI models have different strengths. If your tool allows model selection, match the model to the task.
Fast models (Claude Sonnet, GPT-4o-mini) work well for:
- Simple code generation with clear patterns
- Inline documentation and comments
- Quick explanations and lookups
- Test generation from explicit test case lists
- Formatting and linting suggestions
Powerful models (Claude Opus, GPT-4o, o1) are worth the cost for:
- Complex debugging with multi-file context
- Architecture decisions and tradeoff analysis
- Large-scale refactoring across many files
- Security audits and vulnerability analysis
- Code review with nuanced feedback
In Claude Code, you can switch models mid-session with the /model command or start with a specific model using the --model flag.
The Meta-Prompt: Improving Your Own Prompts
One of the most powerful uses of AI is improving your prompts themselves. When you consistently get poor results from a prompt, ask the AI to help you rewrite it.
I keep using this prompt but the results are inconsistent:
"Refactor the component to be more performant"
Help me rewrite this prompt to be more specific and actionable. Ask me
clarifying questions about:
1. What specific performance problem I am seeing
2. What metrics I am optimizing for (render time, bundle size, memory)
3. What constraints I have (cannot change the API, must support IE11, etc.)
4. What patterns I want the refactored code to follow
Then write an improved version of my prompt based on my answers.
This meta-prompt technique is especially useful when you are starting out. Over time, you internalize the patterns and write precise prompts naturally.
Building Your Project's AI Configuration
Here is a practical approach to building effective persistent context for your project:
-
Start with the minimum. Create a CLAUDE.md with just your tech stack and top 5 coding conventions. Use it for a week.
-
Add rules reactively. Every time the AI produces output that does not match your project's style, add a rule to CLAUDE.md that would have prevented it. "Do NOT use semicolons" or "Always use named exports" -- these specific rules accumulate into a comprehensive style guide.
-
Review monthly. Remove rules that no longer apply. Consolidate duplicates. Reorder by importance. Your CLAUDE.md should be a living document, not a write-once file.
-
Share with your team. Commit CLAUDE.md to your repository. When every developer on the team uses the same persistent context, AI output becomes consistent across the team -- reducing code review friction and improving codebase uniformity.
The investment in building good persistent context pays returns on every single AI interaction for the life of the project. A well-crafted CLAUDE.md can save hours per week across a development team.