Let an agent delete your dead TypeScript, but only the code that's really dead: Knip as the worklist, a triage script as the brake
A Knip report, a 70-line triage script and a three-part gate that stop a cleanup from deleting the handler nobody tests. About 15 minutes to try.

Somebody asks the agent to “clean up unused code” in a TypeScript service. It finds a few helpers, deletes them, runs the tests, and reports green. The diff is 400 lines smaller and looks like a good afternoon.
Three weeks later a webhook for voided invoices does nothing. The handler lived in src/handlers/void.ts, loaded by name at runtime from a string in the request. No import statement pointed at it, so nothing in the editor, the compiler or the agent’s grep saw a caller. No test covered it either, which is why the suite stayed green.
Dead-code removal is a good job for an agent. It’s tedious, the answer is mostly mechanical, and the diff is easy to review once it’s small. The risk is that “unused” is a claim about what a tool can see, not about what production does. This Playbook builds a loop that takes the mechanical part (Knip finds candidates) and adds a brake (a script that separates the safe deletions from the ones that need a human), so the agent only touches what has been checked. The loop works with any coding agent that can read files and run a shell.
The project
A small invoicing module is enough to show every case. Knip 6.48.0, Vitest 5.1.1 and TypeScript 7.0.2 on Node 22.23.5:
src/index.ts public entry: re-exports totalCents and runHandler
src/money.ts totalCents (used), formatEuro and legacyRound (unused)
src/oldReport.ts imports formatEuro, imported by nothing
src/registry.ts loads src/handlers/<name>.ts with a dynamic import
src/handlers/refund.ts loaded by name, covered by a test
src/handlers/void.ts loaded by name, covered by nothing
package.json lists lodash-es, which nothing imports
The registry is the part that fools static analysis:
export async function runHandler(name: string, payload: unknown): Promise<string> {
const mod = await import(`./handlers/${name}.ts`);
return mod.default(payload);
}
The test file checks the total and the refund handler. The tsconfig has allowImportingTsExtensions on so the template-string import type-checks and types: ["node"] for the node:fs import used later, and the project’s package.json has "type": "module" with scripts for test, typecheck and knip.
Step 1: Get Knip’s worklist
Install it as a dev dependency and run it with no config:
npm i -D knip
npx knip
It exits with code 1 and prints:
Unused files (3)
src/handlers/refund.ts
src/handlers/void.ts
src/oldReport.ts
Unused dependencies (1)
lodash-es package.json:11:6
Unused exports (2)
formatEuro function src/money.ts:4:17
legacyRound function src/money.ts:7:17
Four of these are real. Two are wrong: both handler files are reported unused, because the only reference to them is a template string. Knip’s own documentation says it starts from entry files (by default index, main and cli at the root and in src/, plus whatever plugins and package.json fields add) and follows imports from there. A computed path isn’t an import it can follow.
Now the naive version. Knip can apply its own fixes: --fix removes unused exports and dependencies, and --allow-remove-files lets it delete files too. In a throwaway copy:
npx knip --fix --allow-remove-files
Unused files (3)
src/handlers/refund.ts (removed)
src/handlers/void.ts (removed)
src/oldReport.ts (removed)
Unused dependencies (1)
lodash-es package.json:11:6 (removed)
Unused exports (2)
formatEuro function src/money.ts:4:17 (removed)
legacyRound function src/money.ts:7:17 (removed)
Then the checks an agent would run:
$ npx tsc --noEmit && echo tsc ok
tsc ok
$ npx vitest run
FAIL test/money.test.ts > refund handler
Error: Unknown variable dynamic import: ./handlers/refund.ts
Tests 1 failed | 1 passed (2)
The compiler is happy, because nothing in the remaining code names the deleted files. The test run catches refund, because a test exercises it. It says nothing about void. If the agent had also been told to “fix failing tests”, the most likely repair is to delete the refund test or loosen it, and then the cleanup is a clean green run with two production handlers gone. A passing suite proves the tested code still works. It says nothing about untested code.
Step 2: Triage the report before the agent sees it
The brake is a script that reads Knip’s JSON report and sorts each finding into safe or suspect. A finding is suspect if something besides an import could be referring to it:
- A file sits in a directory that a non-literal
import()orrequire()can reach. - A file’s name appears as text somewhere else in the repo (a config file, a test, a doc, a workflow).
- An export’s name appears as a quoted string (a registry key, a decorator argument, a reflection lookup).
- A dependency’s name is mentioned in any file other than
package.jsonand the lockfile.
Save this as scripts/dead-code-triage.py. It uses only the standard library and the --reporter json and --no-exit-code flags from Knip’s CLI:
#!/usr/bin/env python3
"""Sort Knip's unused-file and unused-export findings into safe and suspect."""
import json, re, subprocess, sys
from pathlib import Path
SKIP = {"node_modules", ".git", "dist", "coverage"}
TEXT = {".ts", ".tsx", ".js", ".mjs", ".json", ".yml", ".yaml", ".md", ".toml", ".sh"}
def repo_files():
for p in Path(".").rglob("*"):
if p.is_file() and p.suffix in TEXT and not SKIP & set(p.parts):
yield p
def dynamic_dirs(files):
"""Directories that a non-literal import() or require() can reach."""
dirs = set()
pat = re.compile(r"(?:import|require)\(\s*[`'\"]?(\./[^`'\"$)]*)\$\{")
for p in files:
if p.suffix in {".ts", ".tsx", ".js", ".mjs"}:
for m in pat.finditer(p.read_text(errors="ignore")):
dirs.add((p.parent / m.group(1)).resolve())
return dirs
def main():
report = json.loads(subprocess.run(
["npx", "knip", "--reporter", "json", "--no-exit-code"],
capture_output=True, text=True).stdout)
files = list(repo_files())
texts = {p: p.read_text(errors="ignore") for p in files}
dyn = dynamic_dirs(files)
out = {"safe": [], "suspect": []}
for issue in report["issues"]:
for f in issue["files"]:
path = Path(f["name"]).resolve()
stem = Path(f["name"]).stem
why = []
if any(d == path.parent or d in path.parents for d in dyn):
why.append("sits in a directory a dynamic import() can reach")
hits = [str(p) for p, t in texts.items()
if p.resolve() != path and re.search(rf"['\"`/]{re.escape(stem)}['\"`.]", t)
and not p.name.startswith("knip")]
if hits:
why.append("name appears as text in " + ", ".join(sorted(set(hits))[:3]))
out["suspect" if why else "safe"].append(
{"kind": "file", "target": f["name"], "why": why})
for e in issue["exports"]:
hits = [str(p) for p, t in texts.items()
if re.search(rf"['\"`]{re.escape(e['name'])}['\"`]", t)]
out["suspect" if hits else "safe"].append(
{"kind": "export", "target": f"{issue['file']}#{e['name']}",
"why": ["quoted as a string in " + ", ".join(hits[:3])] if hits else []})
for d in issue["dependencies"]:
hits = [str(p) for p, t in texts.items()
if p.name not in {"package.json", "package-lock.json"} and d["name"] in t]
out["suspect" if hits else "safe"].append(
{"kind": "dependency", "target": d["name"],
"why": ["mentioned in " + ", ".join(hits[:3])] if hits else []})
json.dump(out, sys.stdout, indent=2)
print()
main()
On the unconfigured project it reports (trimmed to the targets and reasons):
safe:
src/oldReport.ts
lodash-es
src/money.ts#formatEuro
src/money.ts#legacyRound
suspect:
src/handlers/refund.ts
sits in a directory a dynamic import() can reach
name appears as text in test/money.test.ts
src/handlers/void.ts
sits in a directory a dynamic import() can reach
That’s the split a reviewer would make by hand after twenty minutes of grepping. The script is crude on purpose. It over-flags (a file named index will match plenty of text) and a false “suspect” costs a minute, while a false “safe” costs an outage.
Step 3: Teach Knip about the dynamic folder
For every suspect, decide whether the file is live or dead. For the handlers the answer is live, so tell Knip. Add knip.json:
{
"$schema": "https://unpkg.com/knip@6/schema.json",
"entry": ["src/index.ts", "src/handlers/*.ts"],
"project": ["src/**/*.ts"]
}
One detail matters here: Knip’s docs state that custom entry and project values replace the defaults and aren’t merged, which is why src/index.ts is listed again. Leave it out and the public entry stops being an entry, and everything it exports looks unused.
Run Knip again:
Unused files (1)
src/oldReport.ts
Unused dependencies (1)
lodash-es package.json:11:6
Unused exports (2)
formatEuro function src/money.ts:4:17
legacyRound function src/money.ts:7:17
The report now matches reality, and the triage script returns an empty suspect list. This step is the real payoff: the configuration is a durable record that handlers load by convention. The next person (or agent) to run Knip gets the right answer without anyone remembering why.
If a suspect turns out to be dead, don’t add it to a Knip ignore list. Put it in the deletion batch with a note, and let the gate prove it.
Step 4: The gate
Create scripts/gate.sh. Three checks, in the order they fail fastest:
#!/usr/bin/env bash
set -euo pipefail
npx tsc --noEmit
npx vitest run --reporter=dot
npx knip --no-progress --max-issues 100 --reporter compact
The first two guard behaviour. The third guards the cleanup itself: --max-issues 100 stops Knip’s own exit code from failing the gate while work remains, and the compact reporter prints nothing when the project is clean, so an empty tail means done. In CI, switch back to the default --max-issues 0 so a new unused export fails the build, which stops the debt from coming back.
Step 5: The agent prompt
Hand the agent the report and the rules. This prompt works in any tool that can run a shell:
Remove dead code from this TypeScript project. Work from the output of
`python3 scripts/dead-code-triage.py`, not from your own search.
Rules:
1. Only act on items in "safe". Never touch an item in "suspect"; list each
one with its reason at the end and stop.
2. One batch = one kind of change (files, then exports, then dependencies).
After each batch run `./scripts/gate.sh`. If it fails, revert that batch
with git and report which item broke it. Do not edit tests to make the
gate pass.
3. Deleting a file can make other things unused. Re-run the triage script
after each batch and continue until "safe" is empty.
4. Commit each passing batch separately, one line saying what was removed.
5. Do not use `knip --fix`. Delete by hand so the diff shows what went.
Rule 3 matters in this project. formatEuro was already flagged because its only caller, oldReport.ts, is itself unused, and in a larger codebase deleting one file regularly exposes the next layer. Looping until the safe list is empty is how those chains get removed, and the re-run after each batch is what keeps each step checked.
Rule 5 is a preference. --fix is fine for exports and dependencies once the report is right, and file removal behind --allow-remove-files is safe only after Step 3. Hand deletion costs a few more tool calls and gives a diff that reads like a list.
What the result looks like
For the safe batch, delete src/oldReport.ts, uninstall lodash-es and drop the two exports from src/money.ts. The file ends up as:
export function totalCents(lines: { qty: number; unitCents: number }[]): number {
return lines.reduce((sum, l) => sum + l.qty * l.unitCents, 0);
}
The gate passes:
$ ./scripts/gate.sh
RUN v5.1.1 /tmp/knipdemo
ยทยท
Test Files 1 passed (1)
Tests 2 passed (2)
No tsc output means no errors, and no Knip output means no findings. Both handler files are still on disk, and git status shows the changes to package.json, the lockfile and src/money.ts plus the one deleted file.
Close the gap the gate can’t see
The suspect list exists because tests don’t cover everything, and void.ts stayed green in the naive run precisely because nothing exercised it. Before relying on the gate for a module, add the missing check. For handlers loaded by name, one parameterised test is enough:
import { readdirSync } from "node:fs";
import { expect, test } from "vitest";
import { runHandler } from "../src/index.js";
const names = readdirSync(new URL("../src/handlers", import.meta.url))
.filter((f) => f.endsWith(".ts"))
.map((f) => f.replace(/\.ts$/, ""));
test.each(names)("handler %s loads and returns a string", async (name) => {
expect(typeof (await runHandler(name, { id: 1 }))).toBe("string");
});
Every file in that folder is now exercised, and the suite runs four tests where it ran two. Deleting a handler file removes its test case instead of failing, so this test only proves that what exists loads. For the real contract (which handler names production sends), a second test should assert against the list of names the API accepts. That list is the thing worth pinning, and the agent can write the test from the router code.
Make it yours
A few variations that fit different setups:
- Libraries. Knip ignores exports from entry files by default, so a package’s public API isn’t flagged. Don’t pass
--include-entry-exportsunless you want that, and be careful with--production, which analyses only production source and drops tests and dev dependencies from the picture. - Monorepos. Run the triage per workspace with
-W(Knip’s workspace filter), and have the script search every workspace for text references, since a package name is often mentioned by a sibling’s config. - Framework conventions. Next.js routes, Nest modules, decorators and file-based routers all load code without imports. Knip’s docs say plugins add entry files, but check the report for a framework’s convention folders anyway, and run the triage script, which flags dynamic-import directories whatever the framework.
- CI. Run Knip with the default
--max-issues 0on pull requests. An agent that adds a helper it never calls then fails the build, which is the same cleanup problem caught a week earlier.
What goes wrong
Text matching has holes. The triage script finds references that are spelled out. It can’t see a name assembled from pieces ("handle" + kind), a path read from a database row, or a file named in a deploy script outside the repo. For anything that smells of runtime lookup, ask the owner of the service, not the agent.
Knip is a static tool with config to maintain. A wrong entry list gives false positives (live code reported dead) or false negatives (dead code kept alive by an over-broad glob such as src/**/*.ts). Treat knip.json as code and review changes to it.
Large deletions need review at the batch level. Each batch is small enough to read in a minute. If a batch touches more than a few files, split it. A reviewer who sees “removed 14 exports” can verify that claim against the report. A reviewer who sees one 400-line diff will skim.
Don’t bother if the codebase has little dead code or no tests worth the name. In the second case, write the characterisation tests first (see the characterisation grid post ), because the gate has nothing to protect without them.
First 15 minutes
Install Knip in a branch of one service (npm i -D knip, npx knip), and read the unused-files section before anything else. For each file ask how it could be loaded other than by an import, and put the answers in a knip.json. Then copy the triage script and the gate, give the agent the prompt above, and read the first commit it produces.