This prompt is designed for platform and DevSecOps teams who need to convert natural language descriptions of forbidden code patterns into structured, machine-readable rule definitions. The primary job-to-be-done is bridging the gap between team conventions and automated enforcement. Use it when your team has coding standards that static analysis tools do not cover out of the box, such as internal library usage rules, naming conventions for specific contexts, or architectural layering violations. The ideal user is a senior engineer or architect who can precisely describe the anti-pattern, provide positive and negative examples, and define the severity of a violation. This prompt is not for generating generic linting rules that are already available in tools like ESLint or Pylint; it is for encoding tribal knowledge that currently lives in code review checklists and onboarding documents.
Prompt
Custom Anti-Pattern Rule Definition Prompt

When to Use This Prompt
Understand the job-to-be-done, ideal user, required context, and when not to use this prompt for custom anti-pattern rule definition.
Before using this prompt, you must have a clear, unambiguous description of the forbidden pattern and at least two concrete code examples—one that should trigger the rule and one that should not. The prompt expects these as inputs to ground the model's generation in your specific context. The output is a JSON rule definition designed to be consumed by an automated code review harness, not a human auditor. This means the rule must include fields for a unique ID, a human-readable description, a severity level, and a query or pattern-matching expression that can be executed against an AST or source text. The harness is responsible for validating the generated rule against your provided examples before deployment, ensuring the rule fires on true positives and remains silent on true negatives.
Do not use this prompt for safety-critical or security enforcement without a human-in-the-loop review step. While the model can generate a syntactically correct rule, it may misinterpret nuanced intent or produce a rule that is too broad or too narrow. The generated rule is a candidate, not a final artifact. Your workflow must include a validation harness that tests the rule against a curated set of positive and negative examples and surfaces any mismatches for human review. This prompt belongs in a pipeline where a human expert describes the pattern, the model generates a candidate rule, and a validation harness gates the rule before it reaches production. If your team lacks the infrastructure to run these automated checks, start by building that harness before relying on this prompt.
Use Case Fit
This prompt encodes team-specific conventions into machine-readable rules. It works best when conventions are explicit and testable. It fails when rules are subjective or require deep business context.
Good Fit: Codifying Explicit Team Conventions
Use when: Your team has written style guides, naming conventions, or forbidden patterns that can be described in natural language. Guardrail: Provide at least three positive and three negative code examples to calibrate the rule definition before deployment.
Bad Fit: Subjective Code Quality Judgments
Avoid when: The rule requires aesthetic judgment, such as 'code should be elegant' or 'functions should feel right.' Guardrail: If you cannot write a clear pass/fail test for the rule, it is not ready for machine-readable encoding. Use human code review instead.
Required Input: Positive and Negative Examples
Risk: Without calibrated examples, the generated rule will be too broad or too narrow. Guardrail: The harness must validate the generated rule against a held-out set of positive examples that should pass and negative examples that should trigger the rule before accepting the definition.
Operational Risk: Rule Drift Over Time
Risk: Team conventions evolve, but the encoded rule stays frozen, creating false positives or missed violations. Guardrail: Schedule periodic re-validation of each rule against recent codebase samples. Flag rules older than 90 days for review.
Operational Risk: Overly Aggressive Matching
Risk: The generated rule matches legitimate code patterns, flooding the team with false positives and eroding trust. Guardrail: Require a suppression mechanism with documented justification. Track false-positive rates per rule and disable rules exceeding a 20% false-positive threshold.
Bad Fit: Context-Dependent Conventions
Avoid when: The forbidden pattern depends on runtime behavior, external service contracts, or business logic that is not visible in static code. Guardrail: If the rule requires understanding of live system state, pair it with runtime analysis tools rather than relying on static pattern matching alone.
Copy-Ready Prompt Template
A ready-to-adapt prompt that converts natural language anti-pattern descriptions into machine-readable rule definitions for automated codebase scanning.
This prompt template transforms a plain-English description of a forbidden coding pattern into a structured rule definition that an automated checker can execute. The template is designed for platform teams who need to encode team-specific conventions—such as 'never use raw SQL string concatenation' or 'avoid importing from deprecated internal packages'—into a format that can be validated, versioned, and deployed into CI pipelines. Replace every square-bracket placeholder with your specific context before running the prompt. The output is a JSON rule object that includes detection logic, severity, remediation guidance, and test cases.
textYou are a codebase rule definition generator. Your job is to convert a natural language description of a forbidden coding pattern into a precise, machine-readable rule definition. ## INPUT Rule Name: [RULE_NAME] Natural Language Description: [RULE_DESCRIPTION] Target Language(s): [LANGUAGE_LIST] Severity Level: [SEVERITY] // Must be one of: CRITICAL, HIGH, MEDIUM, LOW, INFO Team Context: [TEAM_CONTEXT] // Optional: coding standards, framework conventions, or architecture decisions that inform the rule ## OUTPUT SCHEMA Return a single JSON object with these fields: { "rule_id": "string, kebab-case unique identifier derived from rule name", "name": "string, human-readable rule name", "description": "string, one-paragraph explanation of what the rule detects and why it matters", "severity": "string, one of CRITICAL|HIGH|MEDIUM|LOW|INFO", "detection_patterns": [ { "pattern_type": "string, one of: ast_pattern|regex|import_check|call_graph|naming_convention|structural", "pattern": "string, the specific detection expression", "match_context": "string, where to apply the pattern: file|function|class|module|import|call_site|assignment", "exclusion_conditions": ["string, conditions where this pattern should NOT flag"] } ], "false_positive_risks": ["string, scenarios likely to produce false positives"], "remediation": { "summary": "string, one-sentence fix guidance", "preferred_alternative": "string, what to use instead", "code_example_before": "string, minimal code snippet showing the violation", "code_example_after": "string, minimal code snippet showing the fix" }, "positive_test_cases": [ { "description": "string, what this test case verifies", "code_snippet": "string, code that SHOULD trigger the rule", "expected_result": true } ], "negative_test_cases": [ { "description": "string, what this test case verifies", "code_snippet": "string, code that should NOT trigger the rule", "expected_result": false } ], "suppression_mechanism": "string, how developers can suppress this rule when intentional (e.g., comment annotation, config key)", "confidence": "string, one of: HIGH|MEDIUM|LOW indicating how reliably this pattern can be detected automatically" } ## CONSTRAINTS - Detection patterns must be specific enough to minimize false positives while catching real violations. - Every rule must include at least two positive test cases and two negative test cases. - Remediation examples must be syntactically valid for the target language. - If a pattern cannot be detected with high confidence through static analysis alone, set confidence to LOW or MEDIUM and note what additional evidence (runtime profiling, human review) would be needed. - Do not invent language features or APIs that don't exist in the target language. - If the natural language description is ambiguous, ask clarifying questions instead of guessing. ## EXAMPLES [EXAMPLES] // Optional: insert 1-2 example rule definitions that demonstrate your team's expected format and rigor ## RISK LEVEL [RISK_LEVEL] // Set to HIGH if this rule will block merges or deployments; MEDIUM if it generates warnings; LOW if informational only
After pasting this template, replace each placeholder with concrete values. For [RULE_DESCRIPTION], write a precise, unambiguous description that includes both what the pattern looks like and why it is forbidden. For [EXAMPLES], provide one or two existing rule definitions that match your team's preferred format and level of detail—this anchors the model's output style. For [RISK_LEVEL], be explicit about whether this rule will block CI pipelines or merely generate warnings, as this affects how aggressively the model should tune detection patterns. Once the prompt returns a rule definition, validate it against your positive and negative test cases before deploying it to any automated checker. If the generated rule fails any test case, feed the failure back into the prompt as a correction request rather than manually editing the JSON.
Prompt Variables
Required inputs for the Custom Anti-Pattern Rule Definition Prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check input quality before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RULE_NAME] | Unique identifier for the anti-pattern rule being defined | no-bare-exception-handling | Must match pattern ^[a-z0-9-]+$. Reject if empty or contains spaces. |
[PATTERN_DESCRIPTION] | Natural language description of the forbidden code pattern | Catch blocks that log the error and re-throw without wrapping or adding context | Must be 10-500 characters. Reject if contains only code without explanation. |
[SEVERITY] | Impact level of the anti-pattern when detected | high | Must be one of: critical, high, medium, low, info. Reject on unrecognized values. |
[LANGUAGE] | Target programming language for the rule | typescript | Must match a supported language identifier. Validate against allowed language list before execution. |
[POSITIVE_EXAMPLES] | Code snippets that SHOULD trigger the rule | try { await db.query() } catch (e) { throw e } | Must contain at least 2 examples. Each example must be parseable in [LANGUAGE]. Reject if examples are identical. |
[NEGATIVE_EXAMPLES] | Code snippets that SHOULD NOT trigger the rule | try { await db.query() } catch (e) { throw new ServiceError(e) } | Must contain at least 2 examples. Each example must be parseable in [LANGUAGE]. Reject if any negative example matches a positive example pattern. |
[REMEDIATION_TEMPLATE] | Suggested fix pattern for violations | Wrap the caught error in a domain-specific error type before re-throwing | Must be 20-500 characters. Null allowed if remediation is context-dependent. Reject if template references undefined symbols. |
[RULE_CATEGORY] | Taxonomy bucket for grouping related rules | error-handling | Must match an existing category in the team's rule catalog. Reject on unknown categories. Null allowed for uncategorized rules. |
Implementation Harness Notes
How to wire the custom anti-pattern rule definition prompt into a production validation pipeline.
The Custom Anti-Pattern Rule Definition Prompt converts natural language descriptions of forbidden patterns into machine-readable rule definitions. The primary integration surface is a rule authoring service that accepts human-readable descriptions and returns structured rule objects. The harness must treat the generated rule as untrusted code until it passes validation against a curated test suite of positive and negative examples. This prompt is not a one-shot generator; it is the first step in a validate-repair-approve loop that ensures rules are both syntactically correct and semantically aligned with team intent before they are deployed to automated checkers.
Wire the prompt into a rule ingestion pipeline with these stages: (1) Accept a natural language rule description and optional [CONTEXT] (e.g., language, framework, existing rule set). (2) Call the model with the prompt template, requesting a structured output schema that includes rule_id, pattern, severity, positive_examples, negative_examples, and fix_suggestion. (3) Validate the output against a JSON Schema definition—reject any response missing required fields or containing malformed regex/ AST patterns. (4) Run the generated rule against a golden test set of at least 5 positive examples (should flag) and 5 negative examples (should not flag). If precision or recall falls below a defined threshold (e.g., 0.9), route to a repair prompt that includes the failing cases and asks the model to refine the pattern. (5) After passing automated validation, stage the rule for human review in a diff-view UI that shows the rule definition, test results, and affected code samples. Only after explicit approval should the rule be merged into the active rule set used by CI checks or IDE plugins.
For model choice, prefer a model with strong code reasoning and structured output support (e.g., GPT-4o, Claude 3.5 Sonnet). Set temperature=0 to maximize deterministic rule generation. Implement retry logic with exponential backoff for schema validation failures, but cap repair attempts at 3 iterations before escalating to a human author. Log every generation attempt, validation result, and repair iteration for auditability. Critical failure modes to monitor: rules that are too broad (flagging idiomatic code that follows team conventions), rules that are too narrow (missing obvious violations due to overly specific patterns), and rules that contain regex catastrophic backtracking risks. The harness should include a performance sandbox that tests generated regex patterns against large inputs and rejects any that exceed a timeout threshold. Do not deploy rules directly from model output without this multi-stage validation—the cost of a false positive in an automated checker that blocks CI pipelines is far higher than the cost of a slower, gated approval process.
Expected Output Contract
Fields, types, and validation rules for the machine-readable rule definition generated by the Custom Anti-Pattern Rule Definition Prompt. Use this contract to validate the model's output before deploying the rule to an automated check pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
rule_id | string (slug) | Must match pattern ^[a-z0-9-]+$. Must be unique within the rule catalog. | |
rule_name | string | Must be 5-100 characters. Must not duplicate an existing rule name. | |
severity | enum: CRITICAL, HIGH, MEDIUM, LOW, INFO | Must be one of the five allowed values. CRITICAL reserved for security or data-loss patterns. | |
description | string | Must be 20-500 characters. Must describe the forbidden pattern in plain language. | |
detection_pattern | string (AST query, regex, or structural template) | Must be a valid AST selector, regex, or structural match pattern. Must compile without errors in the target tool (e.g., Semgrep, CodeQL, custom linter). | |
positive_examples | array of strings (code snippets) | Must contain at least 2 code snippets that SHOULD trigger the rule. Each snippet must match the detection_pattern when tested. | |
negative_examples | array of strings (code snippets) | Must contain at least 2 code snippets that SHOULD NOT trigger the rule. Each snippet must NOT match the detection_pattern when tested. | |
remediation_guidance | string | Must be 20-300 characters. Must describe the recommended fix, not just restate the problem. |
Common Failure Modes
When encoding team conventions into machine-readable rules, these failure modes surface first. Each card pairs a specific risk with a concrete guardrail to keep your anti-pattern definitions production-ready.
Overly Broad Pattern Matching
What to watch: Natural language descriptions like 'avoid god objects' or 'no long functions' produce regex or AST rules that match far too many legitimate patterns. A rule meant to catch 500-line functions flags every generated file, minified bundle, and auto-generated client. Guardrail: Always run the generated rule against a curated negative-example corpus before deployment. Require zero false positives on known-safe files before the rule enters CI.
Underspecified Exception Handling
What to watch: Team conventions often include exceptions ('unless it's a DTO' or 'except in the data layer') that don't make it into the prompt. The generated rule enforces the letter of the convention without the spirit, blocking valid code that the team intentionally exempts. Guardrail: Include an explicit exceptions section in the rule definition schema. Require the prompt to ask for known exceptions before generating the rule, and store suppression patterns alongside the rule definition.
Context-Insensitive Severity Assignment
What to watch: A rule that correctly detects a pattern assigns the same severity to a test utility and a production payment handler. Teams drown in critical-severity findings and start ignoring the tool. Guardrail: Embed severity heuristics into the rule definition that consider file location, package role, and change frequency. Test that the generated rule assigns lower severity to test fixtures and higher severity to core business logic.
Stale Rule Drift After Codebase Evolution
What to watch: The rule is generated against today's codebase conventions. Six months later, the team adopts a new pattern that the rule flags. Nobody updates the rule because the original prompt author moved on. Guardrail: Store the natural language rationale and generation date alongside the machine-readable rule. Schedule a quarterly review that re-evaluates the rule against recent codebase samples and surfaces rules older than 90 days without a review.
Silent Failure on Unparseable Code
What to watch: The generated rule assumes valid syntax and silently skips files with parse errors, template-heavy code, or macro-generated blocks. Anti-patterns hide in exactly these files. Guardrail: Require the rule harness to report skipped files with a reason code. Set a maximum skip-rate threshold per run. If more than 5% of target files are skipped, fail the audit and surface the unparseable paths for manual review.
Remediation Guidance That Contradicts Team Standards
What to watch: The prompt generates a rule with auto-fix or remediation suggestions that conflict with the team's preferred libraries, patterns, or architectural direction. A rule suggesting 'extract to a helper function' when the team standard is a specific utility class creates more churn than value. Guardrail: Include a team-standards context block in the prompt that specifies approved libraries, naming conventions, and architectural boundaries. Validate generated remediation text against this block before the rule ships.
Evaluation Rubric
Test the generated anti-pattern rule definition against positive and negative examples before deploying it to a production linting or review harness. Each criterion validates a specific failure mode observed in machine-readable rule generation.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Pattern Match Accuracy | Rule correctly flags all positive examples and clears all negative examples from the test suite | False positives on accepted patterns or false negatives on known violations | Run rule against a golden dataset of 10 positive and 10 negative code samples; require 100% precision and recall |
AST Node Targeting | Rule specifies the correct AST node type and traversal path for the target language | Rule matches wrong constructs, fails to parse valid code, or uses node types from a different language | Validate the [AST_NODE_TYPE] field against the language's grammar specification; test with syntactically valid edge cases |
Severity Assignment Consistency | Generated severity matches the team's severity definitions for [SEVERITY_LEVEL] | Critical bugs marked as warning, or style nits marked as error | Cross-reference [SEVERITY_LEVEL] against the team's severity policy document; spot-check 5 findings |
Message Template Clarity | Finding message includes file, line, pattern name, and actionable remediation guidance | Message is generic, missing location data, or suggests a fix that contradicts team conventions | Parse output for required fields: [FILE_PATH], [LINE_NUMBER], [RULE_ID], [REMEDIATION]; reject if any field is empty or templated |
False Positive Suppression Support | Rule definition includes a suppression comment syntax and a rationale field for waivers | No suppression mechanism defined, or suppression syntax conflicts with existing linter directives | Verify [SUPPRESSION_COMMENT] field is non-empty and does not collide with ESLint, Pylint, or RuboCop suppression syntax for the target language |
Multi-File Pattern Handling | Rule correctly handles patterns that span multiple files or require cross-file analysis | Rule only inspects single files and misses import-based or inheritance-based anti-patterns | Test with a cross-file violation example; confirm the rule's [SCOPE] field is set to 'project' and the traversal logic reaches across file boundaries |
Performance Budget Compliance | Rule completes analysis on a 10k-file repository within the [TIMEOUT_MS] threshold | Rule times out, causes OOM, or exhibits quadratic complexity on large codebases | Benchmark rule against a synthetic repository of 10,000 files; measure wall-clock time and peak memory; fail if exceeding [TIMEOUT_MS] or [MEMORY_LIMIT_MB] |
Remediation Suggestion Safety | Suggested fix does not introduce new anti-patterns, break existing tests, or alter public API contracts | Auto-fix suggestion removes necessary error handling, changes function signatures, or deletes referenced code | Apply suggested remediation to a test file; run the existing test suite; fail if any previously passing tests now fail |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single rule and 3–5 positive/negative examples. Skip the JSON schema enforcement and let the model output a human-readable rule description first. Validate manually before encoding.
codeDefine an anti-pattern rule for: [RULE_NAME] Description: [NATURAL_LANGUAGE_DESCRIPTION] Positive examples (should NOT flag): - [EXAMPLE_1] - [EXAMPLE_2] Negative examples (SHOULD flag): - [EXAMPLE_3] - [EXAMPLE_4] Output the rule as a clear detection pattern.
Watch for
- Rules that are too vague to implement programmatically
- Overlap with existing lint rules or team conventions
- Missing edge-case examples that would cause false positives

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us