ZAM

Building an AI Agent to Strip Dead Weight From Code

Learn how to build a custom AI agent that audits codebases, flags unused logic, and keeps internal software lean without heavy SaaS tools.

I spent years watching engineering teams build complex software platforms that slowly choked under their own weight. Every time a new feature shipped, three abandoned experiments stayed behind in the repository. Unused API endpoints, dead utility functions, deprecated database helper classes, and orphan configuration files sat quietly in the dark, slowing down test pipelines and confusing every developer who joined the company.

When you build software around how a business actually operates instead of buying generic SaaS platforms, maintaining codebase leaness is essential. Proprietary systems need to stay clean and readable. Renting monolithic SaaS software tricks people into thinking bloat is inevitable, but when you own your tools, every useless line of code is an operational tax you pay in slow builds, unexpected bugs, and wasted compute.

To fix this across internal platforms, I stopped relying on manual code reviews that developers continually push to next sprint. Instead, I built a specialized AI agent designed specifically to audit codebases, trace execution paths, and identify dead weight. Here is how I designed that agent, how it operates inside a live repository, and how you can run one yourself.

Why Standard Linters Miss Deep Structural Dead Weight

Standard linters and static analysis tools are excellent at catching localized hygiene issues. They spot unreferenced variables inside a scope, missing imports, or basic syntax flaws within a single file. They are designed for localized safety, not architectural awareness.

Where traditional linters fail completely is structural abandoned code that spans across multiple modules or service boundaries. A linter will never tell you that an entire endpoint handler was rendered useless eight months ago when a business process changed. It sees a syntactically correct controller calling a valid service function connected to a valid query builder. As far as the static engine is concerned, the code is healthy because it compiles.

Human reviewers miss these ghost towns for different reasons. During pull request reviews, engineers focus heavily on new logic being added, rarely inspecting whether existing adjacent modules became obsolete as a result. Over time, these orphaned execution paths accumulate until a significant fraction of your repository exists merely to support features nobody calls.

An AI agent bridges this gap because it combines structural AST traversal with semantic comprehension. It traces call graphs from entry points down to database persistence layers, reads recent commit patterns, and evaluates whether a component serves a real path in production.

Designing the Code Review Agent Architecture

Building an effective code-auditing agent requires avoiding the mistake of dumping entire repositories into a raw context window. Repositories are too expansive, and language models lose precision when inundated with thousands of lines of irrelevant files. An operational agent requires structured tool access and incremental graph exploration.

I designed our audit agent around three main functional layers: an Abstract Syntax Tree parser, a deterministic search toolsuite, and an LLM reasoning engine. The parser extracts symbol definitions, export maps, and import bindings, providing a lightweight index of the codebase without burning context tokens on implementation details upfront.

The execution workflow follows a systematic pattern:

  • Map all live entry points including HTTP routes, background queue consumers, CLI commands, and scheduled cron jobs.
  • Traverse the module dependency tree downward from those entry points to construct a reachable symbol graph.
  • Cross-reference the complete symbol index against the reachable graph to isolate unreachable files and uncalled exports.
  • Dispatch target inspection tools to verify whether suspect files are dynamically referenced or genuinely dead.

In our internal operating stack, where we deploy 25+ AI agents to manage core operational tasks, narrow tool scope is mandatory. The dead weight agent does not attempt to edit files during the initial audit phase; its sole objective is mapping dependencies and verifying non-usage.

System Prompts and Tool Constraints

The main operational risk of an automated code auditor is flagging dynamic references as dead weight. Modern frameworks frequently use string-based resolution, dependency injection containers, or meta-programming that bypass static imports. To keep the agent accurate, you must enforce a strict burden of proof through system rules and required tool usage.

The agent operates under system instructions that forbid flagging code based on assumptions alone. Before declaring any class, function, or file unused, the agent must execute direct grep and AST searches across the codebase. If string matches exist in configuration files, environment definitions, or ORM mappings, the item is classified as uncertain and placed in a human-review queue rather than an auto-prune pipeline.

We grant the agent a concise set of read-only execution tools:

  • search_symbol: Runs precise string and regex matching across the target directory structure.
  • parse_ast: Returns export listings and internal declaration trees for specific source files.
  • check_git_history: Fetches commit recency, author context, and PR reference tags for candidate paths.

Integrating Git commit history provides critical context. If a module has no callers in the main call graph and has not been touched in two years, its probability of being dead weight is extremely high. Conversely, if a file was modified last week, the agent investigates whether it belongs to an unmerged feature branch or active refactor before making a recommendation.

Executing Audits and the Verification Pipeline

When running the agent against an active repository, it processes modules incrementally rather than attempting to analyze the entire application in a single pass. It moves directory by directory, evaluating utility libraries, database access layers, and API handlers against the master route map.

The output of an audit run is structured into clear risk levels:

  • Tier 1 (Zero references): Unreachable files with zero static imports, zero string matches, and no active entry point association.
  • Tier 2 (Uncalled internal exports): Helper functions and utility methods declared inside active files that are never called internally or externally.
  • Tier 3 (Orphan dependencies): Package dependencies listed in configuration files that correspond to removed modules.

Never give an AI agent autonomous permission to run deletion commits directly on your master branch. In our workflow, the agent operates in an isolated environment. Once an audit completes, the agent checks out a fresh branch, removes verified Tier 1 dead weight, updates package manifest files, and submits a draft pull request.

The true safety net is the automated integration testing suite. When the agent opens a pull request, the CI/CD pipeline triggers full test suites, build checks, and type-checking scripts. If a test fails, the agent reads the error stack trace, identifies which removed file caused the breakage, restores it, and logs the dynamic dependency pattern for future runs.

Eliminating Software Drag for Long-Term Ownership

Unnecessary code is not just cosmetic clutter; it is technical overhead that drags down operational momentum. Every extra file increases pipeline execution times, expands container image sizes, and increases cognitive overhead when refactoring existing workflows.

When you own custom software built around how your business operates, maintaining a lean codebase ensures your systems remain adaptable. Off-the-shelf software vendors constantly add features to appeal to new buyer segments, leaving every client with a bloated tool full of unused features. When you build and own your operating platform, you have the freedom to keep it lightweight.

Running custom auditing agents allows operating teams to maintain pristine codebases with $0 ongoing cost in commercial code-scanning subscriptions. You do not need expensive static analysis platforms or seats on external SaaS platforms when a focused, internal AI agent can perform depth audits natively inside your standard CI/CD workflow.

This operational setup embodies a fundamental truth: software built specifically for how a team operates stays efficient because you only maintain what is actively doing work. Unused logic is purged as soon as it drops out of service, keeping maintenance overhead near zero.

Point your agent at entry points, give it strict tool-based verification rules, route its output through pull requests, and let your integration test suite confirm the results. Owning simple, clean internal tools will always beat navigating bloated software you pay for every month.