SyntaxPilot
Courses/Vibe Coding/Lesson 31
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Vibe Coding · Lesson 31 of 40

Working with an existing codebase

reading a project's structureREADMEpackage.json/requirements.txtasking the agent to map the codemaking a small change safelymatching the project's style

Vibe Coding: build real apps with AI · Episode 31. Every agent run below is real: Claude Code 2.1.322 (model claude-opus-5-5) in print mode (claude -p --permission-mode acceptEdits), on 12 November 2026, in /home/asha/projects/canteen. The agent could write files but needed approval to run commands, and nobody approved, so it ran nothing. We ran npm test, the server and every attack ourselves, on our own laptop (localhost) only. Never test attacks on apps that aren't yours.

What was written by hand: the canteen app (commit 483346f, author "Kabir") was written for this video to play an existing project someone else wrote. It is not the AI's code. Kabir, Asha, Ravi and Neha are fictional; the PINs 7391 and 482913 are demo values.

Tools: Node.js v22, Express 5.3.0, better-sqlite3 13.1.1, Node's built-in test runner (node --test), the sqlite3 command-line tool, curl, jq.

The problem: cooking in someone else's kitchen

Asha has joined the school coding club. Kabir (Class 12, who has left school) built a canteen pre-order app: students order samosas before the break bell. Canteen aunty has a request: mark items sold out from her phone.

A new kitchen A new codebase
Walk in and start cooking: where's the gas? the salt? "Just run it": fails, or worse, half works
The note on the fridge: how things work here README: setup, layout, rules
Cook their way: same pots, same shelves Match the style: same patterns, same tests

The obvious way: just run it (real)

$ node server.js
Error: Cannot find module '/home/asha/projects/canteen/server.js'
    at Function._resolveFilename (node:internal/modules/cjs/loader:1430:15)

$ npm start
Canteen on http://localhost:3000
$ curl -s localhost:3000/api/menu
{"error":"Something went wrong."}

$ sqlite3 canteen.db .tables
$                                  # no tables at all
  • There is no server.js in this project.
  • npm start starts, but the menu fails. The real error is hidden, because the app hides internal errors from users (a good habit from episode 28).
  • Starting the app created an empty database. A setup step was missing.

Why: every project has its own way to start, and its own steps before that. Half working is worse than failing.

README first

A README is the text file at the top of a project that tells people what it is and how to use it. On GitHub it's shown on the project's front page. Kabir's:

# Canteen pre-order

Order samosas and chai before the break bell, pick them up without the queue.
Built by Kabir (Class 12, 2025-26) for the coding club. Please keep it tidy for the next person.

## Setup

npm install
npm run db:reset     # creates canteen.db with the menu
npm run dev          # http://localhost:4000
npm test

## How the code is organised

- `src/index.js` starts the server. `src/app.js` builds the Express app.
- `src/routes/` one file per area (`menu.js`, `orders.js`). Routes never touch the database directly.
- `src/db/` every SQL query lives here, one file per table.
- `src/lib/money.js` **all money is stored and calculated in paise** (whole numbers): ₹25 = `2500`.
  Only `formatRupees()` turns paise into text like `₹25.00`. Never use decimals for money.
- `src/lib/errors.js` throw `httpError(status, message)`; `app.js` turns it into JSON.
- Tests: `test/*.test.js`, using Node's built-in test runner. Every new rule gets a test.

## Rules the canteen gave us

