跪拜 Guibai
← Back to the summary

Put a README in Every Folder and Make AI Read It First: A Directory Index That Stops AI from Editing the Wrong Files

Conclusion: Place one README in the project root and in every subdirectory, writing only "what's in this layer, who's responsible, and what shouldn't go here," then require in your prompt engineering that AI reads it before touching anything—this is the highest return-on-investment convention for AI coding. It doesn't change code, introduce a framework, or install a plugin. It only costs the time spent writing docs, and in exchange, AI reads ten fewer irrelevant files and mis-edits one fewer module. Below are the rules, a template, a prompt snippet you can copy directly into your rules, and a README gap checker I've run myself.


Table of Contents

  1. Conclusion First: README Is a Directory Index for AI (Index, Not Doc)
  2. Why AI Loves Editing the Wrong File: The Context Is Missing a "Who Owns What" Map (Why AI Misses)
  3. Three Hard Rules: One Per Layer, Direct-Only Descriptions, Read Before Edit (Three Rules)
  4. What a README Should Contain: A Fixed Template with Five Fields (Template)
  5. How to Write the Prompt: Make "Read First" a Hard Constraint (Prompt Rules)
  6. One Reproducible Measurement: 14 Directories, 9 READMEs, 64.3% (Measurement)
  7. Complete Runnable Code: README Gap Checker (Runnable Checker)
  8. Division of Labor Between README and AGENTS.md, CLAUDE.md (Boundaries)
  9. Symptom → Cause → Fix Reference Table (Symptom → Cause → Fix)
  10. Rollout Order: Root First, Then Three Layers, Finally CI Gating (Rollout Order)

1. Conclusion First: README Is a Directory Index for AI (Index, Not Doc)

In traditional projects, the README is written for "people seeing this repo for the first time": what dependencies to install, how to start, what the project does. That positioning has one consequence: the vast majority of repos have only the root README, and it hasn't been updated in a decade.

AI coding has changed the reader structure of this document. Now, what opens your repo every day isn't just a person—it's also an AI that can only perform three actions: ls, grep, and read. It doesn't have the architecture diagram in your head. All it can see are file paths and search results. If you don't give it an index, it can only guess.

So the positioning of README needs to change by one sentence: from "project manual" to "directory index." The judgment criterion for an index is simple: after reading it, you (or AI) should immediately answer three questions:

If these three answers are covered, the README passes. If not, writing three thousand words is wasted paper.

Here's a real-world analogy: a supermarket without shelf labels forces you to pick up items row by row and check production dates; a labeled supermarket lets you walk to aisle 3 and grab what you need. When AI browses your repo, reading the README is looking at shelf labels; ls plus read is picking things up to check production dates. The former gets there in one go; the latter ends in useless reads nine times out of ten.

2. Why AI Loves Editing the Wrong File: The Context Is Missing a "Who Owns What" Map (Why AI Misses)

AI editing the wrong file is rarely because it's "stupid." In the vast majority of cases, it's due to three structural reasons. In How to Review AI-Generated Code, we covered a six-layer inspection checklist—that governs the "post-AI-write acceptance" stage. This article covers an earlier step: "how to locate before AI touches anything." If localization is wrong, no amount of subsequent review will do anything but polish the wrong spot.

First: same-name files cannot be distinguished. apps/api/src/utils.ts and packages/core/src/utils.ts look identical in search results, differing only by path. When AI gets three hits, which one it picks depends entirely on which one it stops reading at. This isn't an ability problem; it's an information problem—you never told it "there are two utils, one is pure functions, one is date formatting, don't mix them."

Second: cross-layer changes have no sense of cost. When a human edits code, seeing import { X } from '@fleet/db' triggers a subconscious thought: "this is another package's boundary," and the hand pauses. AI doesn't have that pause. When it sees a function that isn't sufficient, its first thought is "I'll add a parameter to it," and its second is "I'll just inline an implementation right in this file." Both operations are just a few lines in the diff, but one breaks encapsulation and the other creates a duplicate implementation.

Third: exploration cost eats up context. AI's default action sequence after receiving a task is: ls the root → guess a directory and go in → ls again → open a file that doesn't look right → close it → open another one. Each probe burns tokens. By the time it finally finds the right file, usable context has already been halved by probing, and the remaining half must be spent on writing code and self-checking—quality starts dropping right there.

These three causes point to the same remedial action: before AI starts probing, hand it the "map" first. The map can't be one big document at the root—after reading a 500-line root README, AI still won't know whether that chat in apps/api/src/routes/chat.ts belongs to whom. The map must be layered: the root gives the global view, each layer gives its own level.

3. Three Hard Rules: One Per Layer, Direct-Only Descriptions, Read Before Edit (Three Rules)

