Agent skill
Clean comments
Before a PR, trim the noisy, stale and narrating comments agents leave, but only on lines your branch touched.
Use this skill
Install it into a project with the Skills CLI, or read the files below and adapt them to your own agent.
npx skills add shan8851/agent-skills --skill clean-commentsSKILL.md
View this file on GitHub---
name: clean-comments
description: Before a pull request, trim the comments a branch added or changed so they say why, not what or what-used-to-be. Removes history narrative ("used to be X", "previously", "TODO remove after migration"), shadow documentation that restates the code, stale ticket or PR references and comments the change made untrue, and shortens verbose ones. Only touches comment lines in the branch's own diff plus the comment directly above a changed hunk, edits them directly, checks nothing but comments changed, then summarises. Use when the user says "clean up the comments", "trim comments before I open the PR", "make these comments more concise", or "tidy comments on this branch".
---
# Clean comments
Comments that narrate history rot the moment the old system is gone, and agents write a lot of them ("now uses X instead of Y", "fixed the bug where…"). This skill applies one rule at one moment: just before a branch becomes a PR, every comment the branch is responsible for should explain **why**, in terms that stay true after merge.
The job is **trimming the branch's own comments, not a sweep**. A pre-existing comment that's unrelated to this change stays as it is, however bad. Rewriting it would be an unreviewed change riding along in the PR.
## When to use
- A branch is about to become a PR, or a PR is being updated.
- "Clean up the comments", "trim comments", "make these comments more concise", "tidy comments on this branch".
- After an agent-built change (agents over-comment), for example after `plan-and-build`.
Do not use when:
- the user wants comments added or docs written (this skill only removes or rewrites);
- the user wants a whole-file or whole-repo comment cleanup. Say this skill is diff-scoped and ask whether they want a separate, explicit sweep;
- there's no branch diff (working on the default branch with nothing to compare).
## Rules that matter most
1. **Scope is the diff.** In scope: (a) comment lines that appear as added (`+`) lines in the branch's diff against its base, including the new half of a modified comment; (b) a pre-existing comment block or docstring **immediately** above a hunk's first changed line, skipping only blank lines. Nothing else, not even a comment three lines further up the same function.
2. **Only comments change.** Never touch code, strings, formatting or whitespace outside the comment. If a fix seems to need a code change, report it instead.
3. **Keep real motivation.** A comment that explains a constraint, an ordering requirement, a non-obvious choice, a rejected alternative or why a value is what it is stays, even if it mentions history in passing, as long as the reason still holds today.
4. **Don't anchor a rewrite to the old value.** "Retries 5 times (3 caused failures)" still only makes sense to someone who knew it was 3, and becomes the same stale footnote next time it changes. Justify the current value on its own terms. Rejected alternatives are different: they were never live, so "webhook chosen over polling: polling missed bursts" is fine.
5. **A written standard wins; existing comments are not a standard.** If the repo documents a comment style (`CONTRIBUTING`, `CLAUDE.md`, `AGENTS.md`, a style guide), read it and apply it. The comments already in the file are not the house style, however many there are: noisy code breeds noisy comments, and agents copy the precedent. Judge each comment on its own merit. Never keep one because "it matches the surrounding comments".
6. **Edit, then report.** Don't ask per comment. The branch is still a draft and the user reviews the result in the diff, which is faster than approving a list.
## Process
1. **Find the base and the files.** Fetch, work out the branch's real base (the branch it will merge into, not always the default), and take the merge-base: `git merge-base origin/<base> HEAD`. List changed files with `git diff --name-only <merge-base> HEAD`. That list is the whole world. If the working tree has uncommitted changes, include them (`git diff <merge-base>` without `HEAD`) and say so.
2. **Collect candidates per file.**
- Added lines: `git diff --unified=0 <merge-base> -- <file>`. In each `@@ -a,b +c,d @@` header, `c` is the new-file line number of the first added line; count up from there for each `+` line.
- Leading comments: for each hunk, read upward from its first changed line in the current file, skipping blank lines. If the lines directly above are a contiguous comment or docstring, that block is a candidate. Stop at the first line of code.
- Keep only real comments for the language. Ignore `//` in a URL, `#` in a string, commented-out code (report it, don't silently delete it).
3. **Read each candidate with the code it describes.** Never judge a comment from the diff line alone.
4. **Classify** each candidate:
- **History narrative:** describes a past state ("used to", "previously", "now uses", "fixed the old", "after the migration", "TODO remove once…"). Delete, or rewrite to the present-tense reason.
- **Shadow documentation:** restates what the next line obviously does. Delete.
- **Stale reference:** a ticket, PR or issue number that means nothing once merged. Delete the reference; keep any reason around it.
- **No longer true** (leading comments only): the change made the claim wrong. Rewrite to match the code, or delete if there's no lasting reason. If it's still true, leave it.
- **Verbose:** right content, too many words. Always rewrite, never delete.
- **Fine:** leave it, and don't mention it individually.
5. **Edit** the flagged comments directly.
6. **Check only comments changed.** Re-read the diff of every file you edited (`git diff -- <file>` against the pre-edit state) and confirm each hunk is comment-only. Run the repo's formatter or linter on touched files if one is configured. If anything other than a comment changed, revert that edit.
7. **Summarise** in the output format. Don't commit unless the user asks; if they do, make it a separate commit (for example `docs: trim branch comments`) so it's reviewable on its own.
## Output format
```markdown
**Comments cleaned:** [N] removed, [M] rewritten, across [F] files. Only comment lines changed; [formatter/linter result, or "no linter configured"].
**path/to/file.ts**
- L42 removed: "// now uses the cache instead of hitting the API" (history narrative)
- L88 rewritten: "// We spent a while… [first ~10 words]" → "// batch writes: per-row writes hit the rate limit" (verbose)
**Left alone (worth a look):** [only if relevant: out-of-scope comments that looked wrong, commented-out code, a comment that needs a code change to fix]
```
Scale the reply to the change: two or three comments get two or three lines, not the full template. Never leave a placeholder like "[linter result]" in the reply; say what actually ran. If nothing needed changing, say so in one line.
## Adapting to your setup
The process is plain git plus the agent's normal edit tool. What varies is how you find the base and run the check.
- **Claude Code:** use the Edit tool for each change, so the user sees a per-comment diff. A repo `CLAUDE.md` is the usual place a comment standard lives. Pair with a `/code-review` or `/simplify` pass if you have one, but run this last so it sees the final comments.
- **Codex:** same commands; the standard is usually in `AGENTS.md`. Apply patches per file and re-read the diff before reporting.
- **OpenClaw and similar:** if the agent can't run git, ask the user to paste `git diff --unified=0 <base>` and the relevant file sections, then return the edits as a patch for them to apply.
- **Stacked branches:** the base is the branch below this one, not `main`. Ask if it isn't obvious from the upstream or the PR target.
## Common failure modes
- **Copying the precedent:** keeping "// loop over users" because the rest of the file narrates every line. The rest of the file is out of scope, not a style guide.
- **Scope creep:** "while I was there" fixes to comments the branch never touched.
- **Deleting the why:** removing a comment that looked like history but carried the only explanation of a constraint.
- **Anchored rewrites:** "5 retries (was 3)", which is just slower rot.
- **Code drift:** a reflowed line, changed indentation or an accidentally edited string. The comment-only check exists for this.
- **Judging from the diff line:** calling a comment shadow documentation without reading what it describes.
- **Silently deleting commented-out code**, which may be deliberate. Report it.
- **Adding new comments.** This skill only trims and rewrites.
## Next step
When the comments are clean, suggest `tidy-commits` if the branch history needs rebuilding before review. Run clean-comments first so the comment edits fold into the right commits.
## References
- `references/worked-example.md`: a small TypeScript branch, the candidates found, and the edits and summary.
- `references/edge-cases.md`: no base, uncommitted work, docstrings, generated files, commented-out code, licence headers, non-English comments.
references/edge-cases.md
View this file on GitHub# Edge cases
## Can't find the base
- No remote, no upstream, or a detached HEAD: ask which branch this will merge into. Don't guess `main` on a stacked branch.
- On the default branch with no diff: say there's nothing branch-scoped to clean and stop.
## Uncommitted work
- Include working-tree changes in scope (diff against the merge-base, not `HEAD`) and say you did. Don't stage or commit them.
## Docstrings and doc comments
- JSDoc, Python docstrings, Rust `///` and similar are comments. Parameter and return descriptions that the type signature already says are shadow documentation only if the repo doesn't require them (some lint rules do). Check before deleting.
- Public API docs often go into generated documentation. Rewrite rather than delete if they're the only description of the function.
## Generated, vendored or lock files
- Skip them even if they're in the diff (`dist/`, `*.generated.*`, `vendor/`, lockfiles, snapshots). Edits get overwritten and pollute the diff.
## Commented-out code
- Don't delete it. List it under "Left alone" so the author decides.
## Licence headers, directives and pragmas
- Never touch licence headers, `eslint-disable`, `@ts-expect-error`, `# type: ignore`, `#!` lines, `// @flow`, build tags or similar. They look like comments but are instructions to tools.
- A directive's explanation ("// @ts-expect-error: upstream types are wrong for v3") is a normal comment and in scope.
## TODOs
- A TODO the branch added that is still true and has an owner or condition stays. One that refers to finishing a migration this branch completes is history: remove it.
- Never resolve a TODO by writing code.
## Comment in a language you can't judge
- If a comment is in a language you don't read well, leave it and mention it. Don't machine-translate it into the file.
## Very large diffs
- Over a few hundred candidates, work file by file and report progress. Don't sample: the scope is the diff, all of it.
## The user asks for a sweep
- Explain the diff scope once. If they still want a whole-file pass, treat it as a separate, explicit request, ideally in its own commit or PR.
references/worked-example.md
View this file on GitHub# Worked example
A branch `fix/rate-limit-sync` changes how a sync job writes rows. The base is `main`. Two files changed.
## The diff (abridged)
```diff
--- a/src/sync/writer.ts
+++ b/src/sync/writer.ts
@@ -12,9 +12,14 @@ import { client } from "../db";
// Writes one row per call.
-export async function writeRows(rows: Row[]) {
- for (const row of rows) await client.insert(row);
+export async function writeRows(rows: Row[]) {
+ // Previously we wrote one row at a time, which hit the rate limit (see #482).
+ // Now we batch them instead.
+ // chunk the rows
+ for (const chunk of chunked(rows, BATCH_SIZE)) {
+ await client.insertMany(chunk);
+ }
}
@@ -40,6 +45,11 @@
+// We looked at three options here: a queue, a cron job, or just retrying
+// inline. After some discussion we went with inline retries because a queue
+// was a lot of infrastructure for one job and the cron approach meant data
+// could be up to an hour stale, which product didn't want.
+const MAX_RETRIES = 5; // was 3 but that wasn't enough
```
```diff
--- a/src/sync/config.ts
+++ b/src/sync/config.ts
@@ -3,2 +3,2 @@
// Keep batches under the provider's 500-row request cap.
-export const BATCH_SIZE = 100;
+export const BATCH_SIZE = 250;
```
## Candidates
| Location | Category | Verdict |
|---|---|---|
| writer.ts L12 "Writes one row per call." | leading comment above hunk 1 | **no longer true**: rewrite |
| writer.ts L15–16 "Previously… (see #482). Now we batch…" | added | **history + stale ref**: rewrite to the reason |
| writer.ts L17 "chunk the rows" | added | **shadow doc**: delete |
| writer.ts L45–48 alternatives paragraph | added | **verbose** but real motivation: rewrite shorter |
| writer.ts L49 "was 3 but that wasn't enough" | added | **anchored to old value**: rewrite |
| config.ts L3 "Keep batches under… 500-row cap." | leading comment above hunk | still true at 250: **leave** |
Note what wasn't a candidate: a comment at writer.ts L30 ("TODO: handle deletes") is a context line, not adjacent to a hunk. It stays, even though it looks stale.
## Edits
```ts
// Writes rows in batches of BATCH_SIZE.
export async function writeRows(rows: Row[]) {
// Batched: per-row inserts hit the provider's rate limit.
for (const chunk of chunked(rows, BATCH_SIZE)) {
await client.insertMany(chunk);
}
}
```
```ts
// Inline retries over a queue (too much infra for one job) or cron (data up to an hour stale).
const MAX_RETRIES = 5;
```
The trailing comment on `MAX_RETRIES` gave no current reason, only the old value. Nothing in the code or commit messages says why 5, so don't invent one: remove it and flag the gap under **Left alone**. If the branch had said why (say, a commit message noting the provider throttles for about two minutes), the rewrite would be `// covers the provider's ~2 minute throttling window`.
## Check
`git diff -- src/sync/writer.ts` shows only `//` lines changed. The repo has ESLint; `pnpm eslint src/sync/writer.ts` passes.
## Summary
```markdown
**Comments cleaned:** 2 removed, 3 rewritten, across 1 file. Only comment lines changed; ESLint passes.
**src/sync/writer.ts**
- L12 rewritten: "Writes one row per call." → "Writes rows in batches of BATCH_SIZE." (no longer true)
- L15–16 rewritten: "Previously we wrote one row at a time… (see #482). Now we batch them instead." → "Batched: per-row inserts hit the provider's rate limit." (history narrative, stale reference)
- L17 removed: "chunk the rows" (shadow documentation)
- L45–48 rewritten: 4-line options paragraph → one line (verbose; alternatives kept)
- L49 removed: "was 3 but that wasn't enough" (anchored to the old value; no current reason given)
**Left alone (worth a look):** MAX_RETRIES has no stated reason. config.ts L3 is still accurate at 250.
```