Reading a Codebase You Didn't Write by kirupa (https://www.kirupa.com/me/index.htm) | filed under AI Fundamentals (https://www.kirupa.com/ai_fundamentals/index.htm) TL;DR: Don't read a codebase you didn't write from top to bottom. Sketch a rough map of its folders, entry points, and tables, then follow one real request all the way through. Let an agent draft the map, but check each claim. Before changing anything, write tests that record what the code does today, called characterization tests. - A one-page map of Pinwheel's folders, its entry points (customers, staff, and scheduled jobs), and its tables beat reading 412 PHP files in folder order. - Following one next-day order led from order.php to a 4:05pm cron job that prints the kitchen's prep sheet, and it skipped most of the codebase. - An agent's summary is fast and mostly right, but it trusted a 2014 README and missed a cron job scheduled outside the repository, so check every claim. - Before Biscuit fed Pinwheel's import new rows, a test that recorded today's behavior showed that 2 pies in one row become 2 item rows. When Crumb & Co. bought Rolling Pin Bakeries, its six shops came with Pinwheel, an ordering system that has run on PHP and MySQL since 2011. Wren has already been burned by Pinwheel once, when a harmless-looking cleanup (https://www.kirupa.com/ai_fundamentals/chestertons_fence.htm) left nine customers without bread. Now Biscuit is about to start sending Pinwheel holiday pie pre-orders, and Wren would rather not learn the rest of it one surprise at a time. A lot of the code we work on was written by somebody else, and more and more often, that somebody is an agent. In this article, we'll look at how to find our way around code like this without reading all of it, getting lost, or blindly trusting an agent's summary. Onwards! Opening the Folder Here is what Wren sees in the Pinwheel folder: [Image: Pinwheel's folder as Wren first sees it. The top level holds admin, backup_2017, cron, docs, includes, old, old2, and public, plus a loose test.php. Inside includes, functions.php is 3,812 lines long. Inside public sit four order pages: order.php, order2.php, order_new.php, and order_new_FINAL.php. A handwritten note points at them: four order pages?!] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_folder.png) (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_folder.png) There are four order pages, and only one of them can be the real one. There is a 3,812-line functions.php, plus folders called old and old2. All 412 PHP files came with zero tests. Pinwheel has taken orders every day since 2011, so it clearly works. It just doesn't explain itself to us. The obvious way to learn a codebase (all of the code for one project) is to start at the top of our folder and read our way down: [Image: A gag. Wren at a laptop next to five empty coffee cups, with a progress bar that reads file 37 of 412 and is barely filled. The file on screen is admin/report_old_v2.php. A handwritten note points at it: day 3, still in admin!] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_alphabetical.png) Reading top to bottom treats all of our files as equally important, and they are not. Some run on every order, and some haven't run since 2017. By file 37, we have also forgotten most of files 1 through 36. That hurts, because figuring out code is already a huge part of our job. A 2018 field study of professional developers (https://doi.org/10.1109/TSE.2017.2734091) found that they spent about 58% of their time on it. Map First What we want instead is a rough map. In 1931, Harry Beck, a draughtsman for the London Underground, drew a new map of the Tube in his spare time, and as the London Transport Museum (https://www.ltmuseum.co.uk/collections/stories/design/transforming-tube-map-harry-becks-iconic-design) tells it, he based his map on the order of the stations and where the lines cross, instead of on geography: [Image: Two drawings of the same three train lines. On the left, drawn by geography, the lines wiggle along a faint street grid and cross at odd angles. On the right, drawn by connection, the same lines run only horizontally, vertically, or at 45 degrees, the stations are evenly spaced, and the two places where lines meet, A and B, are easy to spot.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_beck.png) On the left, our lines follow the streets. On the right, every line runs flat, upright, or at 45 degrees, with evenly spaced stations. The distances are all wrong, and riders don't mind, because they want to know which train to take and where to change. Beck's first pocket map came out in January 1933, with a first run of 750,000 copies. Our map of Pinwheel is going to work the same way, with only what connects to what. We'll start with the top-level folders: [Image: The first pass at a map of Pinwheel: one box per top-level folder with a one-line note. public holds the pages customers see, admin holds the staff pages, cron holds maintenance scripts with a question mark, and includes holds the shared functions in db.php, functions.php, and mail.php. Faded along the bottom are docs, old, old2, and backup_2017: old copies and a README from 2014.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_map_folders.png) Our AI coding agent wrote these one-line notes in about a minute, and the note for cron came back with a question mark. Next, we ask how work gets into Pinwheel. Something has to start every piece of code, like a customer loading a page or a scheduled script. These starting points are called entry points, and they are the doors into our map: [Image: The same Pinwheel map with its entry points added on the left. Customers come in through public, staff come in through admin, and the clock (the server's scheduled jobs) comes in through cron, which is still marked maintenance scripts with a question mark.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_map_doors.png) Our customers come in through public, and staff, like Yara's team, come in through admin. The third door is a clock. Linux servers run scheduled jobs with a tool called cron, and cron reads its list of jobs from a file called the crontab, which lives on the server instead of in our repository. Our last pass will add the tables, with arrows for which code reads or writes them: [Image: The finished first map of Pinwheel. Customers, staff, and the clock come in through public, admin, and cron. public and admin call the shared functions in includes, and includes reads and writes five MySQL tables: orders, order_items, products, customers, and shops. No arrow leaves cron yet, because nobody has opened it.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_map_tables.png) (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_map_tables.png) Notice that no arrow leaves cron. We haven't looked inside it yet, so that part of our map is still a guess. Follow One Request To learn how Pinwheel actually behaves, we are going to follow one real request all the way through. For us, that request is a next-day order, because Biscuit's pre-orders will land in the same tables. At 3:40pm on a Tuesday, a customer orders a sourdough loaf for tomorrow: [Image: Rolling Pin's order page on a phone at 3:40. The cart holds 1 sourdough loaf, the pickup day is set to Tomorrow, Wed Oct 14, and a big Place order button sits at the bottom.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_order_page.png) When our customer taps Place order, the form goes to public/order.php, and the form's action attribute is what tells us which of the four order pages is the live one. From there, we follow the code one call at a time, jumping into each function with our editor's Go to Definition (F12 in VS Code, with a PHP extension). Drawn as one line, our order looks as follows: [Image: The order drawn as one line with five stops. It starts at the customer's phone at 3:40pm. Stop 1, public/order.php, shows the form and checks the hour: 15 is less than 16. Stop 2, includes/functions.php, runs save_order(). Stop 3 is the orders and order_items tables, with one row for the order and rows for its items. Stop 4, includes/mail.php, runs send_confirmation(). Stop 5, public/thanks.php, shows the thank-you page.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_line_request.png) At order.php, the code only offers tomorrow while the hour is less than 16. It's 15, so we're fine. Then save_order() writes our rows, send_confirmation() sends an email, and our customer sees a thank-you page. Is that the end of the line? For our customer, yes. For the bakery, nope. Somebody still has to bake our customer's loaf, so we search every file for code that reads our orders table with ripgrep (rg), a fast search tool: [Image: A terminal in the pinwheel folder. The command rg -l "FROM orders" lists three files that read the orders table: admin/orders.php, cron/nightly_report.php, and cron/prep_sheet.php. A handwritten note points at cron/prep_sheet.php: who's this?] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_search.png) The staff page is already on our map, and the other two files live in cron, so we'll check the server's schedule: [Image: A terminal on Pinwheel's server. crontab -l lists three scheduled jobs: 0 2 * * * runs import_wholesale.php at 2am, 30 23 * * * runs nightly_report.php at 11:30pm, and 5 16 * * * runs prep_sheet.php at 4:05pm. A handwritten note points at the prep sheet's schedule: 4:05pm, every day!] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_crontab.png) The five fields are the minute, the hour, the day of the month, the month, and the day of the week, so 5 16 * * * means 4:05pm, every day. That is when prep_sheet.php prints tomorrow's orders, ours included, for our evening crew, who shape the sourdough for an overnight cold proof. This is the job that left nine customers without bread when the 4pm cutoff went away, and it's where our customer's loaf actually begins. Here is our order's whole line, drawn over the tangle we started with: [Image: The order's complete line drawn like a subway line over a faded tangle of Pinwheel's file names. At 3:40pm it runs from order.php to save_order(), the orders table, and send_confirmation(). Then, at 4:05pm, it reaches prep_sheet.php and ends at the kitchen printer, where the evening crew starts the next day's sourdough.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_subway.png) (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_subway.png) Our line ends 25 minutes after our customer's request finished, at a stop that no browser ever touches, and it skips most of Pinwheel along the way. If this were Biscuit, a trace (a recorded timeline of every step one request takes) would draw this line for us, as Tracing and Prompt Logs (https://www.kirupa.com/ai_fundamentals/tracing_and_prompt_logs.htm) shows. Pinwheel records nothing like that, so we drew ours by hand. Besides search and Go to Definition, a few other tools helped: - git log and git blame, to see when a confusing line changed and why. - A copy of Pinwheel on our own machine, where a temporary error_log() line proves a stop really is on the path. - SHOW CREATE TABLE orders, which lists columns the code never mentions. Let Agents Map, Then Check Their Work Before drawing anything, Wren also asked our agent to explain how Pinwheel handles an order. About a minute later, it answered with this: [Image: Wren asks a coding agent in the terminal: How does Pinwheel handle an order? The agent answers with five confident claims: 1, customers order on public/order.php. 2, save_order() writes to orders and order_items. 3, confirmation emails go out through mail.php. 4, each night, email_kitchen() emails tomorrow's orders. 5, the cron folder holds old maintenance scripts.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_agent_summary.png) Our agent found order.php and save_order() in seconds, which saved us time. It also states all five claims with the same confidence. We only know which ones hold up because we traced the request ourselves: [Image: The agent's five claims, each checked against the code. Claim 1 holds: we opened public/order.php. Claim 2 holds: Go to Definition lands in includes/functions.php. Claim 3 holds: we placed a test order on our own machine. Claim 4 is wrong: rg shows nothing calls email_kitchen(), and the claim came from the 2014 README. Claim 5 is wrong: the crontab shows prep_sheet.php prints at 4:05pm.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_agent_checked.png) (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_agent_checked.png) Claim 4 came from a README written in 2014. The email_kitchen() function still exists, but nothing calls it anymore. Claim 5 came from nothing more than a folder name, because our agent never opened prep_sheet.php, and the crontab that schedules it isn't even in the repository our agent was reading. Why would an agent miss the most important job in the building? As we saw in Context Engineering (https://www.kirupa.com/ai_fundamentals/context_engineering.htm), a model only works from what lands in its context window, and an agent fills that window by choosing which files to open: [Image: On the left, the repository the agent read: order.php, functions.php, mail.php, and the 2014 README, which it read, and prep_sheet.php, drawn dashed because it never opened it. On the right, outside the repository and out of the agent's sight: the crontab on the server, the kitchen printer, and Yara and Gus, who know why things are the way they are.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_outside.png) (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_outside.png) When a fact is missing, a model fills the gap with something that sounds right (Why AI Makes Things Up (https://www.kirupa.com/ai_fundamentals/why_ai_makes_things_up.htm) covers why), and a folder named cron sure sounds like maintenance scripts. This means that every line of an agent's summary is a guess until we check it. We'll still let agents map, because they are fast and usually right about the easy parts. We just use them differently: - Ask for a file and line number behind every claim, so we can check each one in seconds. - Give it one request to trace instead of a whole codebase to summarize. - Check each claim the way we checked ours. Pin It Down Before Changing It Now for the change that sent Wren into Pinwheel. Biscuit will take holiday pie pre-orders for all six Rolling Pin shops, and Pinwheel has no API (a way for other programs to send it data). Yara's team agreed that we will add Biscuit's pre-orders to the CSV file that the 2am import already reads, so Pinwheel's code doesn't change before the November 1 change freeze. Biscuit is about to feed our import rows it has never seen, and nobody wrote down what the import does with them. So before Biscuit sends a single pre-order, we write a test that records what the import does today, starting with a guess: public function test_two_pies_in_one_row() { $csv = csv_file("shop_id,product,qty,pickup_date\n3,Apple pie,2,2026-11-25"); import_rows($csv); $items = db_rows("SELECT * FROM order_items WHERE product = 'Apple pie'"); $this->assertSame(1, count($items)); } Our guess is that a row for 2 apple pies becomes one item with a quantity of 2. Here is what PHPUnit, the usual test runner for PHP, says when we run our test: [Image: A terminal running vendor/bin/phpunit tests/ImportTest.php. One test, test_two_pies_in_one_row, fails with: Failed asserting that 2 is identical to 1. The summary line reads Tests: 1, Assertions: 1, Failures: 1. A handwritten note points at the failure: two rows!] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_phpunit.png) The import wrote two rows, one per pie. Is that a bug? We don't know, and that's a question for Yara. It is how Pinwheel behaves today, though, so our test now expects 2, and anything we build on the import will count pies the same way. A test that records what code actually does, instead of what we think it should do, is called a characterization test. Michael Feathers introduced the term in his 2004 book, Working Effectively with Legacy Code (https://www.informit.com/store/working-effectively-with-legacy-code-9780131177055), and in 2016 he described its purpose like this: The purpose of characterization testing is to document your system's actual behavior, not check for the behavior you wish your system had. Michael Feathers, Characterization Testing (https://michaelfeathers.silvrback.com/characterization-testing) His recipe is the one we just followed: write a guess, run it, and let the failure tell us what the code really does. Tests as a Safety Net for Agent-Written Code (https://www.kirupa.com/ai_fundamentals/tests_for_agent_code.htm) goes deeper on tests like these. You Won't Understand All of It After a week, here is our map with the parts we actually understand filled in: [Image: The same Pinwheel map a week later. The parts Wren has traced are filled in blue: customers, public, includes, the orders and order_items tables, and cron, which now reads prep sheet, imports and has a new arrow into orders. Everything else, including admin, staff, products, customers, shops, and the old folders, is faded.] (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_known.png) (https://www.kirupa.com/ai_fundamentals/images/reading_unfamiliar_code_known.png) Everything else is still faded, and some of what Pinwheel does isn't in the code at all. It lives with Yara and with Gus, who set the 4pm cutoff. Untangling Tribal Knowledge (https://www.kirupa.com/ai_fundamentals/tribal_knowledge.htm) is about getting it written down. We will never understand all of a codebase this size, and we don't need to. What we need is the parts our change touches, understood well enough that we would notice breaking one of them. Try It This Week Pick a codebase you didn't write (or one you wrote so long ago it feels that way), and try this: 1. Spend 30 minutes mapping the top-level folders, entry points, and database tables, with arrows for what talks to what. 2. Trace one real request end to end, writing down the file and function at each stop, and draw it as one line over your map. 3. Ask an agent to explain the same request, with a file and line for every claim, and check each one against your line. 4. Before your next change in that code, write one test that records what it does today, odd parts included. Frequently Asked Questions How Do You Understand a Codebase You Didn’t Write? Don’t read it top to bottom, because that treats every file as equally important. Sketch a rough map of the top-level folders, the entry points where work starts, and the database tables, with arrows for what talks to what. Then follow one real request all the way through, writing down the file and function at each stop. Can You Trust an AI Agent’s Summary of a Codebase? Treat it as a list of guesses until you check each claim. An agent only knows the files it opened, so it can trust an outdated README or miss a scheduled job that lives outside the repository. Ask for a file and line number behind every claim, and check each one by opening the file, searching, or running the code. What Is a Characterization Test? It’s a test that records what code actually does today, instead of what we think it should do. Michael Feathers introduced the term in his 2004 book, Working Effectively with Legacy Code. You write a test with a guess, run it, let the failure show the real behavior, and then make the test expect that behavior. Do You Need to Understand the Whole Codebase Before Changing It? No. You’ll rarely understand all of a large codebase, and some of what it does lives in people’s heads instead of the code. Aim to understand the parts your change touches, well enough that you’d notice breaking one of them. Conclusion Ok! It is time to wrap things up. Opening a codebase we didn't write feels like staring at a tangle, and reading it top to bottom only makes it bigger. What worked for us was a rough map first, and then one real order followed all the way to the kitchen printer at 4:05pm. An agent sped up the map, our trace showed which of its claims were true, and a characterization test pinned down the import before Biscuit started leaning on it. The honest limitation is that this never really finishes. Pinwheel will keep surprising us...and some answers will only ever come from Yara and Gus. That's alright. Harry Beck's map left out nearly every street in London, and it still got people to the right station. Our map only has to get us safely through the parts we are about to change. Before you go, here are a few things you can do: 1. Test your knowledge by taking the quiz below. 2. Read the next article in the series, Untangling Tribal Knowledge (https://www.kirupa.com/ai_fundamentals/tribal_knowledge.htm), or check out some related content: - Tracing and Prompt Logs (https://www.kirupa.com/ai_fundamentals/tracing_and_prompt_logs.htm). Follow one request step by step when every status code says 200 OK. - How an Agent Like Claude Code Works (https://www.kirupa.com/ai_fundamentals/how_an_agent_works.htm). How a coding agent reads files, runs commands, and checks its own work. - Tests as a Safety Net for Agent-Written Code (https://www.kirupa.com/ai_fundamentals/tests_for_agent_code.htm). Use tests as the safety net and the spec for code an agent writes. 3. Stuck on something, or curious about a detail we skipped? Ask on the forums (https://forum.kirupa.com/), and we’ll help you out. [Mastery Quiz] Test your knowledge! Take the Reading a Codebase You Didn't Write Quiz: https://www.kirupa.com/quizzes/reading_unfamiliar_code.htm Practice with 6 multiple-choice questions and an explanation after every answer. [/Mastery Quiz]