# Agent Guardrails & Safety Protocols
**Version:** 1.3
**Last Updated:** 2026-01-21
**Applies To:** ALL AI agents, LLMs, and automated systems operating on this codebase
---
## Applicability
This document is **MANDATORY** for:
| System Type | Examples | Binding? |
|-------------|----------|----------|
| **Large Language Models** | Claude, GPT-4/o1/o3, Gemini, LLaMA, Mistral, Qwen, DeepSeek, Cohere, Phi, Falcon, and 30+ other model families | YES |
| **AI Coding Assistants** | Claude Code, GitHub Copilot, Cursor, Cody, Aider, Continue, Windsurf, and others | YES |
| **Autonomous Agents** | AutoGPT, AgentGPT, CrewAI, LangChain, LangGraph, Semantic Kernel agents | YES |
| **Reasoning Models** | o1, o3, DeepSeek-R1, and other chain-of-thought models | YES |
| **CI/CD Bots** | Dependabot, Renovate, automated PR bots | YES |
| **Custom Agents** | Any agent built on this codebase (specialists, operators, swarm) | YES |
| **Human Developers** | Recommended best practices | RECOMMENDED |
**If you are an AI system reading this:** You MUST follow these protocols. They are not suggestions.
---
## Purpose
This document defines mandatory safety protocols, guardrails, and behavioral constraints for ALL automated systems performing tasks on this repository. These rules exist to:
1. **Prevent data loss** — enabling safe rapid iteration without backup anxiety
2. **Maintain code quality** — so AI-generated code ships without manual review overhead
3. **Preserve history** — keeping git history clean and reversible
4. **Enable collaboration** — allowing humans and agents to work together safely
5. **Limit blast radius** — containing errors to minimal scope
### How These Laws Enable Rapid Development
The Four Laws aren't restrictions — they're accelerators. Here's why:
- **Read Before Editing** eliminates rework. One read costs fewer tokens than fixing a blind edit.
- **Stay in Scope** prevents cascade failures. Agents move faster when they're not untangling unintended side effects.
- **Verify Before Committing** catches errors at the cheapest point. A failed test in development costs minutes; in production, it costs hours.
- **Halt When Uncertain** prevents wasted effort. Asking one question is cheaper than building the wrong thing.
When agents follow these laws, they don't need to pause for safety checks — safety is built into every step. The result: full-velocity development with production-grade reliability.
---
## CORE PRINCIPLES
### The Four Laws of Agent Safety
See [skills/shared-prompts/four-laws.md](../skills/shared-prompts/four-laws.md) for the complete Four Laws documentation.
**Quick Reference:**
1. **Read Before Editing** - Never modify code without reading first
2. **Stay in Scope** - Only touch authorized files
3. **Verify Before Committing** - Test all changes
4. **Halt When Uncertain** - Ask instead of guessing
---
## SAFETY PROTOCOLS (MANDATORY)
### Pre-Execution Checklist
**EVERY agent MUST verify these before ANY file modification:**
| # | Check | Requirement | Verify |
|---|-------|-------------|--------|
| 1 | **READ FIRST** | NEVER edit a file without reading it first | [ ] |
| 2 | **SCOPE LOCK** | Only modify files explicitly in scope | [ ] |
| 3 | **NO FEATURE CREEP** | Do NOT add features, refactor, or "improve" unrelated code | [ ] |
| 4 | **PRODUCTION FIRST** | Production code created BEFORE test code | [ ] |
| 5 | **TEST/PROD SEPARATION** | Test infrastructure is separate from production | [ ] |
| 6 | **BACKUP AWARENESS** | Know the rollback command before editing | [ ] |
| 7 | **TEST BEFORE COMMIT** | All tests must pass before committing | [ ] |
| 8 | **CHECK FAILURE REGISTRY** | Review known bugs for affected files ([.guardrails/pre-work-check.md](../.guardrails/pre-work-check.md)) | [ ] |
| 9 | **VERIFY FIXES INTACT** | Confirm previous fixes not being undone | [ ] |
### Git Safety Rules
| Rule | Description | Consequence |
|------|-------------|-------------|
| **NO FORCE PUSH** | Never use `git push --force` | Data loss, history corruption |
| **NO AMEND** | Do not amend commits you didn't create this session | Breaks collaborator history |
| **NO CONFIG CHANGES** | Do not modify git config | Security/identity issues |
| **NO PUSH WITHOUT PERMISSION** | Only push if user explicitly requests | Unwanted remote changes |
| **SINGLE COMMIT** | One focused commit per task | Maintains clean history |
| **NO SKIP HOOKS** | Never use `--no-verify` | Bypasses safety checks |
| **NO REBASE** | Never rebase shared branches | Destroys collaborator work |
| **NO DESTRUCTIVE OPS** | No `reset --hard` on shared branches | Irreversible data loss |
### Code Safety Rules
| Rule | Rationale |
|------|-----------|
| **EXACT REPLACEMENT** | Use provided code exactly - no "improvements" |
| **NO NEW IMPORTS** | Unless explicitly required by the task |
| **NO TYPE CHANGES** | Preserve existing type hints |
| **NO DELETIONS** | Do not delete functionality outside scope |
| **PRESERVE FORMATTING** | Match existing indentation and style |
| **NO SECRETS** | Never commit credentials, keys, tokens |
| **NO BINARY FILES** | Unless explicitly required |
| **NO GENERATED CODE** | Do not commit build artifacts |
### Test/Production Separation Rules (MANDATORY)
| Rule | Violation Level | Action |
|------|-----------------|--------|
| **PRODUCTION CODE FIRST** | CRITICAL | Halt, ask user |
| **SEPARATE DATABASES** | CRITICAL | Halt, ask user |
| **SEPARATE SERVICES** | CRITICAL | Halt, ask user |
| **NO TEST USERS IN PROD** | CRITICAL | Halt, rollback |
| **NO PROD CREDENTIALS IN TEST** | CRITICAL | Halt, rollback |
| **ASK IF UNCERTAIN** | HIGH | Ask user before proceeding |
**Full details:** See [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md)
---
## GUARDRAILS
### HALT CONDITIONS
**Stop immediately and report to user if ANY of these occur:**
```
CRITICAL HALT - DO NOT PROCEED:
[ ] Target file does not exist
[ ] Line numbers don't match expected
[ ] File has unexpected modifications
[ ] Syntax check fails after edit
[ ] Any test fails after edit
[ ] Merge conflicts encountered
[ ] Uncertain about ANY step
[ ] Edit tool reports "string not found"
[ ] Permission denied errors
[ ] Import errors when testing
[ ] Network/connection errors
[ ] Out of memory errors
[ ] Timeout errors
[ ] User requests stop
[ ] Test/production boundary unclear
[ ] Attempting to use production DB for tests
[ ] Attempting to use test DB for production
```
### FORBIDDEN ACTIONS
**No agent may perform these actions under any circumstances:**
```
ABSOLUTE PROHIBITIONS:
FILE OPERATIONS:
- Modify files outside declared scope
- Delete files without explicit permission
- Create files without explicit need
- Modify hidden/system files (.*) without permission
- Change file permissions
CODE CHANGES:
- Add logging/debugging to production code
- Add comments that weren't requested
- "Clean up" or "improve" surrounding code
- Update version numbers without explicit request
- Change security configurations
- Modify authentication/authorization code without review
TEST/PRODUCTION SEPARATION:
- Deploy test code to production environment
- Use production database for tests
- Create test users in production database
- Write test code that imports production secrets
- Use production services for test execution
- Share user accounts across environments
GIT OPERATIONS:
- Force push to any branch
- Delete branches without permission
- Modify git hooks
- Change git config
- Push without explicit permission
SYSTEM OPERATIONS:
- Run servers or long-running services
- Execute commands requiring user input
- Make network requests to unknown endpoints
- Install new dependencies without permission
- Modify CI/CD pipelines without permission
- Execute shell commands with elevated privileges
- Access or modify environment variables
DATA OPERATIONS:
- Access databases without explicit permission
- Modify production data
- Export or transmit user data
- Store credentials or secrets
- Mix test and production data
```
### SCOPE BOUNDARIES
**For any task, clearly define IN/OUT scope:**
```
IN SCOPE (may modify):
- Specific file(s) listed in task
- Specific line ranges identified
- Exact changes described
- Production code (before test code)
OUT OF SCOPE (DO NOT TOUCH):
- All other files
- All other methods/functions in target file
- Tests in production files (read-only unless task is test-related)
- Documentation (unless task is doc-related)
- Git hooks and configs
- CI/CD configurations
- Dependencies/package files
- Environment configurations
- Security-related files
- Production database connections in test code
- Test database connections in production code
```
---
## QUICK REFERENCE
```
+------------------------------------------------------------------+
| UNIVERSAL AGENT GUARDRAILS |
+------------------------------------------------------------------+
| ALWAYS: |
| - Read before edit |
| - Verify before proceeding |
| - Test before committing |
| - Create production code BEFORE test code |
| - Separate test/production infrastructure |
| - Report results to user |
| - Include AI attribution |
+------------------------------------------------------------------+
| NEVER: |
| - Edit without reading |
| - Push without permission |
| - Modify outside scope |
| - Force push or rebase |
| - Continue when uncertain |
| - Use production DB for tests |
| - Create test users in production |
+------------------------------------------------------------------+
| HALT IF: |
| - Conditions don't match |
| - Any check fails |
| - Uncertain about anything |
| - User requests stop |
| - Test/production boundary unclear |
+------------------------------------------------------------------+
| ROLLBACK: git checkout HEAD -- <file> |
+------------------------------------------------------------------+
| APPLIES TO: ALL LLMs, AI assistants, coding agents, and automated systems |
+------------------------------------------------------------------+
```
---
## RELATED DOCUMENTS
### Core Guardrails
- **This document** - Core safety protocols (MANDATORY)
- [TEST_PRODUCTION_SEPARATION.md](standards/TEST_PRODUCTION_SEPARATION.md) - Test/production isolation (MANDATORY)
- [REGRESSION_PREVENTION.md](workflows/REGRESSION_PREVENTION.md) - Bug tracking and regression prevention
### Regression Prevention
- [.guardrails/pre-work-check.md](../.guardrails/pre-work-check.md) - MANDATORY pre-work checklist
- [.guardrails/failure-registry.jsonl](../.guardrails/failure-registry.jsonl) - Bug database (JSONL format)
- [scripts/log_failure.py](../scripts/log_failure.py) - CLI to log new failures
- [scripts/regression_check.py](../scripts/regression_check.py) - Pre-commit regression scanner
### Workflow Documentation
- [AGENT_EXECUTION.md](workflows/AGENT_EXECUTION.md) - Execution protocol, rollback, Three Strikes Rule
- [AGENT_REVIEW_PROTOCOL.md](workflows/AGENT_REVIEW_PROTOCOL.md) - Post-work agent/LLM review (RECOMMENDED)
- [TESTING_VALIDATION.md](workflows/TESTING_VALIDATION.md) - Validation protocols
- [COMMIT_WORKFLOW.md](workflows/COMMIT_WORKFLOW.md) - Commit guidelines
- [GIT_PUSH_PROCEDURES.md](workflows/GIT_PUSH_PROCEDURES.md) - Push safety
- [ROLLBACK_PROCEDURES.md](workflows/ROLLBACK_PROCEDURES.md) - Recovery operations
- [MCP_CHECKPOINTING.md](workflows/MCP_CHECKPOINTING.md) - Checkpoint integration
### Agent Operations
- [AGENT_ESCALATION.md](workflows/AGENT_ESCALATION.md) - Audit requirements and escalation
- [CODE_REVIEW.md](workflows/CODE_REVIEW.md) - Code review process
### Standards
- [PROJECT_CONTEXT_TEMPLATE.md](standards/PROJECT_CONTEXT_TEMPLATE.md) - Project Bible template
- [ADVERSARIAL_TESTING.md](standards/ADVERSARIAL_TESTING.md) - Breaker agent, fuzz testing
- [DEPENDENCY_GOVERNANCE.md](standards/DEPENDENCY_GOVERNANCE.md) - Package allow-list
- [INFRASTRUCTURE_STANDARDS.md](standards/INFRASTRUCTURE_STANDARDS.md) - IaC, Terraform, drift detection
- [OPERATIONAL_PATTERNS.md](standards/OPERATIONAL_PATTERNS.md) - Health checks, circuit breakers
- [LOGGING_PATTERNS.md](standards/LOGGING_PATTERNS.md) - Structured logging
- [MODULAR_DOCUMENTATION.md](standards/MODULAR_DOCUMENTATION.md) - 500-line rule
### Sprint Framework
- [Sprint Task Template](sprints/) - Task execution format
- [SPRINT_GUIDE.md](sprints/SPRINT_GUIDE.md) - How to write sprints
### Security
- [SECRETS_MANAGEMENT.md](../.github/SECRETS_MANAGEMENT.md) - GitHub Secrets
---
**Authored by:** TheArchitectit
**Document Owner:** Project Maintainers
**Review Cycle:** Monthly
**Last Review:** 2026-01-21
**Next Review:** 2026-02-21
agent-guardrails-template - docs agentmcp Sentinel System Prompt
3993 characters
Project Sentinel: The Agent System PromptVersion: 3.0.0-EnterpriseModule: 23-Setup-PromptMaps to: CLAUDE.mdScope: The authoritative System Instruction that must be provided to the LLM to enable Sentinel compatibility.1. The Prompt StrategySentinel is an MCP server, but the Agent needs to know how and why to use it. If you simply give the Agent tools, it might ignore them. We must "Prime" the Agent to respect the Sentinel's authority.1.1 The "Sandwich" DefenseWe use a specific prompting strategy where the Guardrail Instructions are injected at both the System Level (Top) and the Context Level (Dynamic Injection).2. The Core System PromptCopy and paste this into your Agent configuration (e.g., CLAUDE.md, .cursorrules, or OpenCode System Prompt).# IDENTITY & GOVERNANCE
You are an Autonomous Developer Agent operating within the Project Sentinel Environment.
You are NOT a standard assistant. You are a "Task Execution Unit" subject to strict strict governance.
# THE SENTINEL PROTOCOL
You do not have direct access to the Operating System. You interact with the world EXCLUSIVELY through the `Sentinel` MCP Tools.
1. **State Sovereignty:** - You DO NOT track task status in your memory.
- You MUST query `get_sprint_status()` to know what to do.
- You MUST call `start_task(id)` before writing a single line of code.
2. **The VFS Jail:**
- You cannot read/write files outside the repository root.
- You cannot access `.env` files directly. You must use `get_config()`.
3. **Documentation Parity:**
- You are prohibited from completing a task if the documentation is stale.
- Use `check_doc_parity()` before calling `complete_task()`.
# CRITICAL RULES (VIOLATION = TERMINATION)
- NEVER attempt to bypass the `git_commit` tool.
- NEVER output high-entropy secrets (API keys, passwords) to the chat.
- NEVER hallucinate a successful test run. You must run `run_tests()` and read the output.
- NEVER edit `services/sentinel/**`.
# ERROR HANDLING
If a Sentinel Tool returns a "BLOCKER" or "403" error:
1. STOP immediately.
2. Do not retry the exact same input.
3. Analyze the error message.
4. If you are stuck, call `request_human_help()`.
# YOUR GOAL
Your goal is not just to write code, but to advance the State Machine from 'PLANNING' to 'ARCHIVED' while maintaining a clean Audit Log.
3. Dynamic Context InjectionsSentinel injects specific prompts based on the Agent's state. These are handled automatically by the Sentinel Server, but it helps to understand what the Agent sees.3.1 The "Planning" InjectionWhen in PLANNING state:"Current Context: PLANNING. You are restricted from writing code. Focus on breaking down requirements into atomic Tasks using add_task(). Estimate complexity for each."3.2 The "Review" InjectionWhen in REVIEW state:"Current Context: REVIEW. Code editing is LOCKED. You may only run linters, tests, and request human review. If you need to fix a bug, you must call revert_to_active()."3.3 The "Error" InjectionWhen a tool fails 3 times:"SYSTEM INTERVENTION: You are looping. Stop. Read the file docs/workflows/AGENT_ESCALATION.md to understand how to resolve this deadlock."4. Prompt Engineering for ToolsWe optimize the Tool Definitions to guide the Agent.4.1 Description EngineeringInstead of:write_file(path, content)We define:write_file(path, content) - Writes to the VFS. Will return 403 if path is restricted or if the file is locked by another Agent. Triggers automatic linting post-write.4.2 Parameter HintsWe use the description field in the MCP schema to enforce behavior:commit_message: "MUST follow Conventional Commits regex ^(feat|fix|...). Do not use generic messages."confirm: "Set to TRUE only if you have verified the action is safe."5. CompatibilityThis prompt structure is tested with:Claude 3.5 Sonnet: High compliance. Excellent at following the State Machine.GPT-4o: Good compliance. Needs more reminders about the "VFS Jail".Gemini 1.5 Pro: Excellent context retention. Very good at the "Doc Parity" checks.
agent-guardrails-template - PROMPTING GUIDE
21047 characters
# Master Prompting Guide
> How to write prompts that work beautifully with Agent Guardrails
**TL;DR:** Be explicit, provide context, define scope, and the guardrails will keep your AI on track.
---
## Table of Contents
1. [The Golden Rules](#the-golden-rules)
2. [Prompt Templates](#prompt-templates)
3. [Common Patterns](#common-patterns)
4. [Advanced Techniques](#advanced-techniques)
5. [Examples by Use Case](#examples-by-use-case)
6. [Anti-Patterns to Avoid](#anti-patterns-to-avoid)
7. [Troubleshooting](#troubleshooting)
---
## The Golden Rules
### Rule 1: Start with Context
❌ **Bad:**
```
Fix the bug
```
✅ **Good:**
```
There's a bug in the authentication system where users can't log in with valid credentials.
Context:
- Repository: myapp/backend
- File: src/auth/login.js
- Error: "Invalid credentials" even with correct password
- Database: PostgreSQL
- Framework: Express.js
Task: Find and fix the login bug. The issue is likely in the password comparison logic.
```
### Rule 2: Define Scope Explicitly
❌ **Bad:**
```
Update the API
```
✅ **Good:**
```
Update the user API endpoints to add email validation.
Scope:
- File: src/routes/users.js
- Only modify POST /api/users and PUT /api/users/:id
- Do NOT touch authentication or other routes
- Add validation using Joi schema
- Return 400 if email is invalid
```
### Rule 3: Provide Constraints
❌ **Bad:**
```
Refactor the code
```
✅ **Good:**
```
Refactor the data processing module to improve readability.
Constraints:
- Keep all existing functionality
- Maintain backward compatibility
- Don't change function signatures
- Add unit tests for new helper functions
- Use existing patterns from src/utils/helpers.js
```
### Rule 4: Include Examples
❌ **Bad:**
```
Add error handling
```
✅ **Good:**
```
Add error handling to the file upload endpoint.
Current code (src/routes/upload.js):
```javascript
app.post('/upload', (req, res) => {
const file = req.files.file;
fs.writeFileSync('/uploads/' + file.name, file.data);
res.json({ success: true });
});
```
Expected behavior:
- Handle missing file: return 400 with error "No file provided"
- Handle file too large (>10MB): return 413 with error "File too large"
- Handle disk full: return 500 with error "Storage error"
- Always return JSON: { success: boolean, error?: string }
Example error response:
```json
{ "success": false, "error": "No file provided" }
```
```
> **Why explicit context enables speed:** Every detail you provide upfront is a clarification your AI agent doesn't need to ask for. Explicit context eliminates round-trips, reducing a 5-prompt conversation to a single generation. The most productive vibe coding sessions start with the richest prompts.
---
## Prompt Templates
### Template 1: Feature Implementation
```markdown
## Feature: [Feature Name]
### Context
[Background information about the feature]
### Requirements
- [ ] Requirement 1
- [ ] Requirement 2
- [ ] Requirement 3
### Scope
- Files to modify: [list files]
- Files to NOT touch: [list files]
- New files to create: [list files]
### Technical Details
- Framework: [framework]
- Language: [language]
- Patterns to follow: [reference existing code]
### Acceptance Criteria
1. [Criteria 1]
2. [Criteria 2]
3. [Criteria 3]
### Testing
- [ ] Unit tests written
- [ ] Integration tests pass
- [ ] Manual testing completed
### Additional Notes
[Any special considerations]
```
### Template 2: Bug Fix
```markdown
## Bug Fix: [Bug Title]
### Problem
[Clear description of the bug]
### Steps to Reproduce
1. Step 1
2. Step 2
3. Step 3
### Expected Behavior
[What should happen]
### Actual Behavior
[What actually happens]
### Context
- File(s) involved: [list]
- Error message: [if any]
- Environment: [dev/staging/prod]
### Root Cause (if known)
[Your analysis]
### Proposed Solution
[Your suggestion, or leave blank]
### Testing After Fix
- [ ] Reproduction steps no longer trigger bug
- [ ] Related functionality still works
- [ ] Edge cases handled
```
### Template 3: Code Review
```markdown
## Code Review Request
### PR/MR Information
- Branch: [branch name]
- Changes: [files modified]
- Lines changed: [+X, -Y]
### Focus Areas
- [ ] Logic correctness
- [ ] Edge cases
- [ ] Performance
- [ ] Security
- [ ] Style/consistency
### Specific Questions
1. [Question 1]
2. [Question 2]
### Skip These
- [ ] Nitpicks (formatting)
- [ ] Out of scope files
- [ ] Known issues
### Timeline
[Urgency level]
```
### Template 4: Refactoring
```markdown
## Refactoring: [Area]
### Current State
[What's wrong with current code]
### Target State
[What it should look like]
### Constraints
- [ ] No functionality changes
- [ ] All tests must pass
- [ ] Maintain backward compatibility
- [ ] Update documentation
### Files
- Primary: [main file(s)]
- Dependencies: [files that depend on these]
- Tests: [test files to update]
### Patterns to Follow
- [Reference to similar code]
### Success Criteria
- [ ] Code is cleaner/more readable
- [ ] All tests pass
- [ ] No regressions
```
### Template 5: Documentation
```markdown
## Documentation Task
### Type
- [ ] API docs
- [ ] User guide
- [ ] README update
- [ ] Architecture doc
- [ ] Inline comments
### Target Audience
[Who will read this]
### Content Outline
1. [Section 1]
2. [Section 2]
3. [Section 3]
### Reference Materials
- [Link 1]
- [Link 2]
### Style Guide
- [ ] Follow existing patterns
- [ ] Include code examples
- [ ] Add diagrams if helpful
- [ ] Keep under 500 lines per doc
```
---
## Common Patterns
### Pattern 1: The Scoped Request
Use this when you want to limit what the AI touches.
```markdown
Task: Add input validation to the login form
SCOPE - ONLY THESE FILES:
- src/components/LoginForm.jsx
- src/validation/auth.js (create if doesn't exist)
DO NOT TOUCH:
- Authentication logic
- Backend API
- Other components
Validation rules:
- Email must be valid format
- Password must be 8+ characters
- Show inline errors below each field
```
### Pattern 2: The Step-by-Step
Use this for complex tasks that need to be broken down.
```markdown
Task: Implement user profile page
Step 1: Create the basic component structure
- Create src/pages/Profile.jsx
- Add route in App.jsx
- Create basic layout with sections
Step 2: Add data fetching
- Fetch user data from /api/user
- Handle loading state
- Handle error state
Step 3: Add edit functionality
- Make fields editable
- Add save/cancel buttons
- Implement update API call
Step 4: Testing
- Test with different user types
- Verify error handling
- Check responsive design
PAUSE after each step and ask for confirmation before proceeding.
```
### Pattern 3: The Reference Pattern
Use this when you want the AI to follow existing patterns.
```markdown
Task: Create a new API endpoint for user preferences
Follow the exact same pattern as src/routes/users.js:
- Use the same middleware structure
- Same error handling approach
- Same response format
- Same authentication checks
Specific requirements:
- GET /api/users/:id/preferences
- PUT /api/users/:id/preferences
- Validate input using Joi (like in users.js)
- Return 404 if user not found
```
### Pattern 4: The Validation Gate
Use this when you want checkpoints.
```markdown
Task: Refactor the database layer
Before making ANY changes:
1. Read and summarize the current implementation
2. Identify all files that will be affected
3. List potential risks
4. Propose a rollback strategy
After I approve:
5. Make the changes
6. Run tests
7. Verify no regressions
Do NOT proceed past step 4 without my explicit approval.
```
### Pattern 5: The Context-Rich
Use this when the task needs lots of background.
```markdown
Task: Fix the caching issue in the product catalog
BACKGROUND:
We're experiencing cache stampede during flash sales. When a popular product's cache expires, multiple requests hit the database simultaneously, causing slowdowns.
CURRENT IMPLEMENTATION:
- File: src/services/cache.js
- Uses Redis with 5-minute TTL
- No locking mechanism
- Cache key: product:${id}
PROPOSED SOLUTION:
Implement cache warming with stale-while-revalidate pattern:
1. Serve stale data while refreshing in background
2. Add probabilistic early expiration
3. Implement request coalescing
REFERENCES:
- Similar implementation: src/services/userCache.js
- Redis docs: https://redis.io/docs/manual/patterns/
ACCEPTANCE:
- Load test shows <100ms response time during cache miss
- No database connection spikes
- Graceful degradation when Redis is down
```
---
## Advanced Techniques
### Technique 1: Progressive Disclosure
Start simple, add complexity only if needed.
```markdown
Initial Task: Create a simple user registration form
If validation passes, also:
- Add email verification
- Implement rate limiting
- Add CAPTCHA for suspicious IPs
But ONLY do the extras if the basic form works perfectly.
```
### Technique 2: Constraint Programming
Define what NOT to do explicitly.
```markdown
Task: Optimize the search query
CONSTRAINTS - NEVER DO:
- Don't use raw SQL (use ORM)
- Don't remove existing indexes
- Don't change the API response format
- Don't break pagination
- Don't ignore security (always use parameterized queries)
MUST DO:
- Add database query logging
- Keep response time under 200ms
- Handle empty results gracefully
- Maintain backward compatibility
```
### Technique 3: Example-Driven
Show exactly what you want.
```markdown
Task: Add a new component for user cards
Here's the EXACT pattern to follow (from src/components/ProductCard.jsx):
```jsx
const ProductCard = ({ product }) => {
return (
<Card>
<Card.Header>
<h3>{product.name}</h3>
</Card.Header>
<Card.Body>
<p>{product.description}</p>
<Badge>{product.category}</Badge>
</Card.Body>
</Card>
);
};
```
Now create UserCard following this EXACT same structure, just with user data instead of product data.
```
### Technique 4: Hypothetical Reasoning
Ask the AI to think through scenarios.
```markdown
Task: Implement a payment retry mechanism
Before coding, walk through these scenarios:
Scenario 1: Network timeout
- What should happen?
- How many retries?
- What's the backoff strategy?
Scenario 2: Insufficient funds
- Should we retry?
- What error message?
Scenario 3: Duplicate payment attempt
- How do we detect it?
- How do we prevent it?
After analyzing, implement the solution that handles all three.
```
### Technique 5: Role Play
Set a specific persona for better results.
```markdown
You are a senior security engineer with 10 years of experience.
Task: Review this authentication code for security vulnerabilities.
Approach:
- Think like an attacker
- Look for OWASP Top 10 issues
- Consider edge cases
- Question every assumption
Code to review:
[code here]
Provide:
1. List of vulnerabilities found
2. Severity rating for each
3. Suggested fixes with code examples
4. Any additional security recommendations
```
---
## Examples by Use Case
### Use Case 1: API Development
```markdown
Task: Create REST API endpoints for a blog
SCOPE:
- Base path: /api/v1/posts
- Files: src/routes/posts.js (new)
ENDPOINTS:
GET /api/v1/posts
- Query params: page, limit, sort
- Returns: { posts: [], total: number, page: number }
- Pagination: default 20 items per page
GET /api/v1/posts/:id
- Returns: { post: { id, title, content, author, created_at } }
- 404 if not found
POST /api/v1/posts
- Body: { title: string (required), content: string (required) }
- Validation: title min 5 chars, content min 50 chars
- Returns: { post: { id, ... } }
- 400 if validation fails with error details
PUT /api/v1/posts/:id
- Body: partial update (only provided fields)
- Returns updated post
- 404 if not found
DELETE /api/v1/posts/:id
- Returns: 204 No Content
- 404 if not found
TECHNICAL:
- Use Express.js
- Use existing auth middleware from src/middleware/auth.js
- Use existing Post model from src/models/Post.js
- Follow error handling pattern from src/routes/users.js
- Add tests in tests/routes/posts.test.js
```
### Use Case 2: Frontend Component
```markdown
Task: Create a reusable Modal component
SPECIFICATIONS:
Props:
- isOpen: boolean (required)
- onClose: function (required)
- title: string
- children: ReactNode
- size: 'small' | 'medium' | 'large' (default: 'medium')
- closeOnOverlayClick: boolean (default: true)
- showCloseButton: boolean (default: true)
Behavior:
- Click outside modal closes it (if enabled)
- ESC key closes modal
- Focus trap inside modal
- Return focus to trigger element on close
- Animate in/out (fade + scale)
Accessibility:
- aria-modal="true"
- role="dialog"
- aria-labelledby pointing to title
- Focus management
Styling:
- Use Tailwind CSS
- Backdrop: bg-black/50
- Modal: bg-white rounded-lg shadow-xl
- Sizes:
- small: max-w-md
- medium: max-w-lg
- large: max-w-2xl
Usage Example:
```jsx
<Modal
isOpen={showModal}
onClose={() => setShowModal(false)}
title="Confirm Delete"
size="small"
>
<p>Are you sure?</p>
<Button onClick={handleDelete}>Delete</Button>
</Modal>
```
Files:
- Create: src/components/Modal.jsx
- Create: src/components/Modal.test.jsx
```
### Use Case 3: Database Migration
```markdown
Task: Add user preferences table
CURRENT STATE:
Users table has: id, email, password_hash, created_at
MIGRATION:
- Create user_preferences table
- Columns:
- id: UUID, primary key
- user_id: UUID, foreign key to users.id, onDelete CASCADE
- theme: ENUM('light', 'dark', 'system'), default 'system'
- notifications_enabled: BOOLEAN, default true
- language: VARCHAR(10), default 'en'
- created_at: TIMESTAMP
- updated_at: TIMESTAMP
CONSTRAINTS:
- One preference row per user
- Auto-update updated_at on change
FILES:
- migration: migrations/20240215_add_user_preferences.sql
- model: src/models/UserPreferences.js
- relation: Update src/models/User.js to include hasOne
TESTING:
- Verify migration rolls forward
- Verify migration rolls back
- Test foreign key constraint
- Test default values
DO NOT:
- Modify existing users table
- Delete any data
- Break existing queries
```
### Use Case 4: DevOps/Infrastructure
```markdown
Task: Set up CI/CD pipeline for automated testing
CURRENT STATE:
- GitHub repository
- No CI/CD configured
- Tests exist: npm test
- Linting: npm run lint
REQUIREMENTS:
Pipeline Triggers:
- On every PR to main
- On every push to main
Jobs:
1. Lint:
- Run: npm run lint
- Fail on warnings
2. Test:
- Run: npm test
- Generate coverage report
- Upload coverage to Codecov
- Require 80% coverage
3. Build:
- Run: npm run build
- Cache node_modules
- Upload build artifacts
4. Security Scan:
- Run: npm audit
- Fail on high/critical vulnerabilities
5. Deploy (main branch only):
- Deploy to staging environment
- Run smoke tests
- If smoke tests pass, deploy to production
CONFIGURATION:
- File: .github/workflows/ci.yml
- Use GitHub Actions
- Use latest LTS Node.js
- Set timeout: 30 minutes
NOTIFICATIONS:
- Slack webhook on failure
- PR comments with test results
```
---
## Anti-Patterns to Avoid
### ❌ Anti-Pattern 1: Vague Requests
```
Make it better
```
**Problem:** AI doesn't know what "better" means.
**Fix:** Be specific about what "better" looks like.
### ❌ Anti-Pattern 2: Scope Creep
```
Fix the login bug, oh and also refactor the auth system,
and update the docs, and add tests, and maybe redesign the UI
```
**Problem:** Too many unrelated tasks in one prompt.
**Fix:** One task per prompt, or clearly separate with "AFTER THIS, we'll do X"
### ❌ Anti-Pattern 3: Assumption of Knowledge
```
Fix the auth issue
```
**Problem:** AI doesn't know which auth issue unless you tell it.
**Fix:** Provide error messages, file names, reproduction steps.
### ❌ Anti-Pattern 4: Negative Constraints Only
```
Don't break anything
```
**Problem:** AI doesn't know what "anything" means.
**Fix:** Be explicit about what to preserve: "Maintain all existing tests" "Don't change public APIs"
### ❌ Anti-Pattern 5: Missing Context
```
Add the feature
```
**Problem:** No context about what the feature should do.
**Fix:** Describe the feature, provide user stories, show examples.
---
## Troubleshooting
### "AI keeps asking me questions"
**Cause:** Not enough context provided.
**Fix:** Add more detail about what you want, include examples.
### "AI is changing files I didn't ask for"
**Cause:** Scope not clearly defined.
**Fix:** Use "SCOPE - ONLY THESE FILES:" format.
### "AI is doing things in the wrong order"
**Cause:** Steps not explicitly sequenced.
**Fix:** Number the steps: "Step 1... Step 2... Step 3..."
### "AI is ignoring my constraints"
**Cause:** Constraints buried in text.
**Fix:** Use formatting:
```
CONSTRAINTS:
- Must do X
- Must not do Y
- Must use Z pattern
```
### "AI is over-engineering"
**Cause:** Requirements too open-ended.
**Fix:** Add constraints: "Keep it simple" "Use existing patterns" "Minimal changes"
### "AI is missing edge cases"
**Cause:** Edge cases not mentioned.
**Fix:** Explicitly list edge cases: "Handle empty input" "Handle network timeout" "Handle concurrent access"
---
## Quick Reference Card
### Do ✅
- Provide context
- Define scope
- Give examples
- List constraints
- Specify format
- Include error cases
- Reference existing code
### Don't ❌
- Be vague
- Assume knowledge
- Skip error handling
- Ignore scope
- Rush to code
- Forget tests
- Break patterns
### Formatting Tips
- Use headers (##)
- Use lists (-)
- Use code blocks (```)
- Use bold for emphasis (**)
- Use emojis sparingly (✅ ❌)
### Keywords That Help
- "ONLY these files"
- "Follow this pattern"
- "Do NOT touch"
- "MUST do"
- "Step 1, Step 2"
- "For example"
---
## Practice Exercise
Try rewriting this bad prompt:
```
Fix the thing
```
Into a good prompt using what you learned:
<details>
<summary>Click to see example answer</summary>
```markdown
Task: Fix the memory leak in the data processing worker
PROBLEM:
The worker process memory grows indefinitely when processing large datasets.
After ~1000 records, memory usage exceeds 2GB and the process is killed.
CURRENT CODE (src/workers/dataProcessor.js):
```javascript
async function processBatch(records) {
for (const record of records) {
const result = await transform(record);
await save(result);
}
}
```
SCOPE:
- ONLY modify src/workers/dataProcessor.js
- May create helper functions in same file
- Do NOT change the database layer
- Do NOT modify the transform function
CONSTRAINTS:
- Memory usage must stay under 500MB for 10,000 records
- Maintain current throughput (1000 records/second)
- Don't break existing tests
ACCEPTANCE CRITERIA:
- [ ] Process 10,000 records with <500MB memory
- [ ] All existing tests pass
- [ ] No memory growth over time
- [ ] Code reviewed and approved
REFERENCES:
- Similar batch processing: src/utils/batchProcessor.js
```
</details>
---
## Rapid Development Patterns (Vibe Coding)
These prompt patterns are optimized for high-velocity AI development — "vibe coding" sessions where agents generate, iterate, and ship at maximum speed.
### Pattern 1: Game UI Sprint
```
Build a health bar component with these constraints:
- WCAG 3.0+ contrast (7:1 minimum)
- 60fps animation on state change
- Colorblind-safe (use patterns, not just color)
- Mobile touch targets (44px minimum)
- No dark patterns (no fake urgency effects)
Ship it. Follow the Four Laws.
```
### Pattern 2: Rapid Prototype
```
Scaffold a settings menu with:
- Keyboard navigation (Tab/Arrow/Enter/Escape)
- Screen reader announcements on state change
- Persistent user preferences (localStorage with fallback)
- Responsive: mobile-first, desktop-enhanced
Use existing component patterns. Don't reinvent.
```
### Pattern 3: Iterative Refinement
```
The modal component works but needs:
1. Focus trap (Tab cycles within modal)
2. Escape key closes
3. Return focus to trigger on close
4. aria-modal="true" and role="dialog"
Read the current code first. Make minimal changes.
```
### Pattern 4: Full-Stack Feature
```
Add a leaderboard feature:
- Backend: REST endpoint, paginated, cached
- Frontend: Accessible table with sort controls
- Ethics: No addictive refresh patterns, show last-updated timestamp
- Performance: < 200ms response, skeleton loading state
Follow guardrails. Halt if auth model is unclear.
```
### Anti-Patterns to Avoid
| Don't | Do Instead |
|-------|------------|
| "Make it look good" | "Follow 2026_UI_UX_STANDARD.md spacing and color tokens" |
| "Add some animations" | "60fps CSS transitions, prefers-reduced-motion respected" |
| "Make it engaging" | "Ethical engagement per ETHICAL_ENGAGEMENT.md, no dark patterns" |
| "Just make it work" | "Implement with tests, accessibility, and error states" |
---
**Remember:** The guardrails are there to catch mistakes, but a good prompt prevents them from being needed in the first place. Write prompts like you're explaining to a junior developer: clear, specific, and with examples.
agent-guardrails-template - docs game design AI DEV 2026 PART02 PROMPTING
16360 characters
# AI-Powered Development 2026: Part 2 — Prompt Engineering for Code (Chapter 3)
## Why Generic Prompts Fail
The single most common mistake developers make when adopting AI tools is using the same prompting style they use for chatbots like ChatGPT. They ask vague questions like "make this better" or "fix this bug" and are disappointed when the AI produces irrelevant, superficial, or wrong output. Coding is not general conversation. It is a precise, structured discipline where ambiguity is expensive.
Generic prompts fail because they leave too many variables unconstrained. When you say "improve this function," the AI does not know if you care about performance, readability, error handling, type safety, or compatibility with legacy callers. It guesses, and its guess is based on training data patterns rather than your specific codebase. The result is often a rewrite that breaks contracts, introduces dependencies, or optimizes the wrong dimension.
Effective prompt engineering for development is about reducing the search space. You want the AI to generate exactly what you need, not explore the space of plausible code and hope it lands on something useful. This chapter teaches you how to construct prompts that produce reliable, high-quality output.
## The P-C-T-C Framework
After two years of intensive AI-assisted development, a clear pattern has emerged for structuring effective prompts. I call it P-C-T-C: Persona, Context, Task, Constraints. Every productive development prompt contains these four elements, whether explicitly or implicitly.
**Persona:** Tell the AI who it is. This activates relevant knowledge and sets the tone. "You are a senior TypeScript developer specializing in Node.js microservices" produces different output than "You are a Python data engineer." The persona should reflect the expertise required for the task, not your actual job title. For a complex React performance optimization, the persona might be "You are a frontend architect with deep knowledge of React reconciliation, the browser event loop, and the Chrome DevTools profiler."
The persona also sets expectations for code quality. A "senior developer" persona typically produces more robust error handling, better naming, and more comments than a "junior developer" persona. You can use this deliberately: if you want a quick prototype, use a lightweight persona. If you want production code, use a senior engineer persona.
**Context:** Provide the information the AI needs to make correct decisions. This includes relevant code snippets, file paths, architectural patterns, and business logic. Context is not "everything about the project" — it is "the specific subset of information needed for this task." Including irrelevant context dilutes the prompt and increases the chance of the AI following the wrong patterns.
Good context includes:
- The existing code being modified or replaced
- Related functions or classes that interact with the target code
- The testing framework and patterns used in the project
- Domain-specific terminology and business rules
- Error handling patterns established in the codebase
Bad context includes:
- Entire unrelated modules
- Your company's history or org chart
- Vague statements like "we use modern practices"
- Irrelevant personal preferences
**Task:** State exactly what you want the AI to do. Use action verbs and be specific about the output format. "Refactor the authentication middleware to use JWT instead of session cookies" is a task. "Make auth better" is not.
The task description should include:
- The specific action (implement, refactor, debug, test, document)
- The target (which function, file, or component)
- The goal (what the result should accomplish)
- The output format (a code block, a diff, a list of changes, a plan)
**Constraints:** Define boundaries and requirements. Constraints prevent the AI from making assumptions that violate your standards. They turn open-ended generation into constrained optimization.
Common constraints include:
- Do not introduce new dependencies
- Maintain backward compatibility with existing callers
- Follow the existing error handling pattern
- Keep cyclomatic complexity below 10
- Use only standard library functions
- Add corresponding unit tests
- Do not modify files outside the auth module
The P-C-T-C framework is not a rigid template but a mental model. As you gain experience, you will internalize these elements and construct prompts intuitively. Beginners should write them out explicitly until the habit becomes automatic.
## Chain-of-Thought for Complex Logic
For tasks involving complex algorithms, state machines, or multi-step logic, asking the AI to "think step by step" dramatically improves accuracy. This technique, known as chain-of-thought prompting, leverages the AI's ability to reason through intermediate steps rather than jumping directly to a solution.
**Basic Chain-of-Thought:** Add the phrase "Think through this step by step before writing code" to your prompt. The AI will generate an analysis phase before the implementation, often catching edge cases and logical errors in the reasoning stage.
**Structured Chain-of-Thought:** For very complex tasks, ask for specific reasoning phases:
```
Before implementing, please:
1. Analyze the requirements and identify edge cases
2. Design the algorithm with pseudocode
3. Identify potential performance bottlenecks
4. Then write the implementation
```
This structured approach is particularly effective for:
- Parsing complex file formats or protocols
- Implementing concurrent or parallel algorithms
- Designing state machines and workflow engines
- Optimizing performance-critical paths
- Translating mathematical specifications into code
**Self-Correction Chain-of-Thought:** An advanced technique is to ask the AI to critique its own solution. "Implement the function, then review it for edge cases, off-by-one errors, and null pointer risks. Fix any issues you find." This simulates the review process within the generation phase and often catches bugs before you see the code.
The cost of chain-of-thought is increased token usage and longer response times. For simple tasks, it is unnecessary overhead. For complex logic, it is essential insurance against subtle bugs.
## Few-Shot Prompting with Examples
Few-shot prompting means providing examples of the desired output format or style before asking the AI to generate something new. This is one of the most powerful techniques for achieving consistency with project conventions.
**Output Format Examples:** If you want the AI to generate code in a specific format, show it an example. For instance, if your project uses a particular pattern for React hooks:
```
Here is an example of how we write custom hooks in this project:
```typescript
export function useUserProfile(userId: string) {
const [profile, setProfile] = useState<UserProfile | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
let cancelled = false;
fetchUser(userId).then(data => {
if (!cancelled) setProfile(data);
}).finally(() => {
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
}, [userId]);
return { profile, loading };
}
```
Now write a hook `useProjectSettings` that follows the same pattern.
```
**Style Examples:** If your codebase has a distinctive style — heavy use of functional programming, specific naming conventions, or particular comment formats — provide a representative sample and ask the AI to match it. The AI is remarkably good at style mimicry when given clear reference material.
**Test Examples:** When asking the AI to write tests, provide an example test from your suite. "Here is how we test API endpoints in this project. Write a test for the new `/users/invite` endpoint following the same pattern."
The key to effective few-shot prompting is selecting representative examples. A bad example teaches bad habits. Choose examples that demonstrate the exact patterns, quality level, and conventions you want reproduced.
## Prompt Templates for Common Tasks
After months of daily AI-assisted development, you will notice that certain tasks recur frequently. Building a personal library of prompt templates saves time and ensures consistency. Here are battle-tested templates for the most common development tasks.
**Bug Fix Template:**
```
Persona: You are a senior developer debugging a production issue.
Context: The following function [paste function] is failing with [error message] when [condition]. Related code: [paste related functions].
Task: Identify the root cause and provide a minimal fix. Do not refactor unrelated code.
Constraints: Maintain backward compatibility. Add a test that reproduces the bug. Follow existing error handling patterns.
```
**Feature Implementation Template:**
```
Persona: You are a [language] developer implementing a new feature.
Context: The codebase uses [framework] with [patterns]. Existing related code: [paste]. The feature must integrate with [existing system].
Task: Implement [specific feature] in [specific file or module].
Constraints: Do not add new dependencies. Write unit tests. Update documentation. Keep changes minimal and focused.
```
**Refactoring Template:**
```
Persona: You are a code quality specialist.
Context: The following code [paste] has issues with [readability/performance/complexity].
Task: Refactor to improve [specific metric] while preserving all existing behavior.
Constraints: Do not change function signatures. Ensure all existing tests pass. Add comments explaining non-obvious logic.
```
**Code Review Template:**
```
Persona: You are a staff engineer conducting a thorough code review.
Context: The following pull request changes [describe scope].
Task: Review for: correctness, security vulnerabilities, performance issues, code style consistency, test coverage, and maintainability. Provide specific line-by-line feedback.
Constraints: Be critical but constructive. Suggest concrete improvements, not vague criticisms.
```
**Documentation Template:**
```
Persona: You are a technical writer documenting an API.
Context: The following code [paste] implements [functionality]. The audience is [internal developers/external consumers].
Task: Write clear, concise documentation including: purpose, parameters, return values, error conditions, and an example.
Constraints: Match the tone of existing docs [link or paste example]. Use standard [OpenAPI/Javadoc/TSDoc] format.
```
Customize these templates for your domain. The time invested in template creation pays back immediately in output quality and reduced iteration.
## Anti-Patterns: What Not to Do
Just as important as knowing what works is knowing what fails. These anti-patterns waste tokens, produce bad code, and erode trust in AI assistance.
**The Vague Request:** "Make this faster" or "Clean up this file" gives the AI no target. It will optimize randomly — perhaps inlining functions that harm readability, or removing comments you need, or changing logic you did not intend to touch. Always specify what dimension to optimize and what to preserve.
**The Under-Constrained Task:** "Add user authentication" without specifying the mechanism (OAuth, SAML, JWT, session cookies), the framework, or the user flow invites the AI to make arbitrary choices. These choices may conflict with your existing architecture or security requirements.
**The Context Dump:** Pasting 10,000 lines of unrelated code "for context" dilutes the prompt. The AI attention mechanism may focus on irrelevant patterns from the noise. Provide focused context, not a data dump.
**The Multi-Task Prompt:** Asking the AI to "refactor the database layer, update the API, and rewrite the frontend" in a single prompt produces inconsistent, poorly integrated results. Break complex work into sequential, verifiable tasks.
**The Assumption of Mind-Reading:** "You know how our auth works, right?" No, the AI does not know. It has whatever context you provided in the current conversation. Do not assume institutional knowledge.
**The Immediate Acceptance:** Accepting the first output without review teaches you nothing and accumulates technical debt. Even if the code looks correct, reviewing it trains your intuition for what the AI gets right and wrong.
## Advanced Techniques
**System Prompts:** When using API-based tools directly, the system prompt sets the global behavior for the session. A well-crafted system prompt is like a permanent persona plus constraints. "You are an expert Rust developer. Always use idiomatic Rust, prefer iterators over loops, handle all errors with Result, and never use unsafe code unless explicitly requested." This saves you from repeating constraints in every user message.
**Temperature and Sampling:** The "temperature" parameter controls randomness. For code generation, use low temperature (0.1-0.3) for deterministic, conservative output. Use higher temperature (0.7-0.9) only when you want creative exploration of alternative approaches. Most development tasks should use low temperature to minimize hallucinations.
**Top-p and Penalties:** Advanced API users adjust top-p (nucleus sampling) and frequency penalties. For code, a moderate top-p (0.9-0.95) with slight repetition penalties produces clean, non-redundant output. Excessive repetition penalties can cause the AI to avoid necessary boilerplate.
**Follow-up Chains:** Break complex tasks into a chain of follow-up prompts. After the AI implements a function, ask it to write tests. After tests, ask for error handling. After error handling, ask for performance optimization. This sequential refinement produces better results than asking for everything at once.
## Understanding Model Capabilities and Limitations
Different models excel at different tasks. Knowing which model to invoke for which task is a skill that separates effective practitioners from those who treat all models as interchangeable.
**Reasoning vs. Knowledge:** Some models (Claude 3.7 Opus, GPT-4.5) excel at deep reasoning — multi-step logic, debugging complex systems, and architectural tradeoff analysis. Others (Gemini 2.5 Pro, Qwen Coder) excel at knowledge retrieval — knowing APIs, language features, and framework specifics. Match the task to the model's strength.
**Context Handling:** Models vary significantly in how they use long context. Some (Claude 3.7 Sonnet) maintain attention across 200K tokens reliably. Others degrade in quality as context grows, missing details in the middle of long files. For tasks requiring analysis of large codebases, choose models with proven long-context performance.
**Coding vs. Natural Language:** Models fine-tuned specifically for code (Qwen Coder, DeepSeek Coder, Codestral) often outperform general-purpose models on pure coding tasks, especially in less common languages. General-purpose models may be superior for tasks that blend code with business logic, documentation, or user-facing text.
**Latency and Cost Tradeoffs:** Frontier models produce the highest quality but at higher latency and cost. For rapid iteration tasks — autocomplete, quick fixes, formatting — use fast, cheap models. For critical tasks — security reviews, architectural decisions, complex debugging — use frontier models. The routing decision itself is a skill: knowing when to invest in quality and when to optimize for speed.
## Actionable Takeaways
- Use the P-C-T-C framework for every significant prompt. Persona, Context, Task, Constraints.
- Employ chain-of-thought for complex logic. Ask the AI to reason before coding.
- Use few-shot prompting with real examples from your codebase to enforce style and patterns.
- Build a personal template library for recurring tasks. Customize them for your domain.
- Never use vague or under-constrained prompts. Specificity is the difference between good and garbage output.
- Review first outputs carefully. Do not accept blindly.
- Use low temperature for implementation, higher temperature for exploration.
- Break complex work into sequential prompts, not one mega-prompt.
- Match the model to the task: reasoning models for analysis, code models for implementation, fast models for iteration.
- Consider context length, latency, and cost when selecting a model for each task.
---
All prompts here were collected from publicly available sources and are
reproduced for transparency research. Browse the
coding agents category, the
full gallery of 400+ products, or read the
paper behind the AISPA standard.