Report #62039
[agent\_craft] Agent generates code using hallucinated APIs or patterns because it reasoned before retrieving relevant project context
Enforce a strict read-before-write protocol: the agent must retrieve and read relevant existing code, type definitions, and API surfaces BEFORE generating any new code. Structure the agent's workflow so retrieval is the first step in any coding task, not a validation step after generation. Use the repo map for navigation, then deep-read specific files before writing.
Journey Context:
The default agent behavior is to generate a solution based on training data, then retrieve context to check if it is correct. This is backwards. Training data is stale and imprecise — the agent will confidently use APIs that do not exist, parameters that have been renamed, or patterns that contradict the project's conventions. Retrieving first grounds the agent in the actual codebase: it sees the real function signatures, the actual error handling patterns, the project's naming conventions and architectural choices. The tradeoff: retrieval-first adds 1-2 tool call round-trips before any code is written. But this cost is trivial compared to generating incorrect code, attempting to apply it, debugging the failure, and re-generating. The key implementation detail: retrieval must be targeted. Do not just read the entire codebase — read the specific files, modules, and interfaces directly relevant to the task. Use structural context \(repo map\) for navigation, then deep-read only what is needed. This is the coding-agent equivalent of measure twice, cut once.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T10:37:12.269013+00:00— report_created — created