Using AI to Add Comments to Legacy Code: Common Failures and the Right Approach
1. First, Let's Talk About the Common Ways This Fails
Any developer who has taken over an old project has probably had this experience: the repo contains hundreds of lines of Shell scripts and a pile of regular expressions nobody dares to touch. No comments, no documentation, the original authors have long since left, and git blame points to "initial commit."
So many people's first instinct is: let the AI do it all in one go.
Failure mode #1: Throw the whole file at the AI and say "add comments for me."
The result is usually a set of comments that look beautiful but are actually useless. For example, AI will comment the regex ^(?:\d{1,3}\.){3}\d{1,3}(:\d+)?$ as "matches an IP address with an optional port" — correct, but it doesn't explain that in the actual business logic this regex validates the upstream gateway whitelist, or which branch the logs go to when validation fails. Anyone can write a generic explanation; business context is the soul of comments on legacy code.
Failure mode #2: Accept the AI's first draft and commit it directly.
The AI sometimes "helpfully" does extra things: changes ${var} to $var, replaces grep -E with what it considers a better syntax, or describes in the comments its imagined ideal behavior rather than the script's actual behavior. You think it's a comment-adding PR, but it's actually a stealth refactoring PR — and when something breaks, you don't even know which line to roll back.
Failure mode #3: Process too much at once, with no acceptance step.
Annotating dozens of scripts all at once means reviewers can't keep up and merge them hastily. Three months later, you discover a comment that completely contradicts the code's behavior, which creates new "trust debt": everyone starts assuming comments are unreliable, which is worse than having no comments at all.
Failure mode #4: Only comment the regex itself, not why it exists.
For something like sed 's/\r$//', the AI will write "removes carriage returns." But what should really be recorded is: "In 2019, a file committed by a Windows colleague contained CRLF line endings, which caused a cron job to fail silently once." AI can't guess this kind of decision context unless you give it the material.
2. The Right Path: Small Batches, Provide Context, Read-Only Mode, Keep an Acceptance Step
The core principle in one sentence: the AI handles understanding and the first draft; you provide context and acceptance, and explicitly forbid it from changing the code.
The workflow I've settled on has five steps:
- Inventory the legacy code. First, use a simple script to list all files to be annotated, sorted by "high risk (called by cron, on the production path)" vs. "low risk (one-off tools)." Start with small, high-risk files to build confidence.
- Feed in small batches. One file at a time, or a group of related regexes. Attach context: who calls this script, what the inputs and outputs look like, known historical pitfalls.
- Use a "read-only mode" prompt. Explicitly require the AI not to modify any character of code; comments may only explain the current behavior.
- Accept via diff. Use
git diff -wto check whether anything besides comments has changed. Reject any non-comment changes. - Backfill business knowledge. For spots the AI marked as "uncertain," find the person on the team most familiar with that code to confirm, or run a piece of real input to verify the AI's explanation, then add the business context.
With this approach, a 200-line deployment script takes about ten minutes from feeding to acceptance; manually working through it from scratch would take at least an hour, and you still might not claim to fully understand it.
3. Before vs. After Using AI
Before using AI:
- A new hire taking over the script library spends days on average asking around and trial-and-error;
- One wrong character in a regex causes silent log-collection loss, discovered a week later;
- The answer to "why was this written this way" exists only in the head of a colleague who has already left;
- Nobody dares to delete or modify anything, so scripts keep piling up.
After using AI (once the workflow is running smoothly):
- Every file has a header comment with its responsibilities, dependency list, and known side effects;
- Complex regexes are broken down section by section with comments, plus 2–3 matching/non-matching examples;
- Comments flag portability traps like "this behavior depends on a GNU sed feature and won't work on macOS";
- Review cost drops from "read through the code" to "verify whether the AI's explanation matches the behavior" — for solo developers, this means a dramatic reduction in self-review time.
The key change isn't "writing faster," but that legacy code becomes discussable and transferable for the first time. For a solo-maintained project, it's like gaining a partner who's always available and can read terrible code.
4. A Reusable Prompt Template
你是一位资深 Shell 与正则维护工程师。请为下面的存量代码补充注释。
严格遵守:
1. 只添加注释,禁止修改、格式化或"优化"任何一行原有代码,包括空格;
2. 注释解释的是代码的真实行为,不是理想行为;不确定的地方标注 [待确认];
3. 文件头部增加块注释,包含:脚本职责、输入输出、依赖的外部命令、已知风险;
4. 对每个正则表达式,逐段拆解含义,并给出 1-2 个能匹配和 1 个不能匹配的示例;
5. 指出可移植性问题(如 GNU/BSD 差异)、边界情况和潜在的静默失败点;
6. 输出完整代码,并在最后单独列出"我无法确定、需要人工确认的点"。
背景信息(供理解,不要写进注释):
- 该脚本的调用方:{cron/CI/手动}
- 运行环境:{系统/SHELL 版本}
- 已知历史问题:{没有可写"无"}
代码:
{粘贴代码}That last item — "separately list the points needing confirmation" — is especially useful: it makes the AI's uncertainty explicit, so you only need to spend effort verifying those few spots instead of doubting every line.
5. A Few Reminders
- On model choice, for this kind of task I recommend a stronger-capability model; check the official pricing page for current prices. Commenting is a one-time investment, so prioritize quality over cost.
- For scripts containing sensitive information, sanitize them before feeding them to the AI.
- After the comments are merged, have the next reader double-check them — the credibility of comments is built through continuous maintenance.
Legacy code won't speak for itself, but with the right workflow and tools, AI can "translate" it for you. If you're planning to give it a try, you can first register an account at https://api.thistoken.ai/register and practice on the most painful script in your repo — the best way to climb out of the failure patterns is to run through it again the right way.
---
Tired of juggling provider integrations? Register at https://api.thistoken.ai/register and call every model through one base_url.
Vous voulez essayer Token.AI ?
Créez une API Key au niveau du projet, activez les canaux dans la console et configurez le routage, les budgets et les journaux d'audit.
注册 ThisToken.AI 并获取 API Key