Inferensys

Prompt

Reflection Prompt for Code Smell Identification

A practical prompt playbook for using Reflection Prompt for Code Smell Identification in production AI workflows.
Developer doing prompt engineering on laptop, prompt variations visible on screen, casual coding session.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, required context, and operational boundaries for the reflection prompt.

This prompt is designed for a static analysis agent that has already completed a first-pass scan of a codebase and produced a list of detected code smells. The reflection step acts as a second-pass reviewer: it re-examines each finding against the source code, filters false positives, adjusts severity, and prioritizes the remaining issues by impact and remediation effort. The primary job-to-be-done is to reduce noise and increase the actionability of an initial findings list before it reaches a developer's queue. The ideal user is an engineering lead or platform engineer integrating this into a CI/CD pipeline where a single-pass detector is known to produce noisy results, where the cost of a false positive is high (wasted developer time, alert fatigue), or where an auditable rationale for why a finding was escalated or suppressed is required for compliance.

This prompt is not a primary detector. It assumes an initial findings list already exists in a structured format, such as a JSON array of objects with fields for id, file_path, line_range, smell_type, initial_severity, and description. The prompt also requires access to the source code files referenced in the findings. Without this context, the reflection step cannot validate claims against the actual code and will either hallucinate justifications or rubber-stamp the initial results. The output should be a filtered and re-prioritized list with an added reflection_rationale field for each finding, explaining why it was kept, removed, or reclassified. This rationale is the auditable artifact that turns a black-box detection into a reviewable decision.

Do not use this prompt when the initial detector already has high precision and the cost of a false negative (missing a real issue) outweighs the cost of a false positive. In safety-critical systems, a reflection step that suppresses a true finding is a liability. In those cases, route all findings to a human reviewer instead of filtering programmatically. Also avoid this prompt when the codebase is too large to fit in a single context window; you will need to batch findings by module and run the reflection step per batch, with a final deduplication pass. Finally, do not use this prompt as a replacement for a proper static analysis tool—it is a filter and prioritization layer, not a detector.

PRACTICAL GUARDRAILS

Use Case Fit

Where the reflection prompt for code smell identification works and where it introduces risk. Use this to decide whether a second-pass review is the right pattern for your static analysis pipeline.

01

Good Fit: Pre-Commit Review

Use when: a coding agent or linter has flagged smells and you need a second pass to reduce false positives before a developer sees the report. Guardrail: run reflection only on flagged diffs, not the entire codebase, to keep latency under 10 seconds.

02

Bad Fit: Real-Time Keystroke Analysis

Avoid when: latency budget is under 2 seconds or the analysis must run on every keystroke. Reflection doubles inference time and is inappropriate for real-time inline suggestions. Guardrail: gate reflection behind an explicit review trigger or batch job.

03

Required Inputs

What you need: the original code snippet, the initial smell classification with line references, and a severity rubric. Without these, the reflection prompt has no baseline to critique. Guardrail: validate that all three inputs are present before invoking the reflection model.

04

Operational Risk: Confirmation Bias

What to watch: the reflection model may rubber-stamp the initial findings rather than challenge them, especially if the same model produced both passes. Guardrail: use a different model or temperature for the reflection pass, and require at least one smell to be downgraded or removed in every batch.

05

Operational Risk: Over-Correction

What to watch: the reflection pass may suppress true positives to appear thorough, reducing recall. Guardrail: track the rate of smells removed by reflection against a golden set of known true positives, and alert if the removal rate exceeds 30%.

06

Not a Replacement for Test Execution

Avoid when: the smell suggests a behavioral bug or logic error. Reflection cannot verify runtime behavior. Guardrail: route reflection-validated smells that imply incorrect behavior to a test-generation or execution harness before surfacing to the developer.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for performing a structured second-pass review of an initial code smell analysis, filtering false positives and prioritizing findings by impact.

This template is designed to be the core instruction set for a reflection agent. Its job is to take an initial list of detected code smells and critically re-evaluate each one. The model must act as a skeptical senior engineer, not a rubber stamp. It should demand evidence, consider context, and be willing to downgrade or dismiss findings that don't hold up under scrutiny. The output is a refined, prioritized list that a developer can trust and act on immediately.

text
You are a principal software engineer performing a rigorous second-pass review of an automated code smell analysis. Your goal is to filter false positives, confirm true positives with precise reasoning, and prioritize findings by their impact on maintainability, performance, and correctness.