- One order can have at most 5 items in total (aunty can't pack more before the bell).
- Orders close at 10:45 (the break is 10:50).

Three kinds of information: setup (the missing db:reset step), layout (where things go), and rules you must not break.

package.json: the project's ID card

{
  "name": "canteen",
  "version": "0.3.0",
  "description": "Pre-order snacks from the school canteen before the break bell.",
  "type": "module",
  "main": "src/index.js",
  "scripts": {
    "db:reset": "node scripts/reset-db.js",
    "dev": "PORT=4000 node --watch src/index.js",
    "start": "node src/index.js",
    "test": "node --test"
  },
  "engines": { "node": ">=22" },
  "dependencies": {
    "better-sqlite3": "^13.1.1",
    "express": "^5.3.0"
  }
}
  • main: which file starts the app (src/index.js, not server.js).
  • scripts: named commands. npm run dev runs PORT=4000 node --watch src/index.js (restarts when files change); npm test runs node --test.
  • "type": "module": this project uses import / export, not require.
  • engines: it needs Node 22 or newer.
  • dependencies: the packages it needs, with version ranges (^5.3.0 = 5.3.0 or a later 5.x). npm install downloads them.

The same idea in Python projects (an example)

# requirements.txt  (Python: one package per line, often with a version)
flask==3.1.2
requests>=2.32

$ pip install -r requirements.txt

# pyproject.toml  (newer Python projects: name, version, dependencies)
[project]
name = "flaskr"
dependencies = ["flask"]

Whatever the language, find the dependency file first: it tells you what the project needs.

Do what the README says (real)

$ npm run db:reset
Created canteen.db with 6 menu items
$ npm run dev
$ curl -s localhost:4000/api/menu | jq -c '.[] | {name, price}'
{"name":"Samosa","price":"₹15.00"}
{"name":"Vada pav","price":"₹20.00"}
{"name":"Masala chai","price":"₹10.00"}
{"name":"Veg sandwich","price":"₹35.00"}
{"name":"Poha","price":"₹25.00"}
{"name":"Nimbu pani","price":"₹15.00"}
$ npm test
# tests 6
# pass 6
# fail 0

Green tests before you change anything. If something turns red later, you know you broke it.

Prompt 1 (real): ask the agent to map the code

claude -p "I just joined this project, someone else wrote it. Don't change anything yet. Explain how it's organised, how to run it, and the rules I have to follow when I change it." --permission-mode acceptEdits

It read every file and changed nothing. Its map (real, shortened):

src/index.js        starts the server (PORT env var, default 3000)
src/app.js          buildApp({ now }): sets up routes and the error handler
src/routes/         HTTP layer, one file per area
  menu.js           GET  /api/menu         → items with a formatted "price"
  orders.js         POST /api/orders       → validates and creates an order
                    GET  /api/orders/:id   → order with its items
src/db/             all SQL lives here, one file per table
src/lib/money.js    formatRupees(), sumPaise()
src/lib/errors.js   httpError(status, msg)
db/schema.sql       tables: menu_items, orders, order_items
scripts/reset-db.js deletes and rebuilds the database from schema + seed
test/               Node's built-in test runner; helpers.js gives each test file its own temp DB and server

It listed the rules ("Money is always whole paise", "Routes never touch the database", "throw httpError(status, message)", "Every new rule gets a test"), noted that buildApp takes a now function "so tests can fake the clock", and under Things I noticed:

"qty is never checked. Negative, zero or fractional quantities get through ... a negative qty can make the total negative. This is the most serious one."

A bug found by reading (real)

The order route in Kabir's code:

orderRoutes.post("/", (req, res) => {
  const { student, items } = req.body ?? {};
  if (!student || !Array.isArray(items) || items.length === 0) {
    throw httpError(400, "Send a student name and at least one item.");
  }
  const count = items.reduce((n, item) => n + item.qty, 0);
  if (count > MAX_ITEMS_PER_ORDER) {
    throw httpError(400, `At most ${MAX_ITEMS_PER_ORDER} items per order.`);
  }
  // ... closing time, items exist and in stock ...
  const totalPaise = sumPaise(lines);
  // ...
});

Using the project's own test helper (fake clock at 10:15):

await app.post("/api/orders", { student: "Ravi 10B",
  items: [{ id: 1, qty: 1 }, { id: 3, qty: -4 }] });

201 {"id":1,"total_paise":-2500,"total":"₹-25.00"}

One samosa and minus four chai: the canteen owes Ravi ₹25. Not today's task, so: write it down, tell the team, fix it separately with a test first (see the mini project).

A small change, safely

  1. Tests green first (6/6), and a commit.
  2. One small request: just the sold-out button.
  3. The agent should follow the README's rules.
  4. Read the diff: does it look like Kabir wrote it?
  5. Run the tests, then try to break it yourself.

Prompt 2 (real): the sold-out button

claude -p "Canteen aunty wants to mark items as sold out (and back in stock) from her phone during the break. Add that." --permission-mode acceptEdits
Edit   src/db/menu.js      + setInStock(id, inStock)     (SQL in src/db)
Edit   src/routes/menu.js  + PATCH /api/menu/:id, httpError(401 ...)
Write  public/staff.html   a phone page with big buttons
Write  test/stock.test.js  sold out, back in stock, wrong PIN ...
Edit   README.md           STAFF_PIN=1234 npm run dev
Reply: "The PIN is there so students can't mark things sold out
   themselves."
$ npm test
# tests 12   # pass 12   # fail 0

The new route (real):

// Only canteen staff may change stock. They send the staff PIN in the X-Staff-Pin header.
function requireStaff(req) {
  const pin = req.app.get("staffPin");
  if (!pin) throw httpError(503, "Staff PIN is not set up. Start the server with STAFF_PIN.");
  const given = Buffer.from(String(req.get("X-Staff-Pin") ?? ""));
  const expected = Buffer.from(pin);
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
    throw httpError(401, "Wrong staff PIN.");
  }
}

