Skip to main content

Anatomy of Prompt Engineering for Repos

System prompts, few-shots, CLAUDE.md interplay, and design patterns.

Prompt Engineering

System prompts, few-shots, and CLAUDE.md interplay โ€” the art of giving AI the right context, at the right time, to produce reliable results across your codebase.


TL;DRโ€‹

  • Prompt engineering for repos isn't writing one clever prompt โ€” it's layering context across the stack.
  • The hierarchy: System Prompt โ†’ CLAUDE.md โ†’ Skills/Commands โ†’ Few-Shots โ†’ User Prompt.
  • Lower layers set defaults; upper layers override and specialize.
  • Few-shots beat instructions for nuanced behavior โ€” show, don't just tell.
  • Keep rules consistent across layers. Less conflict = better results.

Why this mattersโ€‹

A great prompt for a one-off task is a clever trick. A great prompt system for a repo is leverage that compounds โ€” every team member, every session, every PR benefits.

Bottom line: Prompt engineering at the repo level turns a raw model into a domain expert your team can trust.


The Big Picture โ€” The Prompt Stackโ€‹

Bottom line: Five layers. Each one feeds the next. Most teams only think about layer 5.


The Five Layers (top of stack = highest specificity)โ€‹

#LayerWhat it setsWho owns it
5User PromptThe specific askThe person at the keyboard
4Few-Shots / ExamplesPatterns to emulateSkill / command author
3Skills / CommandsReusable instructionsTeam
2CLAUDE.mdProject memory, conventionsRepo maintainers
1System PromptBase capabilities & safetyAnthropic

๐Ÿ’ก Tip: Lower layers set the defaults. Upper layers override and specialize.


Layer 1 โ€” System Prompt (Built-in)โ€‹

You don't edit this directly, but it defines core behaviors Claude always follows.

What it includesโ€‹

  • ๐Ÿ›ก๏ธ Safety & alignment policies
  • ๐Ÿ”ง Tool use rules
  • ๐Ÿง  Reasoning & planning behavior
  • โœ๏ธ Response formatting defaults
  • ๐Ÿงฐ Memory & context management

Conceptual (not editable)โ€‹

You are Claude, an AI assistant.
Be helpful, harmless, and honest.
Use tools responsibly.
Explain your reasoning.
If unsure, say so.
Follow user & project rules.

๐Ÿ’ก Tip: You specialize the system prompt by adding layers above it, not by fighting it.


Layer 2 โ€” CLAUDE.md (Project Memory)โ€‹

Loaded first. Sets the ground truth for your codebase. (See the dedicated Anatomy of CLAUDE.md for the full spec.)

What to includeโ€‹

  • โœ… Project overview & goals
  • โœ… Tech stack & versions
  • โœ… Architecture & structure
  • โœ… Conventions & style
  • โœ… Workflows & commands
  • โœ… Testing strategy & DoD
  • โœ… Security & data handling
  • โœ… Decisions & rationale
  • โœ… Known gotchas
  • โœ… Integration & tools (MCP)

Example skeletonโ€‹

# Project: Acme App

## Tech Stack
- Next.js 14 (App Router) ยท TypeScript
- Postgres ยท Prisma ยท tRPC
- Tailwind CSS ยท shadcn/ui

## Conventions
- Use TypeScript strict mode.
- Prefer server components.
- File names: kebab-case. Components: PascalCase.
- Tests: Vitest + React Testing Library.

## Workflows
- Dev: npm run dev
- Test: npm test
- Lint: npm run lint

## Security
- Never log secrets.
- Validate all inputs with Zod.
- Use parameterized queries only.

๐Ÿ’ก Tip: Keep CLAUDE.md concise (โ‰ค 300 lines) and up to date. Reference, don't repeat.


Layer 3 โ€” Skills & Commands (Reusable Playbooks)โ€‹

These encode repeatable workflows so the team doesn't reinvent them each session. (See the Skills and Slash Commands anatomies for full detail.)

What they provideโ€‹

  • ๐Ÿ“ˆ Task success rate
  • ๐ŸŽฏ First-pass correctness
  • โฑ๏ธ Time to completion
  • ๐Ÿ” Rework / revisions
  • ๐Ÿ’ฐ Token usage / cost
  • ๐Ÿ˜Š User satisfaction

