Inferensys

Prompt

Multi-File Dead Code Elimination Plan Prompt

A practical prompt playbook for using Multi-File Dead Code Elimination Plan Prompt in production AI workflows.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Multi-File Dead Code Elimination Plan Prompt.

This prompt is for engineering managers and tech leads who need to reduce maintenance burden by systematically removing dead code across a repository. The job-to-be-done is producing a safe, verifiable elimination plan that identifies unreachable functions, unused exports, dead dependencies, and orphaned configuration—without breaking runtime behavior. The ideal user has access to the codebase, understands its build system and module graph, and can run static analysis tools to validate the plan before any code is deleted. Required context includes the repository structure, a list of entry points (binaries, route handlers, cron jobs, test suites), and any known dynamic access patterns (reflection, dependency injection containers, string-based imports) that static analysis alone would miss.

Do not use this prompt when the codebase relies heavily on runtime metaprogramming that cannot be enumerated—frameworks with convention-over-configuration routing, ORM lazy-loading, or plugin systems that discover modules at startup. In those cases, a dead code elimination plan from static analysis will produce dangerous false positives. Similarly, avoid this prompt for repositories where the build graph is incomplete or where critical entry points are undocumented; the model cannot infer what it cannot see. For high-risk codebases (payments, auth, safety-critical systems), every removal candidate must be verified with runtime coverage data and a human approval gate before deletion. This prompt is a planning tool, not an automated deletion engine.

After generating the plan, validate each removal candidate against your static analysis toolchain (e.g., ts-prune, vulture, dead, knip) and cross-reference with runtime coverage reports if available. Flag any candidate where the model's reasoning cites 'appears unused' rather than a concrete unreachability argument—these are the highest-risk false positives. The next step is to stage removals in dependency order (leaf modules first) with a build-and-test gate between each stage, ensuring no removal breaks downstream consumers. If you need a broader change impact analysis before executing, pair this prompt with the Multi-File Change Impact Analysis Prompt to assess downstream breakage risk across the full dependency graph.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Multi-File Dead Code Elimination Plan Prompt delivers value and where it introduces risk. Use these cards to decide if this prompt fits your current task before wiring it into a pipeline.

01

Good Fit: Static Analysis Augmentation

Use when: You have a mature codebase with static analysis tooling (e.g., ts-prune, vulture, dead) and need an AI layer to interpret raw results, group related dead symbols, and propose a safe removal order across files. Guardrail: Always feed the prompt the raw tool output as ground truth; the AI should plan the cleanup, not discover the dead code from scratch.

02

Bad Fit: Dynamic or Reflection-Heavy Runtimes

Avoid when: The codebase uses heavy runtime reflection, dynamic import() patterns, metaprogramming, or dependency injection containers that resolve symbols at startup. Risk: The prompt will produce false positives by treating reflectively accessed code as dead. Guardrail: Require a runtime coverage profile or dynamic access log as a required input before allowing any removal plan.

03

Required Inputs

Must provide: (1) A static dead-code report from a trusted tool, (2) the repository file tree, (3) a dependency graph or import map, and (4) a list of public API surface files that must not have exports removed. Guardrail: Reject the prompt if any of these four inputs is missing; the plan quality degrades sharply without them.

04

Operational Risk: Silent Build Breakage

Risk: The prompt may propose removing a symbol that is only referenced in a build script, code generation template, or integration test fixture outside the main source tree. Guardrail: Run a full build and test suite on a branch after applying the plan. Never merge a dead-code elimination PR without CI passing on the exact removal diff.

05

Operational Risk: Public API Contract Violation

Risk: Removing an export that appears unused internally but is part of a documented public API breaks downstream consumers silently. Guardrail: Mark all public API entry points explicitly in the prompt input. The plan must treat any removal touching those files as a breaking change requiring deprecation, not deletion.

06

Scale Boundary: Monorepo vs. Single Service

Use when: The scope is a single service or library with a well-defined boundary. Avoid when: The prompt must reason about dead code across dozens of services with independent release cycles. Guardrail: For monorepos, run the prompt per-service with service-level dependency graphs. Do not ask a single prompt to plan removals across service boundaries with different owners.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating a safe, verifiable dead code elimination plan across multiple files.

