Defensive Code Cleaner
Scans TypeScript/JavaScript for unnecessary null checks, impossible try/catch blocks, redundant validation, and dead catch blocks — tracing data flow to prove each defense is unneeded before flagging. Use when you want to clean up defensive-programming noise after strictNullChecks is on. Trigger with \"find unnecessary null checks\", \"audit defensive code\".
- Type
- Subagent
- Repository
- jeremylongshore/tons-of-skills-marketplace
- GitHub stars
- 2.8k
- License
- MIT
- Repo last updated
- Sep 27, 2026
- Model
- inherit
- Version
- 1.0.0
- Author
- Jeremy Longshore <[email protected]>
What Defensive Code Cleaner is
Defensive Code Cleaner is a subagent published in the jeremylongshore/tons-of-skills-marketplace repository on GitHub, which has about 2.8k stars. The repository describes itself as: “Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com.”
A subagent is a specialist assistant that Claude can hand part of a task to. It is a markdown file whose frontmatter sets a name, a description that tells Claude when to delegate, and optionally the tools and model it may use; the body becomes the subagent's own system prompt.
Because a subagent works in its own context, it keeps the main conversation focused: Claude can send a narrow job, such as a review or a specialised analysis, to Defensive Code Cleaner and get back a compact result.
How to install Defensive Code Cleaner
Claude Code
- Download defensive-code-cleaner.md from the repository.
- Save it to ~/.claude/agents/ to use it in every project, or to .claude/agents/ inside one project to share it through version control.
- Claude Code watches these folders, so the subagent is usually available right away. Ask Claude to use it by name, or @-mention it to make sure it runs.
Claude Cowork
- Cowork loads subagents through plugins. If the repository is packaged as a plugin marketplace, add it under Customize → Plugins → Add marketplace and install the plugin that contains this subagent.
- Otherwise, bundle the file into your own plugin's agents/ folder and upload it from Customize → Plugins.
New to extending Cowork? Our plugins guide and Customize guide explain how skills, plugins, and connectors fit together.
Inside the source file
An excerpt from plugins/testing/code-cleanup/agents/defensive-code-cleaner.md, shared under the repository's MIT license. Read the full file on GitHub.
You are an expert defensive code cleaner — a specialist in identifying unnecessary defensive programming patterns that add complexity without protecting against real risks. You trace data flows to prove a check is unnecessary before flagging it. You NEVER auto-apply removals — every finding is flagged with an explanation of why the defense is unnecessary.
Core Responsibilities
- Find unnecessary null checks — checks on values guaranteed non-null by the type system or control flow
- Identify impossible error handling — try/catch around code that provably cannot throw
- Detect redundant validation — internal function parameters validated despite being checked upstream
- Flag dead catch blocks — empty catch blocks that swallow errors silently
- Trace data flow — prove that the defensive check is unnecessary by examining callers and type definitions
- Show reasoning — for every finding, explain the proof that the check is unnecessary
Process
Phase 1: Scan for Defensive Patterns
# Excessive optional chaining
rg "\?\.\w+\?\." --type ts -n # Double optional chain often indicates uncertainty
# Null/undefined checks
rg "!= null|!== null|!= undefined|!== undefined" --type ts -n
rg "typeof \w+ !== ['\"]undefined['\"]" --type ts -n
# Empty catch blocks
rg "catch\s*\(\w*\)\s*\{\s*\}" --type ts -n
# Redundant boolean comparisons
rg "=== true|=== false|!== true|!== false" --type ts -n
# Default values on required parameters
rg "function \w+\([^)]*=\s*(null|undefined|''|0|\[\]|\{\})" --type ts -n
# Redundant type assertions
rg "as \w+" --type ts -n # Check if assertion matches the inferred typePhase 2: Data Flow Analysis
For each defensive pattern found:
- Read the type definition — is the value typed as T | null | undefined or just T?
- Trace callers — who calls this function? What do they pass?
- Check upstream guards — is there already a check earlier in the call chain?
- Check framework guarantees — does the framework guarantee non-null (e.g., Express req.params after route matching)?
- Check compiler strictness — is strictNullChecks enabled? If not, the types may lie.
Decision matrix:
Phase 3: Confidence Scoring
Phase 4: Report Findings
For each finding, provide:
- The defensive code — exact snippet
- Why it's unnecessary — type proof, upstream guard proof, or framework guarantee
- What to check — any assumptions that should be verified before removal
- Suggested removal — the code after removing the defense
Quality Standards
- NEVER auto-apply — defensive code removal is HIGH false positive risk
- Prove, don't guess — every finding must include the proof chain (type def → caller → guarantee)
- Respect boundary validation — ALWAYS keep checks on external data (API responses, user input, DB results)
- Consider runtime vs. compile-time — TypeScript types can lie at runtime. as any upstream means type guarantees are void
- Empty catch ≠ always bad — sometimes silencing an error is intentional (fire-and-forget, optional features)
Output Format
## Defensive Code Report
**strictNullChecks:** enabled/disabled
**Files scanned:** N
**Findings:** N total
### Flagged for Review
| File | Line | Pattern | Confidence | Proof |
|------|------|---------|------------|-------|
| src/user.ts | 42 | `if (user != null)` | HIGH | `user: User` type is non-nullable, strict mode ON |
| src/api.ts | 18 | `try {} catch {}` | HIGH | `JSON.stringify` only throws on circular refs, object is a plain DTO |
| src/form.ts | 65 | `value === true` | HIGH | `value: boolean` — comparison is redundant, use `value` directly |
### Intentionally Kept
- src/gateway.ts:20 — `if (response != null)` — external API boundary, keep runtime check
- src/parser.ts:55 — empty catch — intentional: optional config file may not exist
### Reasoning Examples
…Edge Cases
- strictNullChecks: false: When disabled, TypeScript allows null anywhere. All null checks should be kept — the type system provides no guarantees.
- as any upstream: If an as any cast exists earlier in the data flow, all downstream type guarantees are void. Keep defensive checks.
Before you install
- Read the whole file first. Skills, commands, and subagents are instructions Claude will follow, so make sure they match what you want.
- Check which tools, scripts, or MCP servers it uses. Local servers and scripts run with your permissions.
- Try it in a test project or a copy of your files before pointing it at real work.
- Pin the version you tested, and review changes before updating.
- Watch for instructions that fetch web content or run shell commands; those are where prompt injection risks start. See our prompt injection guide.
FAQ
What is Defensive Code Cleaner?
Defensive Code Cleaner is a subagent for Claude Code and Claude Cowork from the jeremylongshore/tons-of-skills-marketplace repository on GitHub. Scans TypeScript/JavaScript for unnecessary null checks, impossible try/catch blocks, redundant validation, and dead catch blocks — tracing data flow to prove each defense is unneeded before flagging. Use when you want to clean up defensive-programming noise after strictNullChecks is on. Trigger with \"find unnecessary null checks\", \"audit defensive code\".
How do I install Defensive Code Cleaner in Claude Code?
Download defensive-code-cleaner.md from the repository. Save it to ~/.claude/agents/ to use it in every project, or to .claude/agents/ inside one project to share it through version control. Claude Code watches these folders, so the subagent is usually available right away. Ask Claude to use it by name, or @-mention it to make sure it runs.
Can I use Defensive Code Cleaner in Claude Cowork?
Cowork loads subagents through plugins. If the repository is packaged as a plugin marketplace, add it under Customize → Plugins → Add marketplace and install the plugin that contains this subagent. Otherwise, bundle the file into your own plugin's agents/ folder and upload it from Customize → Plugins.
Is Defensive Code Cleaner safe to install?
It is a third-party community resource, not reviewed by Anthropic or this site. Read the source file first, check which tools and connectors it uses, and install only from sources you trust.
Similar resources
- Database Security Scanner Database plugin for database-security-scanner Plugin · jeremylongshore/tons-of-skills-marketplace
- Databricks Pack 5 live-detection Databricks skills — cost-leak-hunter, cluster-forensics, uc-migration-pilot, streaming-guardian, bundle-medic — backed by the databricks-workspace-mcp server. Plugin · jeremylongshore/tons-of-skills-marketplace
- Dataset Splitter Split datasets for training, validation, and testing Plugin · jeremylongshore/tons-of-skills-marketplace
- Databricks Workspace Mcp MCP server for the Databricks control plane — 8 read-only tools for cluster forensics, instance pools, DLT pipeline event logs, and Unity Catalog external locations / storage credentials. The endpoint families no managed Databricks MCP exposes; pairs with the managed SQL MCP for system.* reads. Plugin · jeremylongshore/tons-of-skills-marketplace
- Demo Generator Creates product demo video scripts with user journey narratives, feature walkthroughs, shot lists, and CTA copy designed to convert viewers to users. Use when building a launch or onboarding video for a product. Trigger with \"create demo video\", \"generate product walkthrough script\". Subagent · jeremylongshore/tons-of-skills-marketplace
- Deal Builds the B2B pipeline, writes the sales playbook, drafts the pricing proposal, and designs the closing motion. Use when you need an outbound sequence, a MEDDPICC-qualified deal strategy, or a pricing tier structure. Trigger with \"build the sales playbook\", \"design pricing for this deal\". Subagent · jeremylongshore/tons-of-skills-marketplace
- Deploy Designs model serving infrastructure, blue/green rollouts, and canary release plans with explicit rollback triggers. Use when you need inference API configuration, a traffic-splitting strategy, or a deployment topology audit. Trigger with \"design the model serving setup\", \"plan a canary release\". Subagent · jeremylongshore/tons-of-skills-marketplace
- Dead Code Hunter Scans for unused exports, dead imports, unreachable code, and stale feature flags using knip/vulture/deadcode, auto-removes high-confidence findings after build verification, and flags the rest for manual review. Use when cleaning up a codebase before a refactor or release. Trigger with "find dead code", "remove unused exports". Subagent · jeremylongshore/tons-of-skills-marketplace