There are only three rules, but people step on pitfalls with each one.

Rule One: One README per layer, no "everything-in-one" documents. One at the root, one in each subdirectory, each serving only its own layer. The reason isn't "it looks nice"; it's maintenance cost: a single all-in-one document must grow linearly with the number of directories, anyone who touches any directory has to edit the same file, and conflicts happen daily. With layering, each file stays under 30 lines, whoever creates the directory writes it, whoever modifies the directory modifies it, and the author is the sole owner.

Rule Two: Write only direct children, not grandchildren. This directory's README only covers "files directly in this folder" and "what each direct subfolder is responsible for." It does not expand into details inside subfolders—those details belong to the subfolder's own README. This rule is the key to the whole structure surviving long-term: once you allow "oh, I'll just write the lower layers too," two places describe the same thing, they will inevitably contradict each other within three months, and AI will read whichever one it lands on—worse than not writing anything.

Rule Three: Read before editing, and require upward traversal. Before AI edits a file, it must read the README of the directory containing the target file, then go up one level and read the parent directory's README for background, with a maximum of two levels up. Reading only the current layer leaves it unaware of its position in the overall system; unlimited upward traversal means reading the root all-in-one again. Two levels is a sufficient boundary: the current layer tells you "what this file does," the parent layer tells you "why this directory exists."

Combined, the three rules produce this effect: AI's exploration path shifts from "breadth-first probing" to "index-based direct access." It no longer lses and guesses. Instead, it locates the target file first, reads the peer-level README to confirm responsibilities, reads the parent-level README to confirm boundaries, then acts. The token cost of these three steps is fixed—it doesn't expand with repo size. That is the most fundamental difference between this and "letting AI fumble around."

4. What a README Should Contain: A Fixed Template with Five Fields (Template)

Don't freeload. Fixed fields let AI form a stable reading expectation—it knows the third paragraph will always be boundary descriptions, so it won't look for startup commands in the boundary section.

Five fields, in order:

  1. One-sentence responsibility: why this directory exists. Writing "what it cannot do" carries more information than "what it can do."
  2. Direct file list: filename → what it does, one per line, sorted by importance.
  3. Boundaries: what shouldn't go here, and where it should go. This section is the core defense against cross-layer edits.
  4. Entry points and commands: if this directory has an executable entry, write the commands.
  5. Change alerts: who editing this will affect. Gives AI a hook to "think before changing."

A real usable sample:

# apps/api/src/routes

## Responsibility
HTTP routing layer only: parses parameters, calls features, returns responses. No business logic.

## Direct Files
- `health.ts` — health check, returns process and dependency status
- `chat.ts` — conversation endpoint, passes through to features/chat
- `ma.ts` — content library endpoint, passes through to features/ingest

## Boundaries
- No SQL: all database access goes through packages/db
- No retry/degradation: these are done in the features layer
- No auth implementation: middleware in ../middleware

## Entry
No independent entry; mounted by ../index.ts.

## Change Alerts
New routes must register dependencies in ../container.ts, otherwise startup fails immediately.

Note this sample has zero filler: no "this directory adopts a modern modular design" adjectives. Everything is executable fact. Adjectives are noise to AI.

5. How to Write the Prompt: Make "Read First" a Hard Constraint (Prompt Rules)

Setting up the README isn't enough—AI won't read it automatically. You must explicitly require it in prompt engineering, written as "condition + action + exception," not as "we recommend reading relevant documentation"—soft phrasing like that AI skips entirely.

A snippet you can paste directly into a rules file or system prompt:

## Directory Index Convention

1. Before modifying any file, you MUST first read the README.md in that file's directory.
2. Then go up one level and read the parent directory's README.md for context; maximum two levels up, do not go higher.
3. If the target directory lacks a README.md, create one per the template before editing. Do not skip.
4. When README conflicts with code, treat code as authoritative, and fix the README in the same change.
5. After adding, deleting, or renaming files, you MUST update the direct-file list in that directory's README.md.
6. Trust only direct descriptions: details of subdirectories come from their own README, not from upper-layer summaries.

Rule 4 is the easiest to ignore, but it decides whether this mechanism survives long-term. Without saying "treat code as authoritative," AI will treat a stale README as gospel and edit today's code according to descriptions from three years ago—more dangerous than not reading the README at all. Documentation is an index, not law.

Rule 5 turns "update the README" into part of the change, not a verbal agreement. Conventions that don't enter the workflow will always rot. It's the same logic as code formatting: no one manually aligns spaces before committing, which is why formatters exist.

6. One Reproducible Measurement: 14 Directories, 9 READMEs, 64.3% (Measurement)