The following prompt template is designed to be copied directly into your AI coding agent or orchestration harness. It instructs the model to produce a structured removal plan rather than executing deletions immediately. The template uses square-bracket placeholders for all dynamic inputs—replace these with your repository context, analysis results, and safety constraints before sending the prompt to the model.

text
You are a senior software engineer planning dead code elimination across a multi-file codebase. Your task is to produce a safe, verifiable removal plan. Do not suggest or execute any deletions. Output only the plan.

## Repository Context
[REPOSITORY_CONTEXT]

## Dead Code Candidates
These symbols, files, and imports have been flagged as potentially dead by static analysis. Each entry includes the file path, symbol name, and the tool that flagged it:
[DEAD_CODE_CANDIDATES]

## Dynamic Access Patterns
These patterns may reference code through reflection, dynamic imports, string-based lookup, or runtime configuration. Code flagged as dead may still be reachable through these paths:
[DYNAMIC_ACCESS_PATTERNS]

## Build and Test Configuration
[BUILD_AND_TEST_CONFIG]

## Output Schema
Return a JSON object with the following structure:
{
  "plan_version": "1.0",
  "generated_at": "ISO timestamp",
  "safe_removals": [
    {
      "file": "path/to/file",
      "symbol": "function_or_class_name",
      "removal_type": "delete_symbol | delete_file | remove_import | remove_export",
      "evidence": ["list of reasons this is safe to remove"],
      "pre_removal_checks": ["checks to run before deleting"],
      "dependent_files_to_update": ["files that import or reference this symbol"]
    }
  ],
  "false_positives": [
    {
      "file": "path/to/file",
      "symbol": "function_or_class_name",
      "reason_retained": "explanation of why this code is actually reachable",
      "reachable_through": "dynamic import | reflection | config | test-only | external_consumer | other",
      "recommendation": "keep | add_suppression_comment | refactor_to_make_obvious"
    }
  ],
  "uncertain_cases": [
    {
      "file": "path/to/file",
      "symbol": "function_or_class_name",
      "uncertainty": "description of what is unknown",
      "investigation_steps": ["steps a human should take to resolve"],
      "risk_if_removed": "what could break"
    }
  ],
  "removal_ordering": [
    {
      "phase": 1,
      "description": "Remove leaf-node dead code with no dependents",
      "files": ["file_list"]
    }
  ],
  "verification_plan": {
    "per_phase_checks": ["build must succeed", "test suite must pass", "lint must be clean"],
    "rollback_triggers": ["any test failure", "build failure", "runtime error in staging"],
    "recommended_test_focus": ["specific test files or suites to run"]
  }
}

## Constraints
- Never mark a symbol as safe to remove if it appears in [DYNAMIC_ACCESS_PATTERNS] unless you can prove the dynamic path never resolves to it.
- If a symbol is exported from a public API module, treat it as uncertain unless you have evidence of zero external consumers.
- Test files that import a symbol count as reachable code—do not flag them as dead.
- If build configuration references a file (e.g., entry points, script targets), that file and its transitive imports are reachable.
- Prefer marking uncertain cases over false positives when evidence is incomplete.
- Order removals so that leaf nodes (symbols with no dependents) are removed first, then their callers.

To adapt this template, replace each placeholder with concrete data from your repository. [REPOSITORY_CONTEXT] should include the language, framework, module structure, and any conventions that affect reachability analysis. [DEAD_CODE_CANDIDATES] should come from static analysis tools such as ts-prune, vulture, dead, or IDE inspections—include the tool name so the model can weigh false-positive tendencies. [DYNAMIC_ACCESS_PATTERNS] is critical: populate it by searching for eval, getattr, importlib, require, string-based dispatch tables, and plugin systems. If you skip this section, the model will produce a plan with dangerous false negatives. After generating the plan, always run the verification steps before any deletion, and escalate uncertain cases to a human reviewer who understands the runtime behavior of the system.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the Multi-File Dead Code Elimination Plan Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[REPOSITORY_CONTEXT]

