Sweeps TypeScript codebases of dead code, unused deps, AI-generated slop, and weak types using Knip and structured cleanup waves. Preserves platform invariants for Cloudflare Workers and other edge runtimes.
Ships in use-sentry. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
A TypeScript codebase accumulates. Features get deprecated but their files stay. A refactor lands half-finished and both abstractions survive. An LLM writes cn for the fourth time in a fourth directory, launders types with as any, duplicates schemas alongside manual interfaces, and blankets properties in defensive ?. optional chains. Dependencies outlive the code that imported them. Types get exported "just in case" and never consumed. In edge environments like Cloudflare Workers (workerd), agents hallucinate process.env, strip ctx.waitUntil() as "redundant", or delete worker-configuration.d.ts as an "unreferenced file".
This skill sweeps all of it into a clean, robust end state guided by The 5 Pillars of TypeScript Project Cleanup:
env, async ctx.waitUntil() boundaries, ambient types (worker-configuration.d.ts), and RPC actor entry points (DurableObject, WorkerEntrypoint, WorkflowEntrypoint).as any, as unknown as T), maintain the type-coverage ratchet, enforce schema inference as single source of truth (z.infer), eliminate non-erasable syntax (--erasableSyntaxOnly), and ensure declaration-emit safety.git reset or git revert.This is a finishing tool. Run it on a green main branch, not mid-feature.
Trigger on phrases and repo states like:
Do NOT use this skill for:
run-repo-cleanup.run-review.Pick the mode explicitly at the start, from the user's ask. Announce which one you picked. Escalating mid-run is fine; silently doing more than was asked is not.
| Mode | Runs | Fires on |
|---|---|---|
| Sweep | Phase 0-1, then lint autofix and Wave 1 only | "tidy this up quickly", "drop the dead files" |
| Standard | Phases 0-3, then Waves 1-5 | "clean up the dead code" — the default |
| Deep | Standard, plus Phase 4 root-cause work, type hardening, and structural refactor | "the codebase is a mess", "make this maintainable", "improve codebase architecture" |
No single tool finds everything. Each engine sees one scope and is blind to the others.
| Engine | Finds | Scope | Autofix? |
|---|---|---|---|
| Knip (v5/v6) | Unused files, exports, types, dependencies, unlisted binaries, import cycles | Module graph | Yes — scoped per wave (--fix-type files, exports, types, dependencies) with native --format via Formatly |
| Biome / Oxlint / ESLint / Ultracite | Unused locals (TS6133), dead imports, correctness lint | File AST | Yes — native autofix per engine (oxlint --fix-dangerously, biome check --write) |
tsc | Type errors, declaration-emit breakage (TS4023, TS2742), non-erasable syntax | Program | No — diagnostic verification gate (tsc --noEmit or tsc -b --clean && tsc -b) |
type-coverage | any-creep score and untyped identifier coordinates | Program | No — numeric ratchet measurement (--detail --strict) |
dpdm / madge | Circular dependency visualization & type-only vs runtime cycles | Import graph | No — inspection & verification (Knip also supports --cycles) |
| anti-slop rules | LLM-generated antipatterns (as any, schema drift, duplicate helpers) | File AST | Partial — targeted linters & ripgrep sweeps |
Knip and the linters are complements, not alternatives: Knip finds a file nothing imports, a linter finds an import nothing uses. Read references/engines/engine-matrix.md for the full matrix and the auto-detection protocol.
Decided once; override per-project only if the repo says otherwise (AGENTS.md / CLAUDE.md / CONTRIBUTING.md win over this skill).
| Key | Default | Why |
|---|---|---|
| the gate | tsc --noEmit (or tsc -b with --clean / --outDir /tmp/dts-check for composite projects) → test → build | The single verification barrier. Defined once in references/remediation/waves.md; every "Run the gate" in this skill means exactly that. |
| branch | chore/ts-cleanup | Never work on main. |
| config file | knip.jsonc (fallback knip.json) | JSONC carries comments explaining why each entry exists. Schema: https://unpkg.com/knip@6/schema-jsonc.json (or @5). |
| package manager | Detected from packageManager field, else lockfile | Never hardcode pnpm or run bare npx tsc (which can invoke obsolete [email protected]). Always use $PM_EXEC tsc. |
| wave order | Files → Barrels/Cycles → Encapsulation → Types → Dependencies | Causal order: pruning leaves first eliminates dead import branches; dependencies pruned last avoids TS2307 crashes. |
| commit unit | One commit per wave | Each wave reverts independently. |
| suppression | Targeted keys only | ignoreDependencies, ignoreBinaries, ignoreExportsUsedInFile, explicit entry. |
git status --porcelain is empty, the typecheck passes, and the test suite passes before touching anything. A cleanup that begins on a red baseline cannot distinguish its own damage from pre-existing damage.ignoreDependencies, ignoreBinaries, ignoreExportsUsedInFile, or an explicit entry — each one silences exactly the finding it names. A broad top-level ignore severs graph edges instead, so files the ignored code imports start reporting as dead and get deleted.knip --fix. Running --fix with all fix types simultaneously deletes files, prunes exports, and mutates package.json in one un-audited pass. Always scope --fix-type to the specific wave (--fix-type files in Wave 1, --fix-type exports in Wave 3, etc.) and leverage --format.tsc --noEmit checks the implementation graph, not the declaration graph. For composite projects or published libraries, prove .d.ts emit using --declaration --emitDeclarationOnly --outDir /tmp/dts-check or tsc -b --clean && tsc -b. In TS 5.8+, tsc -b --noEmit is supported, but CLI --outDir remains forbidden on -b.workerd) invariants. Never delete worker-configuration.d.ts, never prune @cloudflare/workers-types, never strip ctx.waitUntil(), and never access process.env in worker handlers.cn before deleting them; migrate callers before pruning an abstraction.workerd) InvariantsCloudflare Workers runs on Cloudflare's open-source workerd V8 isolate runtime, not Node.js. AI agents and generic cleanup tools consistently make catastrophic mistakes in Workers codebases due to assuming Node.js runtime behavior. When auditing or cleaning up a Workers project, prioritize these non-negotiable rules:
┌────────────────────────────────────────────────────────────────────────┐
│ CLOUDFLARE WORKERS (WORKERD) INVARIANTS │
├──────────────────────────────────┬─────────────────────────────────────┤
│ 1. Ambient Types Protection │ 2. Platform Lifecycle & RPC Classes │
│ • worker-configuration.d.ts │ • ExportedHandler (fetch/queue) │
│ • @cloudflare/workers-types │ • DurableObject, WorkerEntrypoint│
│ • @cloudflare/vitest-pool │ • WorkflowEntrypoint classes │
├──────────────────────────────────┼─────────────────────────────────────┤
│ 3. Runtime Environment Isolation │ 4. Async Boundary Safety │
│ • No global process.env │ • ctx.waitUntil(promise) │
│ • Request-scoped env binding │ • Zero floating background tasks │
│ • this.env in RPC classes │ • Prevent isolate suspension │
└──────────────────────────────────┴─────────────────────────────────────┘
wrangler types)worker-configuration.d.ts (or env.d.ts): Generated by running npx wrangler types. It contains ambient type declarations for KV, D1, R2, Queues, and secrets. Because it contains no imports or exports, naive dead-file sweeps will flag it as unreferenced. You must protect it in knip.jsonc (entry: ["src/index.ts", "worker-configuration.d.ts"] or in ignore). Never delete this file.@cloudflare/workers-types & @cloudflare/vitest-pool-workers: These dependencies are configured in tsconfig.json (compilerOptions.types) and vitest.config.ts, not imported in application source files. Knip will report them as unused dependencies. Always add them to ignoreDependencies in knip.jsonc.ExportedHandler<Env>: The root handler in src/index.ts default-exports an object implementing fetch, scheduled, queue, email, or tail. These methods are invoked by the platform runtime upon cron or queue events, not by local TypeScript imports. Never strip these lifecycle exports.DurableObject, WorkerEntrypoint, or WorkflowEntrypoint are referenced in wrangler.json (e.g. "bindings": [{"name": "COUNTER", "class_name": "Counter"}]) and called via service bindings or RPC.
[!CRITICAL] Knip's built-in
wranglerplugin only inspectsconfig.main. It does NOT inspectdurable_objects,workflows, or service bindings inwrangler.json. Any RPC class in a separate file (e.g.src/objects/counter.tsorsrc/workflows/order.ts) will be reported as an unused file or unused export! Defense: Protect them by adding them toentryinknip.jsonc(e.g."entry": ["src/index.ts", "src/workflows/**/*.ts!"]) or marking their exports with JSDoc/** @public */alongside"includeEntryExports": false.
process.env Eradication & Request-Scoped envIn workerd, process.env is not populated with bindings or secrets. At runtime, process.env.MY_SECRET returns undefined, leading to silent authentication failures or crashes:
// ❌ WRONG (Node.js leak — crashes in workerd):
export async function getDb() {
return drizzle(process.env.DB_URL!); // Returns undefined!
}
// ✅ CORRECT (Edge-native request-scoped env drilling):
export function getDb(env: Env) {
return drizzle(env.PROD_DB);
}
In DurableObject and WorkerEntrypoint classes, access bindings via this.env:
export class AnalyticsWorker extends WorkerEntrypoint<Env> {
async record(event: string) {
await this.env.ANALYTICS_KV.put(event, Date.now().toString());
}
}
ctx.waitUntil)In workerd, when the Promise returned by fetch() settles with a Response, the V8 isolate is immediately suspended or terminated. Un-awaited background promises are aborted mid-flight:
// ❌ WRONG (Floating promise killed when Response is returned):
export default {
async fetch(req, env, ctx) {
env.AUDIT_QUEUE.send({ url: req.url }); // Aborted mid-flight!
return new Response("OK");
}
} satisfies ExportedHandler<Env>;
// ✅ CORRECT (Protects background work until complete):
export default {
async fetch(req, env, ctx) {
ctx.waitUntil(env.AUDIT_QUEUE.send({ url: req.url }));
return new Response("OK");
}
} satisfies ExportedHandler<Env>;
Never strip or unwrap ctx.waitUntil() calls as "redundant wrappers".
knip.jsonc for Cloudflare Workers{
"$schema": "https://unpkg.com/knip@6/schema-jsonc.json",
"wrangler": true,
"vitest": true,
"entry": [
"src/index.ts",
"worker-configuration.d.ts",
"src/workflows/**/*.ts!"
],
"project": ["src/**/*.{ts,tsx}", "test/**/*.{ts,tsx}"],
"includeEntryExports": false,
"ignoreExportsUsedInFile": {
"interface": true,
"type": true
},
"ignoreDependencies": [
"@types/*",
"@cloudflare/workers-types",
"@cloudflare/vitest-pool-workers"
],
"ignore": [".wrangler/**"]
}
AI agents introduce structural bloat due to bounded context windows, lack of cross-file memory, and pressure to make compiler checks green at all costs:
as any, as unknown as T, or chained non-null assertions (x!.y!.z!) when encountering complex generics or external API payloads.
zod.safeParse()) or validate internal object shapes using satisfies.interface User right next to const UserSchema = z.object({...}). Over time, one drifts from the other.
export type User = z.infer<typeof UserSchema>;.a?.b?.c?.d 4 levels deep or if (x && x.y && x.y.z) on strictly typed internal models.
index.ts with export * from './...' in every folder, then importing siblings back through that barrel.
mockUserData, createTestClient, or private _helper from production files so unit tests can import them.
test/ or __mocks__/; test observable behavior through the public module interface ("Replace, don't layer").interface IUserService with exactly one class UserService, or generic abstractions function run<T = unknown>() "just in case".
val is User with typeof val === 'object' && val !== null without checking mandatory fields.
UserSchema.safeParse(val).success.const getX = (id) => api.get(id)).
src/utils/ instead of keeping them local to their feature.
--erasableSyntaxOnly (introduced in TS 5.8). Replace enums with string literal unions (type Status = 'active' | 'inactive') and use explicit property declarations.In Deep mode, cleanup is not just line deletion; it is structural improvement. We integrate Matt Pocock's architecture deepening philosophy into pure Markdown reports (codebase-health.md):
Do not waste time refactoring cold, dormant files that haven't changed in months. Target modules with active churn:
git log --oneline -n 100 -- src/
Focus structural refactoring where development velocity is actively impeded.
Classify every architectural proposal with explicit confidence ratings:
[STRONG]: Clear win with concrete precedent and immediate payoff (e.g. inlining single-use pass-through wrapper, removing cyclic barrel).[WORTH EXPLORING]: Worth considering; has architectural trade-offs that benefit from team alignment (e.g. grouping micro-files into feature pods).[SPECULATIVE]: High risk or only beneficial at massive scale; defer unless current pain is severe (e.g. introducing hexagonal ports and adapters).In codebase-health.md, illustrate structural transformations with Mermaid flowcharts:
flowchart TD
subgraph Before["Before: Shallow Wrappers & Circular Barrel Smog"]
C[Consumer] --> B[Barrel: index.ts]
B --> W[Shallow Wrapper: fetchUser]
W --> S[Core API Service]
S --> B
end
subgraph After["After: Deep Module & Direct Boundary"]
C2[Consumer] --> D[Deep User Module]
D --> E[Direct External API]
end
dead code · unused deps · AI slop · weak types · tangled imports
│
Phase 0 — Baseline: clean tree, green typecheck, green tests, branch cut
│
Phase 1 — Engine setup: detect stack, resolve manager, configure knip v6
│
Phase 2 — Survey: run engines, batch findings (1-9), detect cycles
│
Phase 3 — Triage: apply Three-Question Test, classify verdicts
│
Phase 4 — Architectural Deepening: inlining, seams, zod inference, [Deep]
workerd invariants, codebase-health.md
│
Phase 5 — Waves: scoped deletions, verification gate, one commit per wave
│
zero dead code · green gate · one revertable commit per wave · clean repo
test -z "$(git status --porcelain)"git checkout -b chore/ts-cleanup$PM_EXEC tsc --noEmit && $PM_EXEC testtype-coverage %, cycle count).python3 scripts/audit-ts-health.py --target .python3 scripts/init-knip-config.py --format jsoncworker-configuration.d.ts), RPC entrypoints, and @cloudflare/workers-types ignores.ignore patterns in configuration.python3 scripts/batch-findings.py --run --output markdown --out-file cleanup-plan.md
knip --cycles or npx madge --circular --extensions ts,tsx src/$PM_EXEC type-coverage --detailas any), schema drift, process.env in workers.Apply the Three-Question Verification Test to every finding:
fetch/scheduled, Remix loader)?import(), or RPC service binding?Mark each item in cleanup-plan.md as dead, false-positive, or deferred.
z.infer<typeof Schema>.export * with direct named imports.process.env in worker handlers and wrap background tasks in ctx.waitUntil().codebase-health.md with Mermaid before/after diagrams.Each wave runs behind a passing verification gate and is committed atomically:
| Wave | Deletes | Scoped Knip Autofix | Gate Verification | Commit Message |
|---|---|---|---|---|
| 1 | Unreferenced files | knip --fix-type files --allow-remove-files --format | Full gate | chore: remove unreferenced files |
| 2 | Barrel re-exports & cycles | Manual refactor / direct imports | Full gate + cycle check | refactor: prune dead barrels and break cycles |
| 3 | Test leaks & private exports | knip --fix-type exports --format | Full gate | refactor: internalize private exports |
| BRIDGE | Linter cleanup | Biome / Oxlint / ESLint | Clears TS6133 unused locals | chore: linter autofix after un-export |
| 4 | Unused types & enums | knip --fix-type types --format | Full gate + declaration emit check | refactor: prune dead types |
| 5 | Unused dependencies | knip --fix-type dependencies --format | Full gate + lockfile sync | chore(deps): prune unused dependencies |
| Mistake | Consequence | Instead |
|---|---|---|
Running all-in-one knip --fix | Deletes files, exports, and packages in one un-audited pass; causes unbisectable breakage | Scope --fix-type per wave (files, exports, types, dependencies) and use --format |
| Assuming Knip's wrangler plugin protects RPC classes | It only parses config.main; DurableObjects, WorkerEntrypoints, and Workflows get deleted | Protect RPC classes via entry in knip.jsonc or mark with JSDoc /** @public */ |
Deleting worker-configuration.d.ts in Cloudflare Workers | Destroys ambient bindings; env: Env immediately fails typecheck across worker | Protect in knip.jsonc entry or ignore; never delete ambient declarations |
Accessing process.env in Cloudflare Workers | Returns undefined at runtime in workerd isolates; causes silent production crashes | Drill request-scoped env parameter or access this.env in RPC classes |
Stripping ctx.waitUntil() as "redundant wrapper" | Isolate suspends on response settle; background logs, queues, and metrics are aborted | Preserve ctx.waitUntil() for all edge background work |
Running bare npx tsc | If typescript is not in local node_modules, invokes obsolete [email protected] published in 2017 | Always use $PM_EXEC tsc (e.g. pnpm exec tsc, bun x tsc, or npx -p typescript tsc) |
Passing --no-config-lookup in ESLint v9 for TS | Disables config resolution entirely; defaults to basic JS parser and fails on .ts files | Use flat config (eslint.config.mjs) or invoke targeted linter rules |
Trusting tsc -b --noEmit on older TS versions | Fails with fatal error TS5094 in TypeScript < 5.8 | In TS < 5.8, use tsc --declaration --emitDeclarationOnly --outDir /tmp/dts-check |
Passing --isolatedDeclarations without --declaration | Fails with TS5069: Option isolatedDeclarations cannot be specified without declaration | Pair with --declaration --emitDeclarationOnly --outDir /tmp/dts-check |
Broad top-level "ignore": ["src/legacy/**"] in Knip | Knip halts graph traversal; imports within those files report as dead and get deleted | Use targeted keys: ignoreDependencies, ignoreBinaries, ignoreExportsUsedInFile |
| Dual declaration of Zod schema + manual TypeScript interface | Types drift silently when schemas are updated | Use type T = z.infer<typeof TSchema> as single source of truth |
Exporting internal helpers solely for unit tests (_helper) | Leaks implementation details into public API; breaks encapsulation | Test observable outcomes across public interface ("Replace, don't layer") |
Single-implementation IUserService interfaces | Creates ghost interfaces and doubles file/type maintenance burden | Export concrete implementation directly until a second adapter genuinely exists (Seam Test) |
Dumping single-consumer helpers into src/utils/ | Context fragmentation; creates circular webs and junk drawers | Colocate in consumer file (< 25 LOC) or feature pod (1-to-1 Rule) |
| Using enums / namespaces with modern transpilers | Fails --erasableSyntaxOnly (TS 5.8+); causes bundler transpile friction | Use string literal unions and standard classes |
Python 3 stdlib only — no dependencies, no network beyond the engines they invoke.
| Script | Phase | Purpose | Mutates? |
|---|---|---|---|
scripts/audit-ts-health.py | 1, 4 | Detects linters and formatters, audits tsconfig.json flags, finds import cycles, flags AI slop markers & schema drift. | No |
scripts/init-knip-config.py | 1 | Scans frameworks and monorepo layout; emits knip.jsonc/knip.json with a valid $schema (knip@6) and built-in compilers. | Yes — --dry-run to preview, --force to overwrite |
scripts/batch-findings.py | 2 | Runs or parses the dead-code and analysis engines; batches findings across all 9 batches, scores risk, renders gates. | Only with --out-file |
--fix-dangerously), ESLint (Flat Config v9), and Ultracite recipes.type-coverage, native Knip cycles (knip --cycles), madge, and anti-slop rules.workerd) deep guide: wrangler types, RPC class preservation (DurableObject, WorkerEntrypoint), process.env eradication, and ctx.waitUntil safety.any-creep, type-coverage ratchet, incremental strict-mode migration, type tidying.--isolatedDeclarations, TS4023/4081/4082/4060/2742/2883 matrix, and pre-un-export checklist.Prove green → configure engines & protect platform invariants → survey all scopes across 9 batches → triage with Three-Question Test → deepen architecture & address root causes → delete in five scoped, gated waves → report the deltas.
agents/openai.yaml (opens in a new tab)references/detection/code-slop-catalog.md (opens in a new tab)references/detection/false-positive-triage.md (opens in a new tab)references/detection/finding-classification.md (opens in a new tab)references/engines/analysis-engines.md (opens in a new tab)references/engines/engine-matrix.md (opens in a new tab)references/engines/knip-configuration.md (opens in a new tab)references/engines/lint-engines.md (opens in a new tab)references/remediation/complexity-thresholds.md (opens in a new tab)references/remediation/structural-refactor.md (opens in a new tab)references/remediation/waves.md (opens in a new tab)references/runtimes/cloudflare-workers.md (opens in a new tab)references/types/declaration-emit.md (opens in a new tab)references/types/strict-migration.md (opens in a new tab)scripts/audit-ts-health.py (opens in a new tab)scripts/batch-findings.py (opens in a new tab)scripts/init-knip-config.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
31 skills in this plugin
/audit-agentic-cliUse if auditing or designing a CLI for agent/LLM use — JSON output, exit codes, non-interactive./audit-agentic-mcpUse if auditing or designing an MCP server for agent-readiness — framework, security, context./audit-completionUse if verifying claimed-done work or auditing session/plan/branch completion with evidence./audit-skill-by-derailmentUse if testing a skill with an agent execution trace; never for ordinary code, PR, or workflow review./yigitkonur-use-sentry:run-ts-cleanupfrom use-sentry
Generated from the plugin's indexed repository (yigitkonur/skills-by-yigitkonur) — no native marketplace selected
npx claudepluginhub p/yigitkonur-use-sentryOther plugins' skills for the same job