On the benefits of this approach, the internet is full of numbers like "40% efficiency boost" and "bug reduction of half." I refuse to cite a single one, because nobody gives a reproducible definition—what counts as "one change," what counts as "a wrong edit," what the baseline is—none of it is defined. Non-reproducible numbers are noise in technical writing.

The only quantity that can be reproduced is directory coverage. The definition is clear: recursively traverse all directories under the project, skip artifact directories like node_modules, .git, dist, build, and for each directory check whether it directly contains a README file; coverage = directories with README ÷ total directories.

I built a demo tree with 14 directories (typical structure like apps/api/src/routes, packages/core/src), initially writing READMEs only for the root and 9 middle-layer directories. The actual output was:

Root: .
Total directories: 14 | With README: 9 | Missing: 5
Coverage: 64.3%

Missing list (deepest path first, top 20):
  - apps/api/src/middleware
  - apps/api/src/routes
  - apps/worker/src
  - packages/core/src
  - packages/db/src

All 5 gaps are at the leaf layer, and all under src—exactly where AI acts most often and gets lost most easily. One thing becomes clear: human intuition for writing READMEs naturally favors the upper layers, while AI's error-prone spots are naturally at the bottom. The apps/ overview you think is important, AI reads once and is done. What it actually needs is directories like src/routes where "filenames all look alike."

After filling in those 5, running again brings coverage to 100%, and the exit code drops from 1 to 0:

Total directories: 14 | With README: 14 | Missing: 0
Coverage: 100.0%

You can reproduce both numbers on your own repo with the script below; the definition and skip list are in the code, leaving no room for interpretation.

7. Complete Runnable Code: README Gap Checker (Runnable Checker)

The Achilles' heel of this convention is "relying on self-discipline"—create a new directory, forget to write the README, six months later coverage drops back to 60%, and AI is browsing index-less directories again. So a tool must enforce it.

This Node.js script below is zero-dependency. Copy it to scripts/readme-audit.mjs and run it. Node 18+ works (tested on Node 24):

// Usage: node readme-audit.mjs <project root> [--max-rows 20]
import { readdirSync } from "node:fs";
import { join, relative, resolve, sep } from "node:path";

// Artifact and tool directories are excluded from counting, otherwise the coverage metric gets drowned in noise
const SKIP = new Set([
  "node_modules", ".git", ".hg", ".svn", "dist", "build", "out",
  "coverage", ".next", ".nuxt", ".venv", "venv", "__pycache__", ".idea", ".vscode",
]);
// Recognizes README.md / readme.markdown / README.txt, case-insensitive
const README_RE = /^readme(\.md|\.markdown|\.txt)?$/i;
const args = process.argv.slice(2);
const root = resolve(args.find((a) => !a.startsWith("--")) ?? ".");
const rowsFlag = args.indexOf("--max-rows");
const MAX_ROWS = rowsFlag >= 0 ? Number(args[rowsFlag + 1] ?? 20) : 20;

// Recursively collect directories, and record whether each "directly" contains a README file
function walk(dir, acc) {
  const names = readdirSync(dir, { withFileTypes: true });
  const files = names.filter((d) => d.isFile()).map((d) => d.name);
  acc.push({ dir, hasReadme: files.some((f) => README_RE.test(f)) });
  for (const d of names) {
    if (d.isDirectory() && !SKIP.has(d.name)) walk(join(dir, d.name), acc);
  }
  return acc;
}

// Normalize to forward-slash relative paths so Windows and macOS output matches
const pretty = (p) => relative(root, p).split(sep).join("/") || ".";

const all = walk(root, []);
const missing = all.filter((d) => !d.hasReadme);
const covered = all.length - missing.length;
const pct = all.length === 0 ? 100 : (covered / all.length) * 100;

console.log(`Root: ${pretty(root)}`);
console.log(`Total directories: ${all.length} | With README: ${covered} | Missing: ${missing.length}`);
console.log(`Coverage: ${pct.toFixed(1)}%`);
if (missing.length) {
  console.log(`\nMissing list (deepest path first, top ${MAX_ROWS}):`);
  missing
    .sort((a, b) => pretty(b.dir).split("/").length - pretty(a.dir).split("/").length)
    .slice(0, MAX_ROWS)
    .forEach((d) => console.log(`  - ${pretty(d.dir)}`));
}
// Non-zero exit when gaps exist, for use in CI or pre-commit
process.exit(missing.length ? 1 : 0);

How to run and key design decisions:

8. Division of Labor Between README and AGENTS.md, CLAUDE.md (Boundaries)

At this point I must answer a legitimate question: since a layered standard like AGENTS.md already exists, why make a fuss over README?