File tree, import graph, and symbol references needed to trace reachability

src/ tree with 200+ TypeScript files, tsconfig paths, package.json exports

Parse check: must contain at least one entry-point file and its transitive imports. Null not allowed.

[ENTRY_POINTS]

List of files or symbols that are definitely reachable (CLI entry, server start, exported API)

["src/index.ts", "src/cli.ts", "src/server.ts"]

Schema check: must be a non-empty array of file paths resolvable in [REPOSITORY_CONTEXT]. Each path must exist in the provided file tree.

[EXPORT_MAP]

Public API surface: which symbols are exported and consumed externally

{"src/lib.ts": ["parseConfig", "validateInput"]}

Schema check: must be a JSON object mapping file paths to arrays of exported symbol names. Null allowed if no public API exists.

[DYNAMIC_ACCESS_PATTERNS]

Known reflection, dynamic import, or string-based access patterns that bypass static analysis

["require(variablePath)", "container.get(Symbol.for(name))"]

Parse check: must be an array of strings describing patterns. Empty array allowed. Each entry should include the mechanism and affected files if known.

[IGNORE_RULES]

Files, directories, or symbol patterns to exclude from dead code analysis

["/*.test.ts", "/mocks/", "src/generated/"]

Schema check: must be an array of glob patterns or symbol matchers. Empty array allowed. Each pattern must be a valid glob or regex string.

[CONFIDENCE_THRESHOLD]

Minimum confidence required to classify code as dead (0.0 to 1.0)

0.85

Range check: must be a float between 0.0 and 1.0. Lower values increase false-positive risk. Default 0.85 if not specified.

[OUTPUT_SCHEMA]

Expected structure for the elimination plan output

{"files": [{"path": "string", "dead_symbols": ["string"], "confidence": "float", "rationale": "string"}]}

Schema check: must be a valid JSON Schema or TypeScript interface definition. Parseable as JSON. Required field.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the dead code elimination plan prompt into a reliable application workflow with validation, tool integration, and human review gates.

The dead code elimination prompt is not a one-shot code deletion tool. It is a planning prompt that produces a structured removal plan before any code is touched. Wire it into a workflow where the plan is generated, validated against static analysis ground truth, reviewed by a human, and only then executed. The prompt should receive repository context from a codebase exploration step—file trees, symbol indexes, import graphs, and test coverage reports—rather than raw file contents dumped into the context window. This separation keeps the prompt focused on planning and reduces the risk of hallucinated references when the model cannot see the full dependency graph.

Input assembly. Before calling the prompt, run a static analysis pass to collect: (a) all exported symbols and their importers across the target file set, (b) test file-to-source mappings so the prompt can flag dead code that still has test coverage, (c) any dynamic access patterns detected via grepping for getattr, eval, __import__, reflection APIs, or string-based dispatch tables relevant to the language ecosystem. Package these into the [CODEBASE_CONTEXT] placeholder as structured JSON or YAML, not raw source. For the [TARGET_FILES] placeholder, provide a list of file paths with brief descriptions of each file's role. The [EXCLUSION_PATTERNS] placeholder should capture files or symbols known to be reachable through external entry points, config-driven loading, or plugin systems that static analysis cannot see.

Validation and retry loop. After the model returns a removal plan, validate every claimed dead symbol against the static analysis ground truth. Flag any symbol the model marks as dead but that appears in an import statement outside the target set. Flag any symbol marked as safe to remove that matches a dynamic access pattern from the pre-collected grep results. If validation failures exceed a configurable threshold (start with zero tolerance for false positives), feed the failures back into a retry prompt that includes the specific symbols, their actual references, and an instruction to re-evaluate. Do not proceed to human review until the plan passes automated validation. Log every validation failure for prompt improvement over time.

Human review gate. Even after automated validation passes, the removal plan must go to a human reviewer. The review interface should display: each symbol proposed for removal, its file location, the model's stated reasoning, the static analysis confirmation, and a checkbox to approve or reject each item individually. Highlight any symbols where the model's confidence was marked low or where dynamic access patterns exist nearby. The reviewer should be able to approve the entire plan, reject specific items, or request a re-plan with additional exclusions. Only after human approval should the plan be converted into actual file edits or deletion commands.

