AI Codebase Archaeology: The Evidence Packet to Build Before Your Agent Touches Legacy Code
From the publisher’s feed, collected in the ZeroLabs newsroom.
AI Codebase ArchaeologyA coding agent can read thousands of files and still invent the reason a strange branch exists. Before it edits an unfamiliar system, make it produce evidence you can inspect. The useful first output from an AI coding agent is not a patch. It is a traceable explanation of what the patch would touch.A familiar failure pattern is getting faster. A developer opens an inherited service, asks an AI agent to “clean up the payment flow,” and receives a tidy plan with confident language. The plan names a few modules, recommends an abstraction, and may even pass tests after the change. Then a forgotten retry rule, a compliance log, or an old client integration breaks because nobody established what the odd code was protecting.The problem is not that the agent cannot read. It is that reading source files is only one kind of evidence. A safe change may depend on call paths, Git history, production behavior, test gaps, external contracts, and decisions that never made it into a README. When an agent fills those gaps with a plausible story, the result can sound more certain than it is.Before an AI agent changes an unfamiliar area, ask it to build a small evidence packet for that one change. Facts get sources. Inferences get labels. Unknowns become work, not hidden assumptions.This approach is especially useful now. OpenAI’s planned acquisition of Pierre Computer Company highlights the growing focus on tools that help developers build, understand, and review code. As coding agents make it cheaper to create patches, understanding why existing code behaves as it does becomes the scarce skill. The answer is not to ban agents from legacy repositories. It is to give them a disciplined read-only phase with an exit gate.What an evidence packet changesAn evidence packet is a short, change-specific artifact. It is not a giant architecture document and it is not a dump of agent notes. Think of it as the material a cautious reviewer would want before approving the first write: what behavior is in scope, where it enters and exits, what evidence supports each claim, what is uncertain, and what must be proven before a change can merge.That constraint changes the agent’s behavior. “Explain this repository” invites a broad summary that is hard to verify. “Give me the entry point, three call edges, current behavior probe, historical signal, and unknowns for this checkout failure” invites a bounded investigation. The result is easier to review, cheaper to reproduce, and far more useful to the next engineer.Use this rule: an agent may summarize, but it may not present a design conclusion as a fact unless the packet links it to a file and symbol, a commit, a runtime observation, a test, or an explicitly named human source.The six parts of a useful AI codebase evidence packetKeep the packet small enough to read in one review. If a change is broad, split it by behavior instead of asking for a single “understand the whole repo” report.1. Change question and boundariesStart with one sentence: “What happens when a cancelled subscription is retried after its invoice is archived?” Then list what is in scope and what is deliberately out of scope. This prevents the agent from turning a bug fix into a cleanup project.Include the current branch and commit, relevant environment assumptions, and whether the task is read-only. A claim about a codebase without a revision is already stale. If the answer depends on production configuration, say so instead of quietly treating local defaults as truth.2. A concrete execution pathAsk the agent to follow one real input from trigger to durable side effect. For a web request, that might be route, authorization, command handler, domain rule, persistence, event publication, and background consumer. For an async job, start at the message or scheduler event.The packet should name only the important hops and attach an exact file path plus symbol or line range. A diagram is helpful, but it is not proof. The reader must be able to jump from each hop to the code that supports it.Read-only task: trace one failed checkout retry.For every hop, return:- file path and symbol- input received and output produced- side effect, if any- evidence type: source, test, runtime, or history- confidence: confirmed, likely, or unknownDo not propose edits. Stop when a claim lacks evidence.3. History that explains the strange partsCurrent code tells you what exists. History can reveal why it exists. An apparently redundant guard may have been added after an incident. Two files that look unrelated may nearly always change together. A “temporary” adapter may protect an external client that has not upgraded.Give the agent targeted history, not an invitation to narrate the entire repository. Start with the proposed change site, a suspicious condition, and its neighboring integration code.# Find when a behavior or literal appeared.git log -S 'archiveInvoice' --all -p -- src/billing# Read the file's story, including renames.git log --follow --date=short --format='%h %ad %s' -- src/billing/retry.ts# Find frequently co-changed files near the hot area.git log --format= --name-only -- src/billing | \ sort | uniq -c | sort -rn | head -20History is evidence, not a command. A commit message can be incomplete, and a frequent co-change is a lead rather than a dependency. Label it that way. The useful question is: “What should we verify because this history exists?”A strong packet joins independent evidence types instead of asking one model to infer the entire story from source text.4. Behavior probes and characterization testsStatic reading cannot settle every question. Dependency injection, feature flags, retries, date handling, and data shape often change behavior in ways that are invisible in one file. When possible, run the smallest safe probe that can disprove the agent’s explanation.For legacy code, that often means a characterization test. It records what the system does today, not what the team wishes it did. The test may reveal a bad behavior worth changing later, but it gives the review a baseline before an agent refactors the area.describe('archived invoice retry', () => { it('records the outcome without creating a second charge', async () => { const result = await retryInvoice(archivedInvoiceFixture()); expect(result.status).toBe('skipped'); expect(paymentGateway.charge).not.toHaveBeenCalled(); expect(auditLog.lastEvent()).toMatchObject({ type: 'retry_skipped' }); });});Do not let an agent write a test, see green, and declare understanding. Review the fixture and assertion with a domain owner when the behavior has financial, legal, security, or customer-facing impact. A green test only proves the test ran. It does not prove the test captured the right promise.5. Assumptions, unknowns, and disconfirming checksThis is the section that prevents a polished report from becoming a hallucination. Require the agent to list what it could not establish. Examples include a missing production config, an undocumented vendor retry policy, a branch with no representative fixture, or a database trigger outside the application repository.For every important assumption, ask for the cheapest way to disprove it. If the agent assumes a queue is at-least-once, the check might be a broker setting or an operational runbook. If it assumes a field is unused, the check might be a query, telemetry sample, or consumer inventory. Unknown does not mean blocked. It means someone must choose the evidence needed before the next irreversible step.6. A change contract and permission gateEnd the packet with a narrow proposal: files the agent may edit, files it must not touch, tests it must run, and conditions that require a human decision. This is not bureaucracy. It protects both the repository and the agent’s context from scope drift.Safe to write: a named module and its focused test, on an isolated branch or worktree.Human checkpoint: schema changes, access control, payment behavior, public contracts, or an unresolved high-impact assumption.Stop condition: a new call path, unmodeled side effect, failing characterization test, or evidence that contradicts the packet.Review proof: exact commands run, their result, changed paths, and which claims were confirmed or revised.Run the workflow in two passesMost teams do not need a new platform to use this. They need a repeatable split between exploration and modification.Pass one: explore with no write permissionGive the agent read-only access where your tooling permits it. Ask it to map the smallest behavior, inspect target history, locate tests, and write the packet. It should be allowed to run safe local commands, but not edit tracked files, alter infrastructure, call production services, or “fix” a failing test on the way.A good review question is simple: could another engineer reproduce this claim from the cited evidence in a few minutes? If not, the claim needs a better source or a lower confidence label.Pass two: make one bounded changeOnly after the packet is reviewed should the agent edit. Reuse the packet as the task brief, then constrain the work to the allowed paths. The final response should include a diff summary, tests run, the current commit, and a section called “packet changes” that says which earlier assumptions changed during implementation.This matters because implementation is new evidence. A test failure or unexpected call path is not an inconvenience to hide. It is feedback that the original model of the system was incomplete.A reusable prompt for the read-only phaseYou are in evidence-gathering mode. Do not edit files, create commits,or propose a final implementation yet.Task: [one behavior or question]Revision: [commit SHA]Scope: [folders, service, or component]Produce an evidence packet with:1. the question and scope boundaries;2. a trace of one concrete input through its important side effects;3. source citations as file path plus symbol or line range;4. relevant Git history signals and why they matter;5. tests or safe probes that confirm current behavior;6. assumptions, unknowns, and a disconfirming check for each;7. a narrow write proposal, stop conditions, and required validation.Mark every statement as confirmed, likely, or unknown. Never turn alikely statement into a design recommendation without saying what proofis still missing.Notice what this prompt does not ask for: a complete architecture diagram, a refactor, or a confident answer to every question. It rewards useful uncertainty. That is exactly what you want before a tool that can make changes begins to optimize for completion.Where teams get this wrongThe first mistake is treating a long context window as a substitute for evidence. More files may give an agent more clues, but they do not reveal runtime state, undocumented operations, or a missing external contract. The second is saving a sprawling agent transcript as documentation. Transcripts contain discoveries, dead ends, and stale guesses. Distill the packet instead.The third is insisting on perfect understanding before any progress. That encourages analysis paralysis. You only need enough evidence for the next smallest safe step. A one-line fix may need a small packet. A billing migration may need a deeper trace, production review, and more than one owner. Match the packet to the blast radius.The goal is not perfect certainty. It is a supported decision about the next safe step.Measure whether the practice is paying offDo not measure the number of packets or agent summaries produced. Measure whether they make changes easier to review and safer to finish. Start with a lightweight sample of work in unfamiliar areas. Track how often a packet exposes a missing requirement before editing, how often a listed uncertainty becomes a real issue, how often an agent stays inside its approved file boundary, and how long review takes after a packet exists.Also keep a small set of “known surprising” behaviors. These are cases where history, runtime behavior, or an external contract matters more than a local reading of the code. Run the read-only prompt against them when you change models, agent tools, instructions, or repository indexing. That turns codebase comprehension into something you can test rather than a feeling you rediscover during an incident.The practical takeawayAI coding agents are excellent at accelerating investigation. The risk begins when an investigation is mistaken for proof. A short evidence packet gives an agent a better job: map one behavior, cite the source, expose what it cannot know, and earn permission for a narrow change.That habit lets teams move quickly without pretending their legacy code is self-explanatory. Before the next refactor, migration, or “quick cleanup,” make the agent read first, prove what it saw, and leave a map that survives the session.Further readingOpenAI to acquire Pierre Computer Company for the announcement that Codex tools will expand through the planned acquisition.Scaling Git at OpenAI for an engineering view of how agent-scale development changes software-delivery workload.How to Understand a Legacy Codebase Using AI Before Changing It for a broad code-archeology walkthrough.SWE Atlas for a view of evaluating agents on understanding and validating behavior in real repositories.FAQ: AI Codebase ArchaeologyWhat is AI codebase archaeology?AI codebase archaeology is the use of an AI assistant to recover a defensible understanding of an unfamiliar system before changing it. It combines source reading with call paths, Git history, tests, runtime probes, and explicit unknowns. The aim is not a polished summary. It is evidence for a safe next step.Can an AI coding agent safely edit a legacy codebase?Yes, when its authority matches the evidence available. Start with read-only exploration, give it a narrow task, require a reviewed evidence packet, and allow changes only in a scoped branch or worktree. Require human approval for high-impact behavior and stop when new evidence contradicts the packet.What should be in a codebase evidence packet?Include the change question, current revision, concrete execution path, file and symbol citations, relevant history, behavior probes or characterization tests, assumptions, open questions, and a narrow proposal for what may be edited. Each claim should be labeled confirmed, likely, or unknown.Why are characterization tests useful before an AI refactor?They capture the behavior the system has today, including behavior no one would design from scratch. That gives the team a baseline to inspect when an AI-assisted change alters an output, side effect, or edge case. A characterization test does not say the old behavior is correct. It proves that it exists.Does Git history make an AI agent reliable?No. Git history is one evidence source. It can explain why a guard or coupling exists, but commit messages may be incomplete and patterns may be accidental. Use history to generate checks, then combine it with current source, tests, runtime observations, and human knowledge.How large should the first AI codebase archaeology task be?Start with one behavior that has a clear input and observable outcome, such as a failed webhook retry or a user-permission check. Avoid “map the whole monorepo.” A small investigation makes it easier to assess whether your agent cites evidence honestly before you give it a bigger change.AI Codebase Archaeology: The Evidence Packet to Build Before Your Agent Touches Legacy Code was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.