// PATCH /api/menu/3  { "in_stock": false }   (header X-Staff-Pin: ...)
menuRoutes.patch("/:id", (req, res) => {
  requireStaff(req);
  const { in_stock } = req.body ?? {};
  if (typeof in_stock !== "boolean") throw httpError(400, "Send in_stock as true or false.");
  const item = setInStock(Number(req.params.id), in_stock);
  if (!item) throw httpError(404, "No such menu item.");
  res.json(withPrice(item));
});

The real AI mistake: a 4-digit PIN guessed in 2 seconds

A 4-digit PIN has 10,000 possible values. A person can't try them all; a script can. Our script, on our own laptop:

// A student's script: try every 4-digit PIN against our own server on this laptop.
const t0 = Date.now();
for (let start = 0; start < 10000; start += 50) {
  const tries = [];
  for (let n = start; n < start + 50; n++) {
    const pin = String(n).padStart(4, "0");
    tries.push(fetch("http://localhost:4000/api/menu/1", {
      method: "PATCH", headers: { "Content-Type": "application/json", "X-Staff-Pin": pin },
      body: JSON.stringify({ in_stock: false }),
    }).then((r) => (r.status === 200 ? pin : null)));
  }
  const found = (await Promise.all(tries)).find(Boolean);
  if (found) { console.log(`PIN found: ${found} after ${start + 50} tries max, ${((Date.now() - t0) / 1000).toFixed(1)} s`); break; }
}
$ node guess.mjs
PIN found: 7391 after 7400 tries max, 2.0 s
$ curl -s localhost:4000/api/menu | jq -c '.[0]'
{"id":1,"name":"Samosa","price_paise":1500,"in_stock":0,"price":"₹15.00"}

The AI said the PIN stops students, but nothing limited the guesses: every wrong one just got 401 and the script tried the next. Trying every possible value like this is a brute-force attack.

Prompt 3 (real): the evidence, and the school WiFi

claude -p "I tested the staff PIN on my laptop with STAFF_PIN=7391. A small script tried every 4-digit PIN with PATCH /api/menu/1 and found 7391 in 2.0 seconds (7,400 tries, each wrong one just got 401), then marked Samosa sold out. A student could do this from the school WiFi during the break, and the whole school is on that one WiFi. Fix it. Follow the project's rules in the README, keep the change small, and add tests." --permission-mode acceptEdits
Write  src/lib/lockout.js           5 wrong PINs -> every PIN refused 15 min
Edit   src/routes/menu.js           STAFF_PIN shorter than 6 is refused
Write  test/staff-lockout.test.js   5 tests
Reply: "Why not limit each IP address: the whole school is on one
   WiFi ... A student can lock aunty out. By sending 5 wrong PINs,
   a student can block stock changes for 15 minutes at a time ...
   They still can't change stock."

The new file (real):