## INPUT
- **Initial Smell Report:** A list of detected code smells, each with a file path, line range, smell type, and a brief auto-generated description.
  ```json
  [INITIAL_SMELL_REPORT]
  • Source Code: The full source code for each file mentioned in the report.
    text
    [SOURCE_CODE]
  • Project Context: A high-level description of the project's domain, performance requirements, and known constraints.
    text
    [PROJECT_CONTEXT]

TASK

For each finding in the Initial Smell Report, perform a critical review and output a final verdict. Follow this process for each smell:

  1. Evidence Check: Re-read the indicated source code. Does the code literally match the pattern described by the smell type? Quote the exact lines that are problematic.
  2. Contextualization: Is this pattern actually a problem given the [PROJECT_CONTEXT]? For example, a performance smell might be acceptable in a low-traffic background job. A long method might be the clearest way to express a simple, linear workflow.
  3. Impact Assessment: If the smell is a true positive, assess its real-world impact. Is it a critical bug waiting to happen, a major maintainability headache, or a minor style violation? Justify your assessment.
  4. Remediation Guidance: For confirmed smells, provide a concise, actionable suggestion for how to fix it. If the fix introduces new risks, mention them.

OUTPUT SCHEMA

Return a single JSON object with a reviews array. Each element must conform to this schema:

json
{
  "reviews": [
    {
      "original_finding_id": "string",
      "verdict": "CONFIRMED" | "FALSE_POSITIVE" | "DOWNGRADED",
      "confidence": "HIGH" | "MEDIUM" | "LOW",
      "reasoning": "A detailed explanation of your review, referencing specific code lines and project context.",
      "impact": "CRITICAL" | "MAJOR" | "MINOR" | "NONE",
      "actionable_suggestion": "A concise fix recommendation, or null if verdict is FALSE_POSITIVE."
    }
  ],
  "summary": {
    "total_reviewed": "integer",
    "confirmed": "integer",
    "false_positives": "integer",
    "downgraded": "integer",
    "top_priority_action": "The single most important fix to make, based on the highest-impact confirmed smell."
  }
}

CONSTRAINTS

  • Do not hallucinate. If the source code does not contain the reported pattern, the verdict must be FALSE_POSITIVE.
  • Be skeptical. The default stance is to doubt the initial report until you see clear evidence.
  • Prioritize ruthlessly. Not all true positives are worth fixing now. Use the impact field to guide developer attention.
  • Actionable suggestions only. Avoid vague advice like "refactor this." Be specific.

To adapt this template, replace the placeholders with data from your application layer. The [INITIAL_SMELL_REPORT] should be a JSON array of objects from your static analysis tool. The [SOURCE_CODE] block must contain the complete file content for every file referenced in the report; this is critical for the evidence check step. The [PROJECT_CONTEXT] is a free-text field that can be populated from a README, a project wiki, or a configuration file. Before deploying, validate that the model's output strictly conforms to the OUTPUT_SCHEMA. A common failure mode is the model adding extra commentary outside the JSON block, so implement a post-processing validation step that parses the JSON and checks for all required fields. If the validation fails, retry the prompt once with a stronger instruction to output only the specified JSON object.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the reflection prompt to reliably perform a second-pass review of code smell detection results.

PlaceholderPurposeExampleValidation Notes

[CODE_SNIPPET]

The source code block under review for code smells

def process(data): result = [] for i in range(len(data)): result.append(data[i] * 2) return result

Required. Must be valid code in the target language. Null or empty strings should cause the prompt to abort with a clear error.

[INITIAL_SMELL_LIST]

The first-pass list of detected code smells to be reviewed

[{"smell": "Use of range(len())", "line": 3, "severity": "medium"}, {"smell": "Mutable default argument risk", "line": 1, "severity": "low"}]

Required. Must be a valid JSON array of objects with smell, line, and severity fields. Schema validation required before prompt assembly.

[LANGUAGE]

The programming language of the code snippet

python

Required. Must be a recognized language identifier. Use an allowlist of supported languages to prevent misclassification.

[PROJECT_CONTEXT]

Optional context about the codebase, coding standards, or domain constraints

Data processing pipeline for financial transactions. Must follow PEP 8 and avoid O(n^2) operations.

Optional. If provided, must be a string under 500 tokens. Null allowed. If present, the reflection should use it to calibrate severity.

[FALSE_POSITIVE_EXAMPLES]

Known patterns that the first pass often misclassifies, used to calibrate the reflection

[{"pattern": "Explicit index loops in numerical code", "reason": "NumPy-style iteration is intentional for performance"}]

Optional. Must be a valid JSON array. Null allowed. If provided, the reflection must explicitly check each initial smell against these patterns.

[SEVERITY_THRESHOLD]

Minimum severity level that requires a remediation recommendation

medium

Optional. Must be one of: low, medium, high, critical. Defaults to medium if null. Smells below this threshold are noted but do not require remediation text.

[MAX_REFLECTION_DEPTH]

Maximum number of reasoning steps the reflection can take before producing output

3

Optional. Must be a positive integer between 1 and 5. Defaults to 3 if null. Prevents infinite self-critique loops in the reflection harness.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the reflection prompt into a static analysis agent with validation, retries, and human review gates.

The reflection prompt is not a standalone script; it is a second-pass filter inside a larger static analysis pipeline. The typical harness runs an initial detection prompt against a codebase or diff, collects the raw findings, and then feeds those findings into the reflection prompt along with the original source code. The reflection output should be treated as the final, curated result set—not an optional add-on. Architecturally, this means the reflection step is a synchronous gate: the pipeline does not emit results to the developer or to the review queue until reflection completes and passes validation.

Wire the reflection prompt as a dedicated step with its own retry budget and output validator. After the initial smell detection produces a JSON array of findings, construct the reflection call with [INITIAL_FINDINGS] set to that array and [SOURCE_CODE] set to the same code context used in the first pass. The model must return a structured JSON object containing reviewed_findings (the filtered and re-ranked list), false_positives_removed (with reasons), and confidence_scores. Validate the output strictly: confirm that every removed finding has a non-empty removal_reason, that confidence_scores are numeric and in range, and that no finding references a line number outside the provided source. If validation fails, retry once with the validation error injected into [PREVIOUS_ERRORS]. If the second attempt also fails, route the raw initial findings to a human review queue with a flag indicating reflection failure—never silently fall back to unfiltered output in high-risk codebases.

Model choice matters here. The reflection step benefits from a model with strong instruction-following and structured output discipline. For most teams, a capable frontier model (e.g., GPT-4o, Claude 3.5 Sonnet) works well, but if you are processing large diffs, watch the context window. Chunk the source code by file or function and run reflection per chunk, then merge results. Log every reflection call with the input findings, output findings, validation status, and any retry attempts. This trace is essential for debugging false negatives (real smells that reflection incorrectly removed) and for tuning the reflection prompt's removal criteria over time. If the pipeline operates on production code with deployment gates, require a human sign-off on any finding above a configurable severity threshold, even after reflection has confirmed it.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured output schema for the reflection prompt. The agent must return a JSON object conforming to these fields. Validation rules are applied post-generation to gate acceptance.

Field or ElementType or FormatRequiredValidation Rule

reflection_timestamp

ISO-8601 string

Must parse as a valid UTC datetime. Must be within 5 minutes of system clock.

original_findings_count

integer

Must be >= 0. Must match the count of items in the original_findings input array.

confirmed_smells

array of objects

Each object must contain an original_id field matching an input finding. No duplicate original_id values allowed.

false_positives

array of objects

Each object must contain original_id and a non-empty dismissal_reason string. original_id must not appear in confirmed_smells.

new_smells_identified

array of objects

Each object must have a unique smell_id generated as 'ref-[UUID]'. Must include file_path, line_range, and severity fields.

severity_overrides

array of objects

Each object must reference an original_id and a new_severity value from the enum ['critical', 'high', 'medium', 'low', 'info']. original_id must exist in input.

remediation_priority_queue

array of strings (IDs)

Must be an ordered list of smell IDs (original and new). Every ID in confirmed_smells and new_smells_identified must appear exactly once.

reflection_confidence

number

Must be a float between 0.0 and 1.0. Represents the model's self-assessed confidence in the reflection. If below 0.7, trigger human review.

PRACTICAL GUARDRAILS

Common Failure Modes

Reflection prompts for code smell identification are powerful but brittle. These are the most common failure modes when deploying a second-pass review agent, along with practical mitigations to keep the system useful in production.

01

Reflection Reinforces the First Mistake

What to watch: The model generates an initial smell list, then the reflection pass simply agrees with itself, adding shallow justifications instead of catching false positives. This turns a two-pass system into an expensive single pass. Guardrail: Require the reflection prompt to produce at least one disagreement or refinement. If the reflection output is identical to the initial pass, flag for human review or force a third pass with a more adversarial prompt.

02

False Positives Survive Both Passes

What to watch: A non-issue is flagged in the first pass, and the reflection prompt lacks the domain context to overturn it. The result is a confident, twice-validated false positive that erodes trust in the tool. Guardrail: Include a specific instruction in the reflection prompt to identify low-severity or uncertain findings and downgrade them. Pair with a static rule engine for trivially decidable patterns so the LLM only reviews ambiguous cases.

03

Remediation Advice Is Generic or Unsafe

What to watch: The reflection pass suggests a fix that introduces a new bug, breaks an implicit contract, or is syntactically invalid for the language version in use. Guardrail: Constrain the output schema to require a safety_check field. Instruct the model to verify that the suggested change does not alter public method signatures, change exception behavior, or break existing tests. Always gate automated application of fixes behind a build and test run.

04

Context Window Truncation Causes Missed Smells

What to watch: Large files or multi-file reviews exceed the context window. The reflection pass only sees a fragment of the initial analysis, leading to inconsistent or incomplete re-evaluation. Guardrail: Chunk the input by logical unit (function, class, module) rather than by token count. Include a summary of cross-cutting concerns in each chunk. Validate that every smell from the initial pass appears in the reflection input context.

05

Severity Inflation Across Reflection Passes

What to watch: A minor code smell is initially flagged as low severity, but the reflection prompt, prompted to be thorough, escalates it to critical without new evidence. This creates alert fatigue and obscures real issues. Guardrail: Add a severity_change_justification field to the output schema. Require explicit, evidence-backed reasoning for any severity increase. Implement a post-processing rule that caps single-pass severity jumps by one level unless a new, concrete risk is cited.

06

Prompt Drift Between Initial and Reflection Passes

What to watch: The initial detection prompt and the reflection prompt use different smell taxonomies, severity scales, or output formats. The reflection pass misinterprets the initial findings, leading to dropped items or misaligned comparisons. Guardrail: Define a single source of truth for the smell taxonomy and output schema. Inject the exact same definitions into both prompts. Validate that the reflection output references the initial finding IDs and does not introduce new, unrequested categories.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the reflection output before integrating it into a CI pipeline or agent workflow. Each criterion targets a specific failure mode of second-pass code smell review.

CriterionPass StandardFailure SignalTest Method

False Positive Reversal

At least 80% of initial findings correctly reclassified as false positives are accompanied by a concrete code reason (e.g., 'this is a guard clause, not a nested conditional').

Reversal justifications are generic (e.g., 'this is fine') or missing entirely.

Parse the [REFLECTION_OUTPUT] JSON. For each item in reversed_findings, check that justification is non-empty and references a specific code element from [CODE_SNIPPET].

Severity Reclassification

All severity changes (e.g., critical to minor) include a clear impact rationale referencing execution context, not just code style.

Severity is downgraded without explanation, or the rationale contradicts the original finding's description.

Compare original_severity and new_severity in the output. Assert that rationale field is present and contains a keyword from the [IMPACT_TAXONOMY] list.

Missed Smell Discovery

Any newly identified smell (not in the initial list) must include a line-number reference and a specific rule ID from [SMELL_CATALOG].

New smells are vague ('this function is too long') or lack a precise location.

Validate that each object in new_findings has non-null line_start and rule_id fields that match the provided [SMELL_CATALOG] schema.

Remediation Actionability

Every confirmed finding includes a remediation block with a code diff suggestion or a specific refactoring pattern name.

Remediation is a generic instruction like 'simplify this' or 'refactor'.

Check that remediation.type is either 'diff' or 'pattern_name'. If 'diff', validate that remediation.before and remediation.after are non-empty strings.

Context Window Adherence

The reflection output does not hallucinate code lines or variable names not present in the provided [CODE_SNIPPET].

The output references a function, variable, or line number outside the bounds of the input.

Tokenize [CODE_SNIPPET] and the output's justification fields. Assert that all quoted identifiers exist in the input token set.

Output Schema Compliance

The output is valid JSON that strictly matches the [OUTPUT_SCHEMA] definition.

The output is missing required fields, contains extra fields, or has incorrect types (e.g., string instead of array).

Run a JSON Schema validator against the raw model response using the provided [OUTPUT_SCHEMA]. The test must pass with zero errors.

Confidence Calibration

A confidence_score between 0.0 and 1.0 is provided for each reclassified or new finding, and scores below 0.7 are flagged for human review.

Confidence scores are uniformly high (e.g., all 0.99) or missing.

Assert that confidence_score exists and is a float. Count items with confidence_score < 0.7. Flag the entire output for human review if more than 50% of items fall below the threshold.

Prioritization Logic

The final prioritized_list is sorted by severity first, then by confidence, with critical/high-confidence items at the top.

The list appears randomly sorted or sorts alphabetically by rule name.

Extract the prioritized_list. Assert that for any two adjacent items, the first has a higher severity rank or equal severity with a higher confidence score.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base reflection prompt with a single model call. Feed the initial smell detection output directly into the reflection step without schema enforcement. Accept free-text critique and a simple ranked list.

Prompt snippet:

code
You previously identified these code smells in [CODE_SNIPPET]:
[INITIAL_FINDINGS]

Review your findings. Which are likely false positives? Re-rank by impact.

Watch for

  • Reflection that agrees with everything without substantive critique
  • Missing severity differentiation in the re-ranked list
  • No mechanism to catch hallucinations in the initial pass
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.