You've Probably Been There Too
At the end of last year, I took over a legacy project that had been maintained for five years. The original developer had long since left, and the only handover documentation was a README that said "see the wiki for deployment"—and the wiki link was already a 404.
The code itself ran fine, but the problem was: nobody could explain why it was written that way. Thirty thousand lines of Python, dozens of modules calling each other, some functions over two hundred lines long, with the only comments being a few # TODO: 后续优化 markers—that "later" had been pending for four years.
In this situation, any change is a high-risk operation. My estimate at the time was that manually reading the code to understand the core modules' call relationships and design intent would take at least three to four weeks. But the schedule only gave me one week, and I still needed time to work on feature requests within that.
If this scenario feels familiar, this article is for you. I ultimately used an AI-assisted approach to compress "understanding legacy code" down to three working days, and the resulting architecture documentation was more systematic than what manual organization would have produced.
What AI Can Actually Do Here
Let me first lay out clearly what AI can take on, because it can do more than most people imagine:
- Generate structured comments file by file: function responsibilities, parameter meanings, return values, boundary conditions, known side effects—output in a unified format.
- Map out module dependencies: read imports and call chains, and output explanations of "who depends on whom and why."
- Identify implicit design decisions: for example, why a lock was added somewhere, where a magic number came from, or how a piece of code that "looks redundant" is actually a workaround for a known bug.
- Generate architecture documentation: including a system layering diagram (text version), core data flows, startup process, and a list of external dependencies.
- Flag risk points: hardcoded configurations, outdated patterns, critical paths without test coverage—these become the map for future refactoring.
Pay attention to point 3. This is AI's most easily underestimated capability. A lot of the "why it was written this way" information in legacy code is actually hidden in the code patterns themselves. AI can infer reasonable guesses from context, which you then confirm. When reading code manually, we often don't even know "what questions to ask."
My Actual Process
Step 1: Have AI Produce a Global Map First
Don't start adding comments file by file right away. First, feed the project directory structure to the AI and have it produce a module inventory and dependency overview. The output of this step determines which files to prioritize later—core chains first, peripheral utility classes later.
Step 2: Feed in Batches, Generate Comments Module by Module
Split by module, feed in one module's code at a time, and have the AI output structured comments. The key constraint is consistent formatting—otherwise the final assembled result will be a mess.
Step 3: Let AI Find Suspicious Points Itself
After generating comments, I follow up with another round of questions: "Which parts of this module do you find unclear in intent, or potentially carrying historical baggage?" The AI produces a list of suspicious points, and I take that list to ask former colleagues or check git blame (good news: the git history is still there), then add the answers back into the documentation. In this step, AI poses the questions and humans answer them—far more efficient than hunting for a needle in a haystack.
Step 4: Consolidate into Architecture Documentation
Aggregate the output from each module, have the AI generate the final architecture documentation, then manually proofread the factual content.
A Reusable Prompt Template
This is the core template I used in Step 2—you can take it and adapt it directly:
你是一位资深代码考古专家。我会给你一个模块的源代码,
请为它生成结构化注释文档,输出格式如下:
## 模块概览
- 模块职责:(一句话)
- 对外暴露的接口:(列表)
- 内部依赖与外部依赖:(列表)
## 函数级注释
对每个函数,输出:
- 函数名与签名
- 职责:(一句话说清楚做什么)
- 参数说明:(每个参数的含义与格式)
- 返回值:
- 副作用与注意事项:(写文件、改全局状态、网络请求等)
- 意图存疑处:(如无法从上下文确定的写法,标注"待人工确认",不要编造)
## 风险标记
- 硬编码值、魔法数字、疑似过时写法、缺失的错误处理
要求:
1. 不确定的内容明确标注"待人工确认",严禁猜测后当作事实写出
2. 保持所有注释格式一致,便于后续合并
3. 使用中文输出
代码如下:
<在此粘贴代码>Requirement 1 is critical. The biggest pitfall of AI-generated comments is "confidently fabricating intent"—describing a bug as a design decision. Forcing it to flag uncertain items turns hallucinations into a to-do list.
Before and After: The Numbers Speak
Using this thirty-thousand-line project as the reference:
| Task | Manual Estimate | AI-Assisted Actual | Savings |
|---|---|---|---|
| Module dependency mapping | 4-5 days | 0.5 days | ~90% |
| Full function comments | 8-10 days | 1.5 days (incl. manual spot checks) | ~80% |
| Architecture documentation | 2-3 days | 0.5 days | ~80% |
| Risk point investigation | 2 days | 0.5 days | ~75% |
| Total | 16-20 days | 3 days | ~80% |
On cost: processing thirty thousand lines of code involves a non-trivial amount of tokens, and the actual expense depends on the model and usage you choose—refer to the official pricing page. But one thing is certain: even with a more expensive model, the total cost is far lower than two weeks of a developer's time. I used the saved time for two more valuable things: adding tests for the core paths, and aligning with the business team on the boundaries for future refactoring.
Another benefit that's hard to quantify: the resulting documentation is consistently formatted. When humans write comments manually, they start slacking off by day three; AI doesn't.
A Few Practical Tips
- Feed in small batches. Stuff an entire project in at once and the AI will spread itself too thin, with noticeably degraded output quality. Split by module and the quality is much more stable.
- Manual spot checks are non-negotiable. For each module, I randomly pick two or three functions to verify the comments, and immediately redo any where fabrication is found. This is the key action for maintaining a quality baseline.
- Git history is a golden companion. More than half of the items AI flags as "pending manual confirmation" can be answered directly through git log and commit messages.
- Documentation must flow back into the repository. Put the AI-generated documentation into
docs/and include it in review—otherwise, when the next person takes over, you're creating a new "legacy project."
Final Thoughts
The documentation debt of legacy codebases used to be the kind of debt you "knew you should repay but could never fit into the schedule." AI has pushed the cost of repayment down to less than a fifth of what it was, turning this from "should do" into "just do it along the way."
If you want to run this process yourself, try hooking up an API and building your own pipeline—batch-processing an entire repository is far more efficient than manually pasting into a chat window. The registration entry point is here: https://api.thistoken.ai/register —once you get your key, the prompt template above can be slightly adapted to run batches directly.
---
Ready to try it yourself? Sign up at https://api.thistoken.ai/register to get your API key and start building.
Token.AI を試してみませんか?
プロジェクトレベルの API Key を作成し、コンソールでチャネルを有効にして、ルーティング、予算、監査ログを設定しましょう。
注册 ThisToken.AI 并获取 API Key