// Stops people guessing the staff PIN.
// The whole school is on one WiFi, so every student shares one IP address. Counting
// per IP would not help, so we count wrong PINs for the whole server instead.
// After `maxFailures` wrong PINs in a row, every PIN (even the right one) is refused
// until `lockMs` has passed. The right PIN resets the count.
export function createLockout({ now, maxFailures = 5, lockMs = 15 * 60 * 1000 }) {
  let failures = 0;
  let lockedUntil = 0;
  return {
    // Milliseconds left on the lock, or 0 if not locked.
    remainingMs() {
      return Math.max(0, lockedUntil - now().getTime());
    },
    failed() {
      failures += 1;
      if (failures >= maxFailures) {
        failures = 0;
        lockedUntil = now().getTime() + lockMs;
      }
    },
    succeeded() {
      failures = 0;
    },
  };
}

Because the prompt mentioned the shared WiFi (the trap from episode 28), it counted wrong PINs for the whole server instead of per IP address, and wrote down the downside: a student can lock aunty out for 15 minutes, but can't change stock. A trade-off, documented where the team can see it.

Our retest (real)

$ npm test
# tests 16   # pass 16   # fail 0
$ STAFF_PIN=7391 PORT=4000 node src/index.js       # the old 4-digit PIN
$ curl -s -X PATCH ... -H "X-Staff-Pin: 7391" localhost:4000/api/menu/1
{"error":"Staff PIN is too short. Start the server with a STAFF_PIN
 of at least 6 digits."}
$ STAFF_PIN=482913 PORT=4000 node src/index.js
$ node guess.mjs                           # the same attack
(no PIN found)
$ curl ... -H "X-Staff-Pin: 482913"        # even the right PIN, for now
{"error":"Too many wrong PINs. Try again in 15 minutes."} 429

Matching the project's style

// src/db/menu.js: the new query sits with the other SQL
export function setInStock(id, inStock) {
  db.prepare("UPDATE menu_items SET in_stock = ? WHERE id = ?").run(inStock ? 1 : 0, id);
  return db.prepare("SELECT id, name, price_paise, in_stock FROM menu_items WHERE id = ?").get(id) ?? null;
}

// src/routes/menu.js: errors the project's way
if (typeof in_stock !== "boolean") throw httpError(400, "Send in_stock as true or false.");

// test/stock.test.js: the same helper and fake clock as Kabir's tests
const app = await startApp(at("10:15"), { staffPin: "482913" });

Same folders, same patterns, same kind of tests. A project with three styles is harder for everyone, including the next AI that reads it.

Checklist: joining someone else's project

  1. Read the README, then package.json / requirements.txt / pyproject.toml.
  2. Run it the README's way; run the tests: all green?
  3. Ask the agent for a map: "don't change anything yet".
  4. Write down bugs you find; fix them separately.
  5. One small change, with a commit before and after.
  6. Read the diff: their folders, patterns, tests.
  7. Attack it yourself before you hand it over.

Common mistakes (real)

Mistake What you see Why Fix
Guessing the start command Error: Cannot find module '.../server.js' Every project starts its own way README + package.json
Skipping a setup step {"error":"Something went wrong."} No tables in the database npm run db:reset
No check on qty (Kabir's) 201 · "total":"₹-25.00" Negative quantity allowed A failing test first, then a fix
4-digit PIN, no limit (the AI's) PIN found: 7391 ... 2.0 s Brute force Lockout + 6+ digits
Lockout per IP (the whole school = one IP) Shared WiFi Count for the whole server, or per account

Mini project: fix the negative quantity, test first

  1. Add a test to test/orders.test.js:
test("quantities must be whole numbers from 1", async () => {
  const res = await app.post("/api/orders", { student: "Ravi 10B", items: [{ id: 1, qty: 1 }, { id: 3, qty: -4 }] });
  assert.equal(res.status, 400);
});
  1. Run npm test: it should fail (today the answer is 201).
  2. Fix the route (or ask your agent, with the rule "follow the README; use httpError; keep everything else the same"), e.g. reject any item where !Number.isInteger(item.qty) || item.qty < 1.
  3. Run npm test again: all green. Commit.

Practice questions

  1. A project has no README. How do you find how to run it?
Answer

Read package.json scripts (or requirements.txt / pyproject.toml, a Makefile, a Dockerfile), look for the entry file, and ask the agent for a read-only map. Then write the README for the next person.

  1. What does "type": "module" in package.json tell you?
Answer

The project uses import / export (ES modules), so require won't work in its .js files.

  1. Why run the tests before changing anything?
Answer

To get a green baseline: if a test fails later, your change caused it, not something that was already broken.

  1. Why was a per-IP-address lockout wrong for this school?
Answer

Everyone on the school WiFi shares one public IP address, so the server can't tell students apart by IP.

  1. The agent found a bug while you were adding a feature. Should it fix it in the same change?
Answer

No. Note it and fix it separately, with a test, so each change is small and easy to check and undo.

Quiz

You join a project. What do you do first? A) Ask the AI to add your feature right away · B) Read the README, run it its way, run the tests · C) Rewrite it in your favourite style · D) Delete files that look unused