Model choice and tool integration. Use a model with strong code reasoning capabilities and a large context window—the prompt needs to hold symbol tables, import graphs, and file descriptions for potentially dozens of files. If the repository is large, split the analysis into batches by module or package and run the prompt per batch, then merge the plans. For tool integration, the validated and approved plan can be passed to a file-editing agent that applies removals one file at a time, runs the test suite after each batch, and rolls back if tests fail. Never wire the prompt output directly to automated deletion without the validation and review gates described above. The cost of a false positive—deleting code that is actually reachable at runtime—is a production incident, not a linting warning.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the required fields, types, and validation rules for the Multi-File Dead Code Elimination Plan. Use this contract to parse and validate the model's output before integrating it into a code review or automated refactoring pipeline.

Field or ElementType or FormatRequiredValidation Rule

removal_candidates

Array of Objects

Must be a non-empty array. Each object must conform to the removal_candidate schema defined below.

removal_candidates[].file_path

String (relative path)

Must be a valid relative file path within the repository. Regex check: ^[^/].*[.][a-z]+$

removal_candidates[].symbol_name

String

Must be a non-empty string matching a valid code identifier. Regex check: ^[a-zA-Z_][a-zA-Z0-9_]*$

removal_candidates[].symbol_type

Enum: [function, class, variable, type, import, export]

Must be one of the specified enum values. Case-sensitive check.

removal_candidates[].dead_reason

String

Must be a non-empty string explaining why the symbol is unreachable. Minimum length: 10 characters.

removal_candidates[].confidence

Enum: [high, medium, low]

Must be one of the specified enum values. If 'low', a human_review_required flag must be true.

removal_candidates[].dynamic_access_risk

Array of Strings

If present, each string must describe a potential dynamic access path (e.g., 'eval', 'getattr'). Null allowed.

removal_candidates[].human_review_required

Boolean

Must be true if confidence is 'low' or if dynamic_access_risk is not empty. Otherwise, can be false.

PRACTICAL GUARDRAILS

Common Failure Modes

Dead code elimination plans are prone to false positives from dynamic access patterns and false negatives from incomplete dependency graph traversal. These failure modes help you catch the most dangerous mistakes before a removal plan reaches production.

01

False Positives from Reflection and Dynamic Access

What to watch: The model flags code as dead because no static import or direct call exists, but the code is accessed via reflection, getattr, string-based dispatch, or dynamic class loading. Removing it breaks runtime behavior. Guardrail: Require the plan to explicitly list all dynamic access patterns found in the codebase (decorators, metaprogramming, plugin systems, ORM hooks) and mark any flagged code that intersects with those patterns as requiring manual review before removal.

02

Missed Transitive Dead Code

What to watch: The model identifies a dead export but fails to trace its downstream dependents—types, constants, or utilities that become dead only after the primary removal. The plan underreports the true removal scope. Guardrail: Require the plan to perform a second-pass transitive analysis: for every file flagged for removal, re-scan for symbols that become unreachable after the primary dead code is removed. Validate with a static analysis tool like ts-prune or vulture as a cross-check.

03

Test-Only Code Misclassified as Dead

What to watch: Functions, exports, or test fixtures used exclusively by test files are flagged as dead because the model treats test imports as non-production usage. Removing them breaks the test suite. Guardrail: Instruct the model to treat test files as valid consumers. The plan must include a 'test-only usage' category for code that is dead in production but alive in tests, with explicit confirmation before removal.

04

Public API Surface Removal Without Consumer Check

What to watch: The model flags an exported symbol as unused within the repository but fails to account for external consumers importing the package. Removing a public API export breaks downstream dependents. Guardrail: Require the plan to distinguish between internal-only exports and public API surface. For any public export flagged as dead, the plan must include a 'consumer impact unknown' warning and recommend a deprecation cycle rather than immediate removal.

05

Configuration-Driven Code Paths Missed

