← Public packages
@kentcdodds/codebase-cleanup
Cursor cloud agents for legacy cleanup, docs freshness, tight tests, and prod CI fixes, plus a weekly Devin general audit.
Files
/**
* Editable prompt templates - unique job only.
* Shared shipping / skills / prod-data / format footer is appended by resolvePrompt
* (shipping footer for Cursor-launched automations; private-report footer for Devin).
* Placeholders: {{repo}}, {{branch}}, {{extra}}, {{notify}} (how to reach the owner).
* Scoped templates also use {{range}}, {{files}}, {{reasons}}, and {{branchName}}.
*/
import { auditReportSkeleton } from '../shared.ts'
export const legacyReaperTemplate = `# Legacy Reaper
Eliminate cruft in **{{repo}}** (\`{{branch}}\`) that slows every future change: dead code, expired shims/dual-reads, stale flags, obsolete docs/temporal language, unused deps, test/CI drift, leftover migration residue.
Do real work - small shippable slices, not a status meeting. North star: **net line reduction** with high confidence.
1. **Audit** (bounded). Categorize findings; pick conflict-partitioned tracks (non-overlapping file/migration ownership).
2. **Giant ambiguous areas** → spawn a separate investigation agent (a strong investigation model); instruct it to open a GitHub issue linking itself when done.
3. Prefer high-confidence contained wins.
4. Drive cleanup with \`/conductor\` when that skill exists.
5. Ship each track per the footer.
6. Report: {{notify}} with +/- lines per track and a link to this agent.
{{extra}}
`
export const prodCiFailureTemplate = `# Prod CI failure
Fix the CI failure on **{{repo}}** \`{{branch}}\`; open a PR with the smallest honest fix (prefer real correctness over silencing the check).
{{extra}}
`
export const docsFreshnessTemplate = `# Docs freshness
Refresh docs for **{{repo}}** (\`{{branch}}\`).
Standing docs should describe **how things are now**, not "now we support X" / "we no longer support Y" - unless the doc is explicitly about migrations. Keep legitimately reader-temporal phrases (e.g. "now that you're verified you can connect to the MCP server").
Also: tighten organization, cut duplication, verify accuracy (including inaccurate comments in code). Finding nothing is fine.
{{extra}}
`
export const keepTestsTightTemplate = `# Keep tests tight
Tighten tests in **{{repo}}** (\`{{branch}}\`). If \`docs/contributing/testing-principles.md\` exists, apply it.
Delete leftover agent tests: tautological asserts, static-value pins, lone "q is not there" after a deletion. Keep state-flip absences (x there → action → x gone). Every remaining test needs an independent oracle that can fail on a real regression. Finding nothing is fine.
{{extra}}
`
export const docsFreshnessScopedTemplate = `# Docs freshness
Follow up on recent changes in **{{repo}}** (\`{{branch}}\`), range \`{{range}}\`. A triage model flagged the files below. Start from these files and the docs that describe them.
{{files}}
{{reasons}}
When a file needs nothing, note it in the PR. When nothing needs changing, open no PR.
{{extra}}
`
export const keepTestsTightScopedTemplate = `# Keep tests tight
Follow up on recent changes in **{{repo}}** (\`{{branch}}\`), range \`{{range}}\`. A triage model flagged the files below. Start from these files and the tests that cover them. If \`docs/contributing/testing-principles.md\` exists, apply it.
{{files}}
{{reasons}}
When a file needs nothing, note it in the PR. When nothing needs changing, open no PR.
{{extra}}
`
export const generalAuditTemplate = `# Weekly general audit
Run a thorough general-purpose audit of **{{repo}}** (\`{{branch}}\`) in this one session. Read the code; scanners alone are not enough. Finding nothing in a lane is a fine result; say what you covered.
## How to run this audit
- Walk the four lanes below **in order**, finishing each lane before you start the next: 1. Security, 2. Performance, 3. Accessibility, 4. Code health.
- Finish every lane yourself in this single session.
- For every lane, note which files you reviewed.
## Lane 1: Security
Run a thorough security audit. Work through every area below and note which files you reviewed for each:
1. **Authentication and authorization:** session and token handling, login and OAuth flows, token minting and expiry, permission and scope checks on every route, handler, RPC, and background job. Look for missing checks, checks after side effects, and confused-deputy paths.
2. **Multi-tenant isolation:** every query and storage key is scoped to the right user or org; no cross-tenant reads or writes through ids taken from input; shared caches and queues keep tenants apart.
3. **Secrets handling and leakage:** secrets in source, fixtures, logs, error messages, analytics, client bundles, or API responses; secret interpolation that could reach the wrong host; weak or missing redaction.
4. **Injection:** SQL, command, template, path traversal, header and log injection, prototype pollution, unsafe regex (ReDoS).
5. **SSRF and outbound requests:** user-influenced URLs or hosts, redirect following, internal or metadata addresses, DNS rebinding.
6. **Unsafe deserialization and eval:** \`eval\`, \`new Function\`, dynamic import of input, unsafe YAML or JSON revivers, untrusted code execution sandboxes and their escape paths.
7. **Webhooks:** signature verification (HMAC over the raw body, constant-time compare, replay protection, timestamp checks), and that unsigned or unverified requests do nothing.
8. **CORS, cookies, and browser security:** CORS origin rules, credentialed CORS, cookie flags (Secure, HttpOnly, SameSite), CSRF protection, CSP and other security headers, open redirects, XSS.
9. **Dependencies:** run the package manager's audit (for example \`npm audit\` or \`pnpm audit\`) and judge which advisories are actually reachable from this code.
10. **Anything else you notice** with real impact (rate limiting on auth, crypto misuse, insecure defaults).
## Lane 2: Performance
Look for real, user-facing or cost-relevant slowness. Work through every area below and note which files you reviewed for each:
1. **Data access:** N+1 queries, unbounded queries or missing pagination, missing indexes for hot filters and joins, queries inside loops, over-fetching columns or rows.
2. **Request paths:** serial awaits that could run in parallel, blocking or synchronous I/O on hot paths, redundant outbound calls, missing timeouts, retry storms.
3. **Caching:** missing or broken caching for expensive reads, cache keys that never hit, stale or unbounded caches.
4. **Memory and resource use:** unbounded arrays, maps, or queues; leaks from listeners, timers, or intervals that are never cleared; large payloads held in memory; CPU-heavy work in request handlers or edge workers with tight limits.
5. **Client performance:** bundle size and heavy dependencies shipped to the browser, missing code splitting, expensive re-renders, layout thrash, unoptimized images and fonts, waterfalls of client requests.
6. **Background work:** polling that could be event-driven, jobs that reprocess everything instead of deltas, schedules that run far more often than needed.
7. **Anything else you notice** with real impact.
Measure locally when it is cheap (for example a build size report or a local benchmark). Keep load tests off production and live deployments.
## Lane 3: Accessibility
Review every user-facing UI (web pages, components, emails, CLI output meant for people). If the repo has no UI, say so and report this lane as none found. Work through every area below and note which files you reviewed for each:
1. **Semantics and structure:** semantic HTML and landmarks, heading order, lists and tables marked up as such, page titles and \`lang\`.
2. **Keyboard and focus:** everything reachable and operable by keyboard, visible focus, logical tab order, focus management for dialogs, menus, and route changes, no keyboard traps.
3. **Names and labels:** labels for every form control, accessible names for icon-only buttons and links, meaningful \`alt\` text (or empty \`alt\` for decorative images), error messages tied to their fields.
4. **ARIA:** ARIA used correctly or not at all; roles, states, and properties that match behavior; live regions for async status and errors.
5. **Visual:** color contrast, information not conveyed by color alone, text that survives zoom and reflow, \`prefers-reduced-motion\` respected.
6. **Anything else you notice** that blocks or slows people using assistive technology.
## Lane 4: Code health
Work through every area below and note which files you reviewed for each:
1. **Dead code:** unused exports, files, components, routes, feature flags, config, and unreachable branches. Confirm each is truly unused (search for dynamic references) before calling it dead.
2. **Dependency drift:** outdated, deprecated, duplicated, or unused dependencies, mismatched versions across workspaces, and lockfile drift (for example \`npm outdated\`, \`pnpm outdated\`). Note which upgrades are breaking.
3. **Test gaps:** critical paths with no tests, tests with no independent oracle that could fail on a real regression, skipped or flaky tests, and important error paths never exercised.
4. **Anything else you notice** that makes the code harder to change safely (duplicated logic, type escapes like \`any\` or non-null assertions on untrusted data, confusing ownership).
## Severity (all lanes)
Rate each finding Critical, High, Medium, Low, or Info, with confidence (confirmed, likely, speculative). Prefer fewer real findings over a long speculative list.
## Safe testing
- Use static review and local testing. Keep probes, scans, and exploit payloads off production and live deployments.
- Refer to any secret you find by file path and line, and recommend rotation. Leave the secret value out of every output.
## Disclosure rules (strict)
This repository may be public. Unpatched vulnerabilities stay private.
- Keep findings in the private report. Leave GitHub issues, discussions, gists, PR comments, and review comments for other work.
- Describe vulnerability fixes in the private report so the owner can decide how to ship them. Leave PRs, branches, and commit messages free of vulnerability details.
- Put performance, accessibility, and code health suggested fixes in the private report for the owner to ship. The only PRs allowed in any lane are the optional hygiene PRs below.
- Keep findings off public channels, chat, and websites.
- Keep private info out of public places: leave out user or org handles, emails, internal ids, and credential details.
## Private audit report
Deliver the report privately: {{notify}}. Keep each message under 1900 characters and send several if needed (split between lane sections, never inside a finding). Include:
- A one-line summary: counts by severity across all lanes and the commit SHA you audited.
- One section per lane, in lane order: Security, Performance, Accessibility, Code health. Every section starts with the lane name and its counts by severity.
- Per finding: severity, confidence, a short title, the affected file paths, and the suggested fix. Keep exploit steps and payloads out of the message.
- A lane with zero findings still gets its section, with the line "None found." and what you covered.
- What you covered and anything you could not check.
- A link to this session, which holds the full write-up (put exploit details and reproduction steps there only).
Use this format (replace the angle-bracket placeholders; repeat the finding line per finding):
\`\`\`
${auditReportSkeleton()}
\`\`\`
## Optional hygiene PRs
You may open a PR only for low-risk hygiene that discloses nothing, such as a routine dependency bump. Its title, body, branch name, and commits must read as ordinary maintenance: no CVE or advisory ids, no "security fix" wording, and no link to the findings. Leave it open and mention it in the private report.
{{extra}}
`
export const scopedTemplates = {
'docs-freshness': docsFreshnessScopedTemplate,
'keep-tests-tight': keepTestsTightScopedTemplate,
} as const
export const templates: Record<
'legacy-reaper' | 'prod-ci-failure' | 'docs-freshness' | 'keep-tests-tight' | 'general-audit',
string
> = {
'legacy-reaper': legacyReaperTemplate,
'prod-ci-failure': prodCiFailureTemplate,
'docs-freshness': docsFreshnessTemplate,
'keep-tests-tight': keepTestsTightTemplate,
'general-audit': generalAuditTemplate,
}