Answer

B: learn how the project runs and get a green baseline first. A skips the rules, C breaks the team's style, D can delete things other programs use.

Interview questions

  1. How do you get productive in an unfamiliar codebase? README and dependency files, run it, run the tests, map the structure (entry point, routes, data layer), then a small change.
  2. How can an AI agent help with onboarding? A read-only map of the code, the conventions, and how to run it; it can spot bugs by reading. Verify its claims by running things.
  3. What is a brute-force attack and how do you defend against it? Trying every possible value; defend with attempt limits/lockouts, longer secrets, and per-account limits.
  4. Why match an existing project's style? Consistency makes code easier to find, review and change for everyone.
  5. What is a dependency file? A list of the packages a project needs and their versions: package.json, requirements.txt, pyproject.toml.

Glossary

Term Meaning (with an example from this episode)
Codebase All the code and files of a project (the canteen app).
Existing codebase A project someone else already wrote, which you now change.
Project structure How files and folders are organised (src/routes/, src/db/, test/).
README The file at the top of a project explaining what it is and how to use it.
Setup step Something to do before the app works (npm run db:reset).
Convention / project rule An agreed way of doing things (money in paise; SQL only in src/db/).
package.json A Node project's ID card: name, scripts, dependencies, settings.
Script (npm) A named command in package.json (npm run dev).
Dependency A package the project needs (express, better-sqlite3).
Version range Which versions are allowed (^5.3.0 = 5.3.0 up to, not including, 6.0.0).
"type": "module" The project uses import/export (ES modules).
engines Which Node versions the project needs (>=22).
Entry file / main The file that starts the app (src/index.js).
requirements.txt Python's list of packages to install, one per line.
pyproject.toml Newer Python project file with name, version and dependencies.
pip Python's package installer (pip install -r requirements.txt).
Database / table Stored data organised in tables (menu_items, orders).
Seed data Starting data put in a new database (the 6 menu items).
Test / test runner Code that checks code; node --test runs them.
Green / red tests All passing / some failing.
Fake clock A test trick: pass the app a pretend time (at("10:15")).
Mapping the code Asking for an overview of a project's structure, run steps and rules, without changes.
Paise 1/100 of a rupee; storing money as whole paise avoids decimal errors (₹25 = 2500).
PATCH An HTTP method to change part of something (PATCH /api/menu/1).
Header Extra information sent with a request (X-Staff-Pin: 482913).
PIN A short secret number.
Status codes 201 / 401 / 409 / 429 / 503 Created / not authorised / conflict / too many requests / service not ready.
Brute-force attack Trying every possible value until one works (all 10,000 4-digit PINs).
Lockout Refusing attempts for a while after too many wrong ones (5 wrong → 15 minutes).
IP address The internet address a request comes from; a whole school WiFi can share one.
Trade-off A choice with a known downside (the lockout can also block aunty).
Diff The exact lines a change added and removed.
Matching the style Writing new code with the project's folders, patterns and tests.

Summary

  • "Just run it" failed (Cannot find module) and then half worked (Something went wrong., an empty database).
  • Read the README and package.json (or requirements.txt / pyproject.toml), run it their way, and start from green tests.
  • A read-only map from the agent saved time and found a real bug: a negative quantity gives a total of ₹-25.00.
  • The agent followed every project rule for the sold-out button, and still shipped a 4-digit PIN our script guessed in 2.0 seconds. With evidence, it added a server-wide lockout and a 6-digit minimum, and stated the downside.
  • Match the project's style, and attack it yourself before you hand it over.

Next episode: Rules files and project memory.