1. Why AI Forgets the Overall Project Structure
In large-scale projects, it is not your fault if an AI agent like Claude misses the mark. Models suffer from the "Lost in the Middle" phenomenon, where they focus only on the beginning and end of a conversation. Especially when the context window exceeds 60%, response quality plummets. If system instruction files are too long, the AI wastes tokens reading configuration files instead of the essential logic.
To prevent this, you must not force the AI to spread its attention too thin.
- Keep system instructions (CLAUDE.md) under 200 lines.
- Use the /compact command to summarize history when conversations get long.
- Instead of letting it scan the entire project, directly specify the working scope, such as lines 45-80 of a specific file.
2. Codebase Diet and Schema Design
Throwing the entire source code at an AI is inefficient. Instead, standardize interfaces first. Create separate schema files for APIs using OpenAPI and for data models using Zod or Pydantic. This way, the AI does not need to worry about the entire logic and only generates code within the provided specifications. Based on my personal testing, providing schemas like this reduced the number of repeat correction requests caused by the AI generating incorrect code by nearly 60%.
- Create .json or .yaml schemas for each module.
- Place an ai-context.md file containing only the core structure (under 100 lines) in the project root.
- Do not trigger a full search; use the grep command to extract and feed it only the necessary lines.
3. Verifying AI Code with a Test Sandbox
Code written by AI is often plausible but riddled with bugs. Use frameworks like Husky or pre-commit to block code that fails quality gates from being merged.
- Include eslint and tsc --noEmit in pre-commit hooks to fundamentally block syntax and type errors.
- Configure a PreToolUse hook to perform security scans immediately before code modifications to prevent API key leaks.
- When the main agent writes code, have a sub-agent write failing tests for that code. Running a loop until the tests pass (Green) helps catch bugs early.
4. Initializing Sessions with Branch Strategy
Side effects occur when an AI touches multiple files. To prevent this, use branches as work containers rather than just repositories. Splitting branches by feature allows you to isolate the AI so it only parses the latest changes.
- Even for a single feature like login, split branches (e.g., feature/auth-validation).
- When ending a session, always run /compact and write the remaining tasks in a current-handover.md file.
- When starting a new session, clear previous history with /clear, and reload only the necessary schema files and the handover document.
Following these steps will help prevent the AI from ruining code due to unnecessary past context.
