How to Prevent AI-Generated Spaghetti Code with CLAUDE.md and Detailed Specs
Preventing AI-Generated Spaghetti Code
The fastest way to create unmaintainable code is to give an AI agent a vague prompt and let it figure out the architecture. "Build a user authentication system" produces working code that's a nightmare to maintain. The agent makes dozens of implicit decisions about file structure, naming, error handling, and patterns - and none of them match your existing codebase.
CLAUDE.md Is Your Guardrail
A well-written CLAUDE.md file acts as architectural constraints for the AI agent. It should specify:
- File organization patterns - where new files go, naming conventions
- Code style - error handling approach, logging format, import ordering
- Architecture rules - "use repository pattern for data access," "no business logic in controllers"
- What NOT to do - "never use any-type in TypeScript," "no inline SQL queries"
The agent reads CLAUDE.md before writing any code. Every constraint you add there is a decision the agent won't make on its own - and that's exactly what you want.
Detailed Specs Beat Vague Prompts
Compare these two approaches:
Vague: "Add a notification system"
Detailed: "Add email notifications for failed payments. Create a NotificationService class in src/services/ that accepts a NotificationType enum and a userId. Use the existing EmailProvider in src/providers/email.ts. Store notification records in the notifications table. Follow the error handling pattern in src/services/billing.ts."
The second prompt constrains the agent into producing code that fits your existing architecture. It references specific files, follows established patterns, and limits scope.
The Specification Investment
Writing detailed specs feels slow, but consider the alternative: spending twice as long reviewing and refactoring AI-generated code that went in the wrong direction.
A 10-minute spec saves 30 minutes of cleanup. More importantly, it prevents the compounding problem - sloppy code that future AI sessions build on top of, creating layers of architectural debt.
Rules Worth Adding to Every CLAUDE.md
- Maximum file length before splitting
- Required test coverage for new functions
- Banned patterns and anti-patterns
- Reference files that exemplify the desired style
- Dependencies that should and shouldn't be used
The more specific your constraints, the less the agent improvises. And agent improvisation is how goop code happens.
Fazm is an open source macOS AI agent. Open source on GitHub.