Because they answer different questions. Per the AGENTS.md community convention (spec details at AGENTS.md layering standard and AGENTS.md Specification, neither is an academic paper, no DOI needed):

File Answers Reader Scope of effect
README.md What is in this directory Humans + AI Current layer; effective only via prompt requiring it to be read first
AGENTS.md What must be done in this directory AI Current layer; the one closest to the file being edited takes precedence
CLAUDE.md / tool-specific files Special instructions for one tool Specific AI Parsed by that tool

The key difference is the effect mechanism: AGENTS.md has an explicit "nearest-first" rule—AI looks up from the file being edited, the closest one wins, and subdirectories can override parents. README has no such mechanism; it works entirely because you wrote "read first" in your prompt engineering. So these aren't replacements:

One counter-intuitive trade-off: don't mix both kinds of content into one file. The rationale is in §4's template design—once a README mixes in ten "must-do" items, its third paragraph stops being a stable boundary statement, AI's reading expectation breaks, and the index function dies first. The cost of mixed responsibilities is usually higher than maintaining one extra file.

9. Symptom → Cause → Fix Reference Table (Symptom → Cause → Fix)

Symptom Cause Fix
AI changed packages/core/src/utils.ts, but you wanted apps/api/src/utils.ts Same-name files lack responsibility descriptions; search results differ only by path Write a README on both sides, noting the domain and non-domain boundaries of that utils in direct-file lists
AI wrote SQL directly in the routing layer, bypassing the db package Cross-layer has no explicit prohibition; AI only sees "this works here" In the "Boundaries" section of routes/README.md, write "no SQL, always go through packages/db"
Nobody updates directory descriptions after adding files; six months later everything is stale Updating docs is a verbal agreement, not part of the change workflow Add rule 5 to the prompt, and wire the checker into CI so missing READMEs fail the build
AI edits code per an outdated README, producing a bunch of functions that don't exist No agreement on "when docs conflict with code, which wins" Add rule 4 to the prompt: code wins, fix the doc in the same change
Every task starts with reading seven or eight files before locating the target No index; AI can only trade breadth-first probing for information Roll out layered READMEs, changing the exploration path from "probing" to "direct access"
Root README is 800 lines; AI still can't tell who owns src/routes after reading it Using one all-in-one document instead of a layered index; granularity is wrong Split per "one per layer, direct-only descriptions"; root keeps only global and directory navigation

10. Rollout Order: Root First, Then Three Layers, Finally CI Gating (Rollout Order)

Don't write all several hundred directories at once—no one can sustain that past day one. Follow this order, and each step takes effect independently:

  1. Root directory: write global responsibility + top-level directory navigation (one line per top-level directory, pointing to its own README). This takes twenty minutes.
  2. Second layer: one README for each direct subdirectory under apps/, packages/, etc. This determines whether AI can distinguish "deployable unit vs. shared package."
  3. Third layer: src/. This layer yields the most benefit—AI's error density is highest here because filenames are most similar.
  4. Wire in the checker: node scripts/readme-audit.mjs . into the CI verify step. Allow existing gaps initially (validate only new directories), then tighten gradually.
  5. Add to the prompt: paste the §5 snippet into the project's rules file, turning "read first" from a suggestion into a hard constraint.

After the first three layers, you usually cover more than 80% of actual changes. Fill in deeper leaf directories on demand: prioritize directories where AI repeatedly errs; skip directories that haven't been touched in a year.

There are also clear cases where this approach should not be used, stated explicitly to prevent misuse:

The judgment criterion is consistently this: will someone (or AI) come back to edit this directory in three months? If yes, it's worth an index. If not, don't write it.

When the number of directories exceeds ten and AI modifies code more than five times a week, this README approach is worth rolling out. For a single-layer small tool, writing a root README suffices.

This column, AI Development Paradigms, covers engineering constraints when AI participates in development—code review checklists, AI interface integration, context organization, and directory conventions. Each article comes with a runnable script, updated weekly. To read in sequence, subscribe from the column page.

Comments

Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.

shushenghong 1 likes

I agree with positioning the README as a directory index for AI. Here's a way to keep it from rotting: during review, every time you spot the AI editing the wrong place, immediately write 'who owns this area and what shouldn't go here' into the README for that layer, rather than simply correcting it once in a comment. This way, the index gets built up one mistake at a time, capturing the traps actually hit, and it remains even after whoever built it leaves. Also, does the gap checker ever consider checking for stale references — files listed in the README that no longer exist?

ENCI

Great approach — turning corrections into index entries on the spot is indeed the key to preventing rot. About stale references: right now the gap checker mainly looks for files in the directory not covered by the README; what you're describing — README entries for files that no longer exist — is the exact opposite. That's a good suggestion; I'll add a two-way check so both extra files and missing files get reported.