What to watch: Code behind feature flags, environment-specific config, or build-time conditionals appears unreachable because the model analyzes only the default code path. The plan removes code that is active in production under a different configuration. Guardrail: Require the plan to enumerate all configuration dimensions (feature flags, env vars, build profiles) and confirm that dead code analysis covers every active configuration combination, not just the default path.

06

Removal Ordering Breaks Intermediate Builds

What to watch: The plan proposes removing files in an order that leaves the codebase in a non-compiling state between steps. A later removal depends on an earlier one, but the intermediate state has broken imports. Guardrail: Require the plan to include a dependency-ordered removal sequence with a 'build-green' check after each step. Validate by simulating the removal order in a CI sandbox before committing any changes.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing the quality and safety of a multi-file dead code elimination plan before shipping it to a coding agent or review pipeline.

CriterionPass StandardFailure SignalTest Method

False Positive Rate

Zero false positives: no reachable code flagged as dead

Plan includes a symbol reachable via a static call path or a documented dynamic access pattern

Run a reachability analysis tool (e.g., ts-prune, deadcode, vulture) on the same codebase and diff the flagged symbols against the plan

Reflection and Dynamic Access Coverage

All dynamic access patterns (e.g., getattr, eval, dependency injection containers, route decorators) are explicitly listed and excluded from removal

Plan proposes removal of a symbol that is only referenced inside a string literal, config file, or reflection-based framework wiring

Grep the codebase for the removed symbol name appearing in strings, YAML, JSON, or decorator arguments; flag any match not addressed in the plan

Export Boundary Verification

No exported public API symbol is removed without a deprecation notice and consumer impact note

Plan removes an exported function, class, or type without documenting downstream consumers or providing a deprecation path

Parse the module's public API (e.g., all, package init.py, index.ts barrel files) and cross-reference each removal against the plan's consumer impact section

Build and Test Integrity

The removal plan includes a verification step confirming the project builds and all existing tests pass after each file or batch of removals

Plan lacks per-step build verification or assumes all removals can be applied in one batch without intermediate checks

Simulate the plan's removal order in a sandbox branch; confirm the build succeeds and the test suite passes at each step defined in the plan

Dependency Cascade Correctness

If a removed symbol is the sole consumer of another symbol, that dependent dead code is also included in the removal plan

Plan removes a top-level dead function but leaves its now-unused helper functions, imports, or type aliases untouched

After applying the plan, run the same dead code detection tool again; zero newly-detectable dead symbols should remain that were direct dependencies of removed code

Import and Side-Effect Safety

No file removal or import deletion breaks side-effect-dependent code (e.g., global registrations, monkey-patches, plugin loading)

Plan removes an import or file whose sole purpose is a side effect at load time, causing a runtime behavioral change

Audit each removed import for module-level side effects; run the application's smoke tests or integration tests with the removals applied to detect missing registrations

Plan Completeness and Actionability

Every removal entry includes the file path, symbol name, line range, removal rationale, and a verification command

Plan entries are vague (e.g., 'remove unused code in utils.py') without precise location or verification steps

Parse the plan output against the expected schema; reject any entry missing file path, symbol identifier, or a concrete verification command

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single language or framework. Remove strict output schema requirements and let the model produce a free-text plan. Focus on correctness of dead code identification, not format compliance.

Use a smaller scope: limit to one directory or module. Replace [LANGUAGE] and [FRAMEWORK] with concrete values. Skip the verification checklist section initially.

Prompt modification

  • Remove the [OUTPUT_SCHEMA] constraint and replace with: "Output a plain-text plan with sections for Unreachable Code, Unused Exports, Dead Dependencies, and Recommended Removals."
  • Add: "If uncertain whether code is reachable via reflection or dynamic access, mark it as [NEEDS_MANUAL_REVIEW] and explain why."

Watch for

  • False positives from dynamic dispatch, metaprogramming, or reflection-based access patterns
  • Overly aggressive removal suggestions that don't account for plugin systems or configuration-driven loading
  • Missing distinction between dead code and intentionally dormant code (feature flags, seasonal logic)
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.