Planning & Prompting
Why Planning Wins
Planning is the Highest-Leverage Activity
Teams skipping specs often see an initial velocity boost that degrades as technical debt accumulates. As a rule of thumb, a modest up-front investment in planning tends to prevent a large share of rework downstream.
The Hard-Coded Data Trap
When AI can't solve a problem after multiple attempts, it fabricates data instead of admitting failure
Solution: Set up your data structure (Supabase, Airtable, Postgres) before generating any code. Otherwise, AI will hardcode data into the frontend, creating something that looks functional but isn't.
From Vibe Coding to Context Engineering
MIT Technology Review, November 2025
The field has shifted from loose, vibes-based prompting to a systematic approach for managing AI context. Andrej Karpathy endorsed the concept: context engineering is "the delicate art and science of filling the context window with just the right information for the next step."
Context engineering means systematically curating project architecture, coding standards, documentation, and constraints instead of relying on ad-hoc prompting. If prompt engineering was about crafting clever one-liner instructions, context engineering is about writing the full screenplay.
Ad-hoc Prompting
One-off instructions, inconsistent results, lost context between sessions
Prompt Engineering
Structured prompts, better outputs, still session-dependent
Context Engineering
Persistent rules, project architecture, curated documentation, constraints
Designing a PRD
Minimum Viable PRD Structure
- 1Problem Statement: What problem are you solving, and for whom?
- 2Core Features: 5-7 features maximum for v1. No more.
- 3User Roles: Who uses the app and what each role can do.
- 4User Flows: Step-by-step paths through the application.
- 5Data Model: What data exists and how it relates.
- 6Tech Stack: React/Next.js, Supabase, Tailwind, etc. with versions.
- 7Non-Functional Requirements: Performance, security, deployment targets.
Common PRD Mistakes
- Overly long AI-generated PRDs. Product leader Aakash Gupta observed that "PMs started using LLMs to create overly long PRDs that said nothing." A bloated, vague spec is worse than a short, precise one, because the model fills every gap with its own assumptions.
- Missing data architecture. Without explicit database schemas and API contracts, AI hardcodes data into frontends.
- Mixing too many features. Use milestone-based PRDs with 5-7 incremental steps, each with clear success criteria.
- Vague technical context. Always specify tech stack versions, auth strategy, database choice, error handling, and performance requirements.
Choose a Starting Template
Pick an app archetype to pre-fill features, screens, data models, and roles. You can customize everything later.
Feature-Level Specifications
For each feature, write user stories in this format:
"As a [role], I want to [action], so that [outcome]."
Acceptance Criteria
Specific conditions that must be true for the feature to be complete. Use checkboxes in your spec.
Edge Cases
What happens with empty inputs, network errors, unauthorized access, or duplicate submissions?
Data Requirements
What fields, validations, and relationships are needed? Define these before code generation.
Wireframing Saves Credits
Wireframes eliminate ambiguity and dramatically improve AI code generation quality. A visual reference prevents the AI from guessing at layout, reducing hallucination and wasted tokens.
Figma
Industry standard. Free for personal use.
Excalidraw
Free. Great for casual sketching and diagrams.
Whimsical
Fast wireframing with built-in flowcharts.
Using a consistent design system in your PRD tells AI exactly which components to use. This reduces hallucination and credit waste significantly.
Database Design: The Spreadsheet Analogy
Tables = Spreadsheets
Each table is a spreadsheet: Users, Products, Orders. Separate concerns into separate tables.
Rows = Records
Each row is one record: one user, one product, one order. Each row gets a unique ID.
Columns = Fields
Each column is a field: name, email, price, created_at. Define data types for each.
Relationships
Connect tables with foreign keys. An Order has a user_id column pointing to the Users table.
- SaaS: Users, Organizations, Subscriptions, app-specific data tables
- E-commerce: Products, Categories, Orders, OrderItems, Payments, Addresses
- Content Platform: Users, Posts, Comments, Tags, Likes
- Booking System: Services, TimeSlots, Bookings, Payments, Reviews
- No relationships defined: AI creates disconnected tables with no foreign keys.
- No unique constraints: Leads to duplicate records that are painful to clean up.
- Missing indexes: Queries on frequently searched fields become extremely slow.
- No cascade behavior: What happens to orders when a user is deleted? Define this upfront.
Prompting & Context Engineering
Code Prompting is Specification, Not Conversation
When generating text, vague prompts can produce useful results. With code, vague prompts produce code that compiles but does the wrong thing. Every ambiguity becomes a decision the AI makes without you, often incorrectly.
Model Selection for Code Generation
Based on the 2026 SWE-bench Verified leaderboard and practitioner consensus
| Model | SWE-bench Verified | Best For |
|---|---|---|
| Claude Opus 4.8 | 88.6% | Architecture, planning, and the hardest multi-file bugs (current flagship) |
| Claude Sonnet 5 | 82.1% | Implementation; the best cost/performance workhorse |
| GPT-5.5 | 82.6% | General purpose, strong reasoning |
| Gemini 3.5 Flash | 78.8% | Budget pick, fast, generous free tier |
Benchmark Reality Check
A top model scoring in the high 80s on SWE-bench Verified doesn't mean it one-shots that share of real tasks. SWE-bench Verified is 500 problems, all Python, with nearly half drawn from a single project, Django. The harder SWE-bench Pro is far tougher: at its 2025 launch, the best models, GPT-5 and Claude Opus 4.1, solved only about 23% of its tasks. Claude Sonnet 5 is a current practitioner sweet spot for cost-vs-quality. For budget work, Kimi K2 Thinking and Haiku 4.5 are gaining traction.
Prompt Structures That Work
PRD-to-Code
Include exact model IDs, hex color codes, port numbers, and specific library names. Use XML-structured specifications with 8-10 implementation phases (from Foundation and Database through Polish) and success criteria covering functionality, UX, and code quality.
Precision PromptingArchitect-Then-Implement
"I need to refactor {MODULE} from
{CURRENT_STATE} to {TARGET_STATE}.
Create a step-by-step migration plan where
each step is independently deployable,
can be rolled back, and has a verification
check. Do NOT write the code. I want the
plan reviewed before implementation starts."
Debug Prompts
Share the full error message, the file it occurred in, what you expected, and what actually happened. Don't add commentary or theories. Let the AI diagnose from raw data.
Error: [full error message]
File: [file path]
Expected: [behavior]
Actual: [behavior]
Incremental Build
Addy Osmani's approach: "Implement Step 1 from the plan." Code that step, test it, then move to Step 2. Each iteration carries forward context. Small chunks stay within the AI's reliable comprehension range.
1. "Implement Step 1 from the plan."
2. Test and verify.
3. "Implement Step 2 from the plan."
4. Test and verify.
5. Repeat until complete.
Context Management: Rules Files
Per-Tool Rules File Locations
| Tool | File | Location |
|---|---|---|
| Cursor | .cursor/rules/*.mdc | Project root |
| Windsurf | .windsurf/rules/rules.md | Project root |
| Claude Code | CLAUDE.md | Project root (hierarchical) |
| GitHub Copilot | .github/copilot-instructions.md | .github/ directory |
Real Production Example (Elementor)
# .cursorrules
Do not affirm my statements or assume my
conclusions are correct. Question assumptions,
offer counterpoints, test reasoning.
Prioritize truth over agreement.
# RULE REFRESH
Re-check this rules file every few messages.
Anti-Laziness Rule
You are an expert engineer.
You DO NOT use placeholders.
You output the FULL content of the file
every time.
You do not be lazy.
This widely-shared rule forces AI to output complete files instead of truncating with "rest of code here" comments.
CLAUDE.md: WHAT / WHY / HOW Framework
HumanLayer's context-engineering guidance: let deterministic tools like linters and formatters do their job instead of spending model tokens on what a linter already enforces.
Keep the root file to 100-200 lines. Total token budget: under 2,000 tokens. Don't put code style guidelines in rules files. Use deterministic formatters (Prettier, ESLint) instead.
WHAT
Tech stack, project structure, module map
WHY
Project purpose, architectural decisions, constraints
HOW
Build/test/deploy commands, verification steps
# CLAUDE.md Example
# Tech Stack
- Framework: Next.js 14, TypeScript 5.2, Tailwind CSS v4
# Commands
- npm run dev: Start dev server
- npm run build: Build for production
# Code Style
- Use ES modules (import/export), not CommonJS (require)
- Functional components with hooks
# Do Not
- Do not edit src/legacy/
- Do not commit to main directly
PatrickJS/awesome-cursorrules on GitHub (over 40,000 stars) contains 100+ real-world rules files for Next.js, React, Go, Python, Flutter, and more.
Memory Document Pattern
Maintain persistent markdown files as "external memory" for AI sessions. A session log tracks the current feature, active files, last changes, and architecture notes.
# Session Start Protocol
"Read context files before doing anything."
# Session Log
Current feature: User auth flow
Active files: auth.ts, middleware.ts
Last changes: Added JWT validation
Architecture notes: Using @supabase/ssr
# Session End Protocol
"Update all context files with what we
accomplished, current state, and any
open issues or next steps."
When to Start New Chats
Strong practitioner consensus: start fresh frequently. LLM attention is quadratic. Double your context, quadruple the computation. Start a new chat every 15-20 messages, especially when switching features.
# Handoff Protocol Template
"We are working on [feature].
Main files are [list].
Here is where we left off: [summary]."
15-20
Messages before starting fresh
O(n²)
Attention cost scales quadratically
Quality drops
Output degrades in long sessions
Managing Multi-File Changes
The architect-then-implement pattern is essential for changes spanning multiple files. Use a dedicated planning model (Claude Opus) to outline what files need to change and why. Then use an implementation model (Claude Sonnet) to execute each step.
Focus on Single Modules
Work on one folder or module at a time. AI accuracy drops sharply when editing many files simultaneously.
Maintain a Code Map
A document listing class/module names with purposes, parameters, and return values. No actual code. Dramatically reduces token usage.
Verify After Each Step
Build and test after each file change. Don't batch multiple file changes without verification between them.
Multi-LLM & Agent Workflows
Why Use Multiple Models?
Semgrep's 2025 evaluation found starkly different model strengths: Claude found 22% of IDOR bugs but only 5% of SQL injection. Codex found 47% of path traversal bugs but 0% of IDOR. Neither alone catches everything. Together they catch what neither would alone.
Model Strengths by Security Task
| Security Task | Best Model(s) | Evidence |
|---|---|---|
| SQL injection | GPT-4o (step-by-step prompting) | Highest overall F1 (0.9072) for vulnerability detection |
| IDOR / authorization bugs | Claude (Sonnet/Opus) | 22% TPR vs 0% for Codex (Semgrep) |
| Path traversal | OpenAI Codex/GPT models | 47% TPR vs lower for Claude (Semgrep) |
| Business logic flaws | Claude Opus | Best sustained reasoning, multi-file context |
| XSS detection | Claude + static analysis | All models struggle. Combine AI + SAST tools |
Cost-Effective Three-Pass Strategy
Estimated cost to review 1,000 lines of code (~15K input tokens + ~3K output tokens per pass)
DeepSeek
~$0.005
Catch obvious bugs and syntax issues
Claude Sonnet
~$0.09
Deep code review, IDOR detection, architecture
GPT-4o
~$0.08
Security-focused vulnerability detection
Total: ~$0.17 per 1,000 lines. Roughly 3x the cost of single-model review but with three independent perspectives. Using batch APIs (50% discount, 24-hour turnaround) drops this to ~$0.09.
Practitioner Workflows
Addy Osmani (Google Chrome)
Uses one main agent at a time plus a secondary agent for code reviews. Uses orchestration tools like Conductor to run multiple agents in parallel on different tasks.
Harper Reed
Separates the "thinking model" from the "building model." Uses ChatGPT for brainstorming and spec writing, then hands specs to a code-generation LLM.
CodeRabbit
Production multi-model code review. Their data shows AI-authored code produces 10.83 issues per PR versus 6.45 for human-only PRs.
Cursor Bugbot
Cursor documented running multiple bug-finding passes in parallel with randomized diff orderings, then combining results with majority voting so one-off flags get filtered out. Each pass nudges the model toward different reasoning.
AI Agent Workflow Patterns
Sequential Pipeline
Best for clear dependencies. Each agent's output feeds the next. Example: parse requirements, generate code, run tests.
Parallel Execution
Best for code review. Run a security auditor, style enforcer, and performance analyst all at once. Combine results.
Evaluator-Optimizer Loop
The generator produces code. The critic identifies flaws. The refiner fixes them. Loop three times, then output the final version.
Key Failure Modes in Long-Running Agents
Premature Completion
Agent marks features complete without actually testing them. Confidently reports success while leaving broken functionality.
Context Degradation
Performance drops as the context window fills. The agent starts forgetting earlier instructions and making contradictory decisions.
Feature Drift
Agent declares completion too early or adds unrequested features. Scope creep driven by the model's training patterns.
Fix: Document and Clear Pattern
Have the agent write its progress to a markdown file, clear the context window, then start a fresh session reading that markdown file. This resets context degradation while preserving progress.
The #1 Prompting Principle
"Architect first, code second." Ask AI to write a specification with milestones before writing any code. This prevents the AI from making irreversible decisions early that compound into larger problems later.
Prompting Strategy and Decomposition
Decomposition Strategy
Bad Prompt
"Build a task app with teams, calendar sync, and real-time notifications."
Good Prompt Sequence
- "Write a specification for a task app. List the data model, pages, and API routes. Do not write code."
- "Build a basic task list UI (React/Tailwind)."
- "Add ability to delete tasks."
- "Add checkbox to mark complete."
- "Now add local storage persistence."
Advanced Prompting Techniques
Specification Phase
"Before writing any code, create a detailed specification including data models, API endpoints, and user flows. I will review this before you proceed."
ArchitectureConstraint Forcing
"Implement this using ONLY the existing project dependencies. Do not add new packages. Do not use microservices. Keep it in a single file under 200 lines."
ControlSecurity-First Review
"Review this code for security vulnerabilities. Check for: exposed secrets, missing auth checks, SQL injection, XSS, and IDOR. List every issue found."
SecurityAdversarial Testing
"How could a malicious user break this feature? What happens with empty inputs, negative numbers, extremely long strings, or concurrent requests?"
Edge CasesReference Implementation
"Here is the existing auth pattern used in this project [paste code]. Follow this exact pattern when implementing the new feature."
ConsistencyIncremental Complexity
"Start with the simplest possible version that works. I'll ask for enhancements one at a time. Don't add features I haven't requested."
YAGNI