Improvement loopโ€‹

  1. Define the task & success criteria.
  2. Run prompt & measure.
  3. Analyze gaps & failure modes.
  4. Refine prompt / examples / rules.
  5. Re-run & compare.
  6. Document what changed.
  7. Repeat.

๐Ÿ’ก Tip: Treat prompt tweaks like code changes โ€” review, version, and measure.


Layer 4 โ€” Few-Shots: Show, Don't Just Tellโ€‹

Examples teach faster than rules. For tricky formats, 2โ€“5 high-quality examples beat 20 low-quality ones.

When to use few-shotsโ€‹

  • โœ… Complex formatting
  • โœ… Code style & patterns
  • โœ… Edge cases
  • โœ… Multi-step reasoning
  • โœ… Domain-specific tone

Few-shot exampleโ€‹

# Task: Create a Zod schema for a user

# Example 1
Input: name (string), email (string)
Output:
userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
});

# Example 2
Input: name, age (number where >= 18)
Output:
userSchema = z.object({
name: z.string().min(1),
age: z.number().int().min(18),
});

# Now do:
Input: name, email, role (enum: admin | user | guest)

๐Ÿ’ก Tip: Order examples from simple โ†’ complex. The last example shapes behavior most.


Layer 5 โ€” User Prompt (The Specific Ask)โ€‹

This is where the magic โ€” or the chaos โ€” happens. The other four layers exist to make this layer short, specific, and effective.

A great user promptโ€‹

  • States the role (when useful): "Act as a senior reviewer."
  • States the goal in one sentence.
  • Gives constraints (must / must not).
  • References files (@src/auth/login.ts).
  • Asks for a specific output format.

Anti-prompt โ†’ Betterโ€‹

โŒ "Fix the bug"
โœ… "Act as a senior backend engineer. The /login endpoint
returns 500 for valid creds (logs attached). Find the
root cause and propose a minimal fix with a test.
Output: 1) root cause, 2) patch (diff), 3) test."

The Interplay โ€” How They Work Togetherโ€‹

Each layer feeds the next. Conflicts are resolved by specificity and recency.

Precedence rulesโ€‹

  1. Specific > General โ€” Specific instructions override generic ones.
  2. Recent > Old โ€” Latest instructions in the conversation win.
  3. User > Repo > System โ€” Lower layers set defaults; upper layers override.
  4. Consistency matters โ€” Conflicting rules confuse the model.

๐Ÿ’ก Tip: Keep rules consistent across layers. Less conflict = better results.


Prompt Design Patternsโ€‹

PatternWhat it does
๐ŸŽญ Role + GoalDefine who AI is and the objective
๐Ÿ›ก๏ธ ConstraintsRules, limits, guardrails
๐Ÿชœ Step-by-StepBreak tasks into numbered steps
๐Ÿ“‹ Output FormatSpecify structure: tables, JSON, etc.
๐Ÿ’ก Examples (Few-Shot)Show input โ†’ desired output
๐Ÿ“š ReferencesPoint to docs, files, links
โœ… Check Before FinalSelf-verify & ask clarifying questions
๐Ÿ” Reflect & ImproveCritique and refine before answering

Common Prompt Templatesโ€‹

A) Task Executionโ€‹

Role: {{role}}
Goal: {{goal}}

Context: {{context}}

Steps:
1. {{step1}}
2. {{step2}}
...

Output: {{output_format}}

B) Code Generationโ€‹

Task: {{task}}

Requirements:
- {{req1}}
- {{req2}}

Tech stack: {{stack}}

Constraints:
- {{constraint1}}
- {{constraint2}}

Output: {{format}}

C) Review / Auditโ€‹

Role: {{role}}
What to review: {{scope}}

Standards:
- {{standard1}}
- {{standard2}}

Report format:
- Summary
- Issues (Critical / Medium / Low)
- Suggestions (file:line)

D) Refactorโ€‹

Goal: {{goal}}

Original code:
{{code}}

Constraints:
- {{constraint1}}
- {{constraint2}}

Output: Refactored code + brief explanation of changes.

๐Ÿ’ก Tip: Parameterize with {{variables}} for reuse across slash commands and skills.


Variables & Placeholdersโ€‹

SyntaxMeaningExample
{{var}}Required variable{{scope}}
{{var?}}Optional variable{{scope?}}
{{var=default}}Default value{{base=main}}
{{a|b|c}}Choose-from list{{env|dev|stg|prod}}
{{var:type}}Typed variable{{count:number}}
{{env:NAME}}Environment variable{{env:GITHUB_TOKEN}}

๐Ÿ’ก Tip: Validate inputs and handle missing values gracefully โ€” never assume the caller filled them in.


Step-by-Step Setupโ€‹

1. Write or update CLAUDE.mdโ€‹

Start with the skeleton above. Keep it crisp.

2. Create a slash command for a common taskโ€‹

.claude/commands/review.md:

---
description: Review the current branch
arguments:
- name: base
default: main
permissions:
allow: ["Read", "Bash(git *)"]
---
Act as a senior reviewer. Diff vs `{{base}}`.
Report: Risks (Critical/Medium/Low) ยท Missing tests ยท Suggestions (file:line).
Follow conventions in CLAUDE.md.

# Example output format
## Risks
- ๐Ÿ”ด SQL injection in src/users.ts:42
- ๐ŸŸก Missing null check in src/auth.ts:91

## Missing tests
- /login with invalid creds

## Suggestions
- Parameterize the query in src/users.ts:42

3. Add 2โ€“3 few-shot examplesโ€‹

Inline in the command, or in references/ of a skill.

4. Define output format & success criteriaโ€‹

Be explicit: bullet points, headings, code blocks, JSON, etc.

5. Test on a real taskโ€‹

Run, observe, capture failure modes.

6. Refine based on resultsโ€‹

Tighten constraints; add/remove examples.

7. Share with the teamโ€‹

Commit, demo, document the why.


Variants for Different Team Settingsโ€‹

๐Ÿ‘ค Solo developerโ€‹

  • Minimal CLAUDE.md (โ‰ค 100 lines).
  • 1โ€“2 slash commands.
  • Personal style baked into prompts.

๐Ÿ‘ฅ Small team (2โ€“10)โ€‹

  • Shared CLAUDE.md + shared .claude/commands/.
  • Conventional commits, PR template referencing /review.
  • One few-shot library in docs/examples/.

๐Ÿข Enterprise / regulatedโ€‹

  • Pin model versions.
  • Approved prompt templates committed and code-reviewed.
  • Audit hooks log prompt + response hashes.
  • Inject compliance reminders via layer 2/3 (CLAUDE.md + skills).

๐ŸŒ Open-source / communityโ€‹

  • Generic, jargon-free prompts.
  • Contribution guide for new commands & few-shots.
  • Examples for the most common contributor tasks (file an issue, open a PR, write a test).

Bottom line: Same stack, escalating governance.


Common Patterns & Recipesโ€‹

Pattern 1 โ€” Self-checkโ€‹

Before finalizing, list any assumptions you made.
Re-check each assumption against CLAUDE.md.
If any conflict, ask before proceeding.

Pattern 2 โ€” Clarifying question gateโ€‹

If the task is ambiguous, ask up to 3 clarifying questions
BEFORE writing code. Otherwise, proceed.

Pattern 3 โ€” Output in two passesโ€‹

Pass 1: Write the code.
Pass 2: Critique your own code as a senior reviewer.
Pass 3: Apply fixes from your critique.

Pattern 4 โ€” Constrained formatโ€‹

Return ONLY this JSON:
{
"summary": string,
"risks": [{"level": "critical|medium|low", "file": string, "line": number, "note": string}],
"tests_missing": string[]
}

Pattern 5 โ€” Anchor with referencesโ€‹

Read CLAUDE.md and docs/architecture.md before answering.
Cite the section you're following in your response.

Pattern 6 โ€” Anti-hallucinationโ€‹

If you don't know, say "I don't know" and propose
how to find out (a test, a doc to read, a person to ask).

Best Practices โœ…โ€‹

  • Be specific & concrete โ€” vague prompts โ†’ vague outputs.
  • Provide context deliberately โ€” load what's needed, no more.
  • Show examples โ€” few-shots are gold.
  • Define success criteria โ€” what does "done" look like?
  • Review everything โ€” AI is fast, not infallible.
  • Iterate weekly โ€” prompts are code; refactor them.
  • Keep layers consistent โ€” no contradictions between CLAUDE.md and a command.

Anti-Patterns โŒโ€‹

  • ๐Ÿ—ฏ๏ธ Walls of vague instructions.
  • ๐Ÿค– "Just be smart" prompts.
  • ๐Ÿฅช Stacking 20 examples (more isn't better).
  • ๐ŸŽญ Contradictory rules across layers.
  • ๐Ÿ™ˆ No output format โ†’ unpredictable parsing.
  • โ“ No clarifying-question option.
  • ๐Ÿ“œ Mega prompts that ignore CLAUDE.md.

Troubleshootingโ€‹

SymptomCauseFix
Output ignores conventionsCLAUDE.md too long / vagueTrim to bullets, add examples
Wrong formatNo format specProvide explicit format + 1 example
Hallucinated APIsNo groundingReference docs; add anti-hallucination rule
Inconsistent styleConflicting layersAudit & align rules across layers
Repeats itselfNo constraintsAdd length caps & "no repetition" rule
Skips safety checksFew-shots show bad patternsReplace examples with good patterns
Over-cautiousToo many constraintsTrim guardrails; allow proposal mode

Mini Starter Kitโ€‹

.claude/
โ”œโ”€โ”€ settings.json # hooks, permissions, env
โ”œโ”€โ”€ commands/
โ”‚ โ”œโ”€โ”€ review.md # slash commands
โ”‚ โ”œโ”€โ”€ plan.md
โ”‚ โ”œโ”€โ”€ deploy.md
โ”‚ โ””โ”€โ”€ status.md
agents/
โ”œโ”€โ”€ code-reviewer.yml # reusable playbooks
โ”œโ”€โ”€ test-writer.yml
โ””โ”€โ”€ docs-writer.yml
hooks/
โ”œโ”€โ”€ pre-tool.sh
โ”œโ”€โ”€ post-tool.sh
โ””โ”€โ”€ pre-commit.sh
CLAUDE.md # project memory (layer 2)
docs/
โ””โ”€โ”€ examples/ # few-shot library

๐Ÿ’ก Tip: Start small. Evolve. Share. Repeat the loop.


Quick Start (7 steps)โ€‹

  1. Write or update CLAUDE.md with stack, conventions, security.
  2. Create a slash command for one common task (e.g., /review).
  3. Add 2โ€“3 few-shot examples to that command.
  4. Define output format & success criteria.
  5. Test on a real task.
  6. Refine based on results.
  7. Share with the team โ€” commit + demo + document.

Glossaryโ€‹

  • System prompt โ€” Anthropic-built base instructions; not user-editable.
  • CLAUDE.md โ€” Project-level memory & conventions (layer 2).
  • Skill / Command โ€” Reusable playbook (layer 3).
  • Few-shot โ€” Examples that demonstrate desired input โ†’ output.
  • Zero-shot โ€” Prompt with no examples (relies on layers 1โ€“3 + 5).
  • Chain-of-thought โ€” Encouraging the model to reason step-by-step.
  • Role prompting โ€” "Act as a senior reviewer" โ€” sets persona/context.
  • Output format โ€” Explicit structure for the response.
  • Self-critique / reflection โ€” Asking the model to evaluate its own output.

Further Readingโ€‹

  • Search: "Anthropic prompt engineering guide"
  • Search: "few-shot vs zero-shot LLM examples"
  • Search: "prompt patterns catalog 2026"
  • Search: "prompt versioning & evaluation"

๐Ÿช™ Golden Rulesโ€‹

  • ๐ŸŽฏ Be specific.
  • ๐Ÿ“‚ Provide context deliberately.
  • ๐Ÿ’ก Show examples.
  • โœ… Define success.
  • ๐Ÿ” Review everything.
  • ๐Ÿ” Iterate & improve.

Remember: Good prompts compound over time. Your future self (and your team) will thank you.