Inferensys

Prompt

Circular Dependency Detection Prompt Template

A practical prompt playbook for using the Circular Dependency Detection Prompt Template in production AI workflows to identify, rank, and classify import cycles in codebases.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Understand the ideal context, required inputs, and limitations for using the circular dependency detection prompt in architecture and platform engineering workflows.

This prompt is designed for platform engineers and architects who need to detect circular dependencies across a codebase before they cause build failures, deployment deadlocks, or refactoring paralysis. Use it when you have access to a dependency graph, import manifest, or static analysis output and need a ranked, severity-classified list of cycles. The prompt assumes the input is a structured representation of file-level or module-level dependencies. It is not a replacement for static analysis tools; it is a reasoning layer that classifies, ranks, and explains cycles so teams can prioritize remediation. This prompt belongs in architecture review workflows, CI/CD quality gates, and refactoring planning sessions where human judgment is needed to interpret tool output.

The ideal input is a machine-generated dependency graph—such as the output of madge, dependency-cruiser, or a language-specific import analyzer—formatted as a list of edges or an adjacency map. The prompt works best when the input includes file paths, module names, and dependency direction. It can handle graphs with hundreds of nodes, but for very large codebases, you should partition the input by subsystem or bounded context to avoid token limits and reasoning degradation. Do not use this prompt on raw source code without first running static analysis; the model is not a parser and will hallucinate dependencies when asked to read arbitrary files. Also avoid using it for runtime or dynamic dependency detection, where reflection, service discovery, or lazy loading creates edges invisible to static analysis.

The prompt classifies each cycle by severity—blocking, high, medium, or low—based on cycle length, the number of downstream dependents, and whether the cycle crosses architectural boundaries. It produces a ranked list with file paths, cycle length, and a brief explanation of why the cycle is problematic. Use this output to prioritize remediation: short cycles in core modules are usually the most urgent. Before acting on the results, validate the top findings against your build system and runtime behavior. False positives can arise from test-only imports, type-only references, or dynamic imports that static tools misrepresent. When integrating this prompt into a CI/CD pipeline, pair it with a threshold rule that fails the build only when new blocking cycles are introduced, not when pre-existing debt is detected.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Use these cards to decide if a circular dependency detection prompt is the right tool before wiring it into a CI pipeline or architecture review workflow.

01

Good Fit: Static Import Graph Analysis

Use when: you have a parsed dependency graph (AST-derived imports, module resolution output, or build-tool dependency tree) and need a ranked list of cycles with file paths, cycle length, and severity classification. The prompt excels at pattern recognition across structured graph data. Guardrail: always ground the prompt input in tool-generated dependency data, not human recall of the codebase.

02

Bad Fit: Runtime or Dynamic Dependency Detection

Avoid when: dependencies are resolved at runtime through reflection, service locators, dynamic imports, or plugin systems. The prompt cannot infer edges that only exist during execution. Guardrail: pair this prompt with runtime tracing or dynamic analysis tools before claiming completeness. Flag any cycle report with a confidence caveat when dynamic resolution is present.

03

Required Input: Structured Dependency Graph

What to watch: the prompt degrades sharply when given raw file listings, unstructured directory trees, or prose descriptions of architecture. It needs explicit source -> target edge records. Guardrail: preprocess repository data into a standard edge-list format (CSV or JSON) with file paths, module identifiers, and relationship types before calling the prompt. Validate edge count against expected project size.

04

Operational Risk: False Positives from Test-Only Cycles

What to watch: test files importing production code that imports test utilities can create cycles that are harmless in production but flagged as severe. Guardrail: include a relationship_type field in the input graph (e.g., production, test, development) and instruct the prompt to classify cycles by blast radius. Suppress or downgrade test-only cycles in CI gates.

05

Operational Risk: Cycle Severity Inflation

What to watch: a 2-node cycle in leaf utilities may be flagged with the same severity as a 10-node cycle across core domain modules. Guardrail: require the prompt output to include a severity rubric based on cycle length, module criticality, and fan-in. Calibrate thresholds with the team before blocking builds. Start with warnings, not hard failures.

06

Process Fit: Architecture Review, Not Build Gate

What to watch: teams may be tempted to block CI on zero cycles immediately. Legacy codebases often have known, accepted cycles. Guardrail: use the prompt's output as an architecture review artifact first. Track cycle count over time as a metric. Only promote to a blocking gate after establishing a baseline and fixing existing accepted cycles.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for detecting, ranking, and classifying circular dependency chains from a dependency graph input.

The prompt below is designed to accept a structured dependency graph and return a ranked, classified report of all circular dependency chains. It is built for platform engineers and architects who need to programmatically identify and prioritize cycles before they cause build failures, deployment deadlocks, or refactoring paralysis. The template uses square-bracket placeholders so you can wire it directly into an application harness without manual editing.

text
You are a static analysis engine specialized in dependency graph evaluation. Your task is to analyze the provided dependency graph and detect, rank, and classify all circular dependency chains.

## INPUT
[DEPENDENCY_GRAPH]

## CONSTRAINTS
- Exclude cycles that exist only in test files or test directories unless [INCLUDE_TEST_CYCLES] is set to true.
- Exclude cycles that involve only dynamic imports (e.g., `import()`, `require()` inside functions) unless [INCLUDE_DYNAMIC_IMPORTS] is set to true.
- A cycle must contain at least [MIN_CYCLE_LENGTH] nodes to be included in the report.
- Ignore self-referencing files (a file importing itself) unless [INCLUDE_SELF_REFERENCES] is set to true.
- If [EXCLUDE_PATTERNS] is provided, ignore any node whose path matches one of the glob patterns.

## OUTPUT_SCHEMA
Return a valid JSON object with this exact structure:
{
  "summary": {
    "total_cycles_found": <integer>,
    "max_cycle_length": <integer>,
    "cycles_by_severity": {
      "critical": <integer>,
      "high": <integer>,
      "medium": <integer>,
      "low": <integer>
    }
  },
  "cycles": [
    {
      "cycle_id": "<string, e.g., 'CYCLE-001'>",
      "cycle_length": <integer>,
      "severity": "<critical|high|medium|low>",
      "severity_rationale": "<string explaining why this severity was assigned>",
      "nodes": [
        {
          "file_path": "<string>",
          "import_statement": "<string, the specific import that creates the cycle>",
          "import_type": "<static|dynamic|re-export>"
        }
      ],
      "remediation": {
        "suggested_action": "<extract_interface|invert_dependency|merge_modules|break_with_events|re-evaluate_boundary>",
        "description": "<string with concrete refactoring guidance>",
        "estimated_effort": "<low|medium|high|extreme>",
        "breaking_change_risk": "<low|medium|high>"
      }
    }
  ],
  "false_positives_excluded": [
    {
      "cycle_description": "<string>",
      "exclusion_reason": "<dynamic_import|test_only|below_min_length|excluded_pattern|self_reference>",
      "nodes_involved": ["<string>"]
    }
  ]
}

## SEVERITY CLASSIFICATION RULES
- **critical**: Cycle length >= 5 OR cycle spans >= 3 top-level directories OR cycle includes a module that is a public API surface.
- **high**: Cycle length 3-4 OR cycle spans 2 top-level directories OR cycle includes a module with >= 10 dependents.
- **medium**: Cycle length 2-3 within a single top-level directory, not involving public API surfaces.
- **low**: Cycle length 2 within the same subdirectory, involving only internal utility modules.

## REMEDIATION GUIDANCE
For each cycle, recommend the most appropriate structural fix:
- **extract_interface**: Create a shared interface or abstract class that both modules depend on, breaking the direct cycle.
- **invert_dependency**: Reverse the direction of one dependency so the more stable module depends on the less stable one.
- **merge_modules**: If the cycle indicates false modularity, merge the modules into a single cohesive unit.
- **break_with_events**: Replace a direct call with an event or message to decouple the modules at runtime.
- **re-evaluate_boundary**: The cycle may indicate that the module boundary itself is wrong and needs redesign.

## INSTRUCTIONS
1. Parse the dependency graph to identify all strongly connected components.
2. For each SCC with >= [MIN_CYCLE_LENGTH] nodes, extract the exact cycle paths.
3. Apply the exclusion filters from [CONSTRAINTS].
4. Classify each remaining cycle by severity.
5. Generate remediation suggestions for each cycle.
6. List all excluded cycles in `false_positives_excluded` with clear reasons.
7. Return ONLY the JSON object. No markdown fences, no commentary.

Adaptation notes: Replace [DEPENDENCY_GRAPH] with a structured representation of your dependency graph—this can be a JSON adjacency list, a list of {from, to, import_type} edges, or a serialized graph object from your build tool. The [EXCLUDE_PATTERNS] placeholder accepts glob patterns like "**/*.test.*" or "**/__mocks__/**". Set [INCLUDE_TEST_CYCLES], [INCLUDE_DYNAMIC_IMPORTS], and [INCLUDE_SELF_REFERENCES] to boolean strings ("true" or "false") based on your analysis scope. [MIN_CYCLE_LENGTH] should be an integer, typically 2 or 3 depending on whether you consider direct mutual imports as cycles worth reporting.

Before wiring this into a CI/CD pipeline, validate the output against the schema. Common failure modes include the model returning cycles shorter than [MIN_CYCLE_LENGTH], misclassifying severity when the graph lacks directory hierarchy metadata, or failing to populate the false_positives_excluded array. Run this prompt against a known dependency graph with documented cycles first, then compare the model's output to your ground truth. If the prompt is used in a regulated or safety-critical codebase, add a human review step before any automated refactoring is triggered from the remediation suggestions.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Circular Dependency Detection 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

[CODEBASE_PATH]

Root directory or repository path to scan for circular dependencies

/home/ci/monorepo/packages/backend

Must be an absolute path or repo slug. Validate directory exists and contains at least one supported manifest file (package.json, go.mod, Cargo.toml, pom.xml, etc.).

[DEPENDENCY_GRAPH]

Pre-computed dependency graph in JSON or DOT format showing all import relationships between modules

{"nodes":["src/auth","src/utils"],"edges":[{"from":"src/auth","to":"src/utils"}]}

Validate graph is valid JSON with nodes and edges arrays. Each edge must reference existing node IDs. Reject if graph is empty or contains self-loops only.

[LANGUAGE]

Programming language or ecosystem of the codebase

TypeScript

Must match one of the supported language identifiers: TypeScript, JavaScript, Python, Go, Java, Rust, C#, Kotlin, Swift. Reject unknown values.

[MODULE_RESOLUTION]

How the language resolves imports: relative paths, package names, or both

package-name

Must be one of: relative-path, package-name, or mixed. Affects how the prompt interprets edge labels in the dependency graph.

[EXCLUSION_PATTERNS]

Glob patterns or regex rules for files and directories to exclude from cycle detection

["/*.test.ts", "/*.spec.ts", "/mocks/"]

Must be a valid JSON array of strings. Each string must be a parseable glob or regex. Warn if array is empty (no exclusions may produce noisy results).

[SEVERITY_THRESHOLD]

Minimum cycle length to include in the output report

2

Must be an integer >= 2. Cycles of length 2 are direct A->B and B->A. Set higher to filter trivial pairwise cycles. Validate as positive integer.

[MAX_CYCLE_LENGTH]

Upper bound on cycle length to search for, prevents combinatorial explosion

10

Must be an integer between 3 and 20. Higher values increase computation cost and may time out. Validate range and warn if > 15 for large graphs.

[OUTPUT_FORMAT]

Desired output structure for the ranked cycle list

json

Must be one of: json, markdown-table, sarif. JSON is required for automated harness integration. SARIF enables direct CI/CD tool ingestion.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the circular dependency detection prompt into a reliable application or CI/CD workflow.

The circular dependency detection prompt is designed to be integrated into a deterministic pipeline, not used as a one-off chat. The prompt expects a structured representation of your dependency graph—typically a list of file paths and their direct imports—and returns a ranked list of cycles. The application layer is responsible for extracting this graph from the codebase (using tools like madge, dependency-cruiser, or language-specific AST parsers), formatting it as the [DEPENDENCY_GRAPH] input, and then validating the model's output before it reaches a developer or a build gate.

The implementation harness should enforce a strict contract. Before calling the model, validate that the [DEPENDENCY_GRAPH] input is a complete, non-empty list of {file, imports[]} objects. After receiving the model's response, parse the JSON output and run a structural validator that checks: (1) every reported cycle is a real cycle by walking the original graph, (2) no cycle is reported twice under a different rotation, and (3) the severity field is one of the allowed enum values. If validation fails, retry once with the validation errors appended to the [CONSTRAINTS] field. If the retry also fails, log the raw output and alert a human; never silently accept a malformed cycle report. For high-risk repositories (e.g., monoliths with strict layering rules), route critical severity cycles to a review queue that blocks merges until an architect acknowledges the finding.

Model choice matters here. The task requires precise, exhaustive graph traversal, which is a known weakness for smaller models. Use a model with strong reasoning capabilities (e.g., GPT-4, Claude 3.5 Sonnet, or Gemini 1.5 Pro) and set the temperature to 0 to minimize variance. If you are scanning a very large codebase with thousands of files, you must pre-process the graph to reduce noise: filter out test files (unless [INCLUDE_TEST_PATHS] is true), exclude known dynamic imports that your static analyzer cannot resolve, and consider partitioning the graph by top-level directory before sending it to the model. The prompt's [EXAMPLES] field should be populated with 1-2 real, anonymized cycles from your codebase to calibrate the model's output format. Finally, log every invocation with the prompt version, model, graph hash, and validation result. This creates an audit trail for when a cycle is missed or a false positive is raised, allowing you to debug the prompt rather than the architecture.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the JSON object returned by the Circular Dependency Detection prompt. Use this contract to parse the model's output and validate it before downstream consumption.

Field or ElementType or FormatRequiredValidation Rule

cycles

Array of objects

Must be a non-null array. If no cycles are found, the array must be empty.

cycles[].cycle_id

String

Must match the pattern 'CYCLE-XXXX' where XXXX is a zero-padded integer (e.g., CYCLE-0001). Must be unique within the array.

cycles[].files

Array of strings

Must contain at least 2 file paths. Each path must be a non-empty string. The order must represent the circular chain (A -> B -> ... -> A).

cycles[].cycle_length

Integer

Must be a positive integer >= 2. Must equal the number of unique file paths in the 'files' array.

cycles[].severity

String

Must be one of the allowed enum values: 'CRITICAL', 'HIGH', 'MEDIUM', 'LOW'. 'CRITICAL' is reserved for cycles involving core or foundational modules.

cycles[].entry_point

String

Must be a valid file path string. Must be one of the files listed in the 'files' array for that cycle.

cycles[].rationale

String

Must be a non-empty string explaining the severity classification. Should reference the role of the files involved (e.g., 'utility', 'core domain').

cycles[].false_positive_risk

String

If present, must be one of: 'DYNAMIC_IMPORT', 'TEST_ONLY', 'TYPE_CHECKING', 'NONE'. If absent, treat as 'NONE'. Used to flag cycles that may not exist at runtime.

PRACTICAL GUARDRAILS

Common Failure Modes

Circular dependency detection prompts fail in predictable ways. These are the most common failure modes and how to guard against them before the prompt reaches production.

01

False Positives from Dynamic Imports

What to watch: The model flags import() calls, require() inside conditionals, or lazy-loaded modules as circular when the runtime path never actually forms a cycle. Static analysis alone cannot resolve dynamic import graphs. Guardrail: Require the prompt to classify each cycle as 'static' or 'dynamic' and exclude dynamic-only cycles from severity scoring unless runtime traces confirm the cycle.

02

Test-Only Cycles Masked as Production Risk

What to watch: Test files importing from source while source test helpers import back from test directories creates cycles that are harmless in production but inflate severity rankings. Guardrail: Add a [FILE_CLASSIFICATION] input that tags each file as production, test, or shared. Instruct the prompt to separate test-only cycles into a distinct report section with zero production severity.

03

Type-Only Imports Flagged as Runtime Coupling

What to watch: TypeScript import type or Python TYPE_CHECKING imports create compile-time cycles that vanish at runtime. The model often treats them identically to value imports. Guardrail: Include a [LANGUAGE] parameter and instruct the prompt to detect type-only import syntax. Classify type-only cycles separately and note they do not cause runtime failures.

04

Cycle Length Inflation from Barrel Files

What to watch: Barrel files (index.ts, __init__.py) that re-export many modules create artificially long cycle chains. A 2-module real cycle appears as a 5-module chain when barrel files sit in the path. Guardrail: Add a preprocessing step that collapses barrel-file hops before the prompt runs, or instruct the prompt to annotate barrel-file nodes and report both raw and collapsed cycle lengths.

05

Severity Misclassification Without Context

What to watch: The model assigns 'critical' severity to a cycle between two utility modules that never deploy separately, while missing a 'high' cycle between independently deployed services. Guardrail: Provide a [DEPLOYMENT_BOUNDARY_MAP] input showing which modules deploy together. Instruct the prompt to weight severity by deployment coupling: same-unit cycles are low, cross-service cycles are high.

06

Truncated Output on Large Codebases

What to watch: When the dependency graph is large, the model hits output length limits and silently drops lower-ranked cycles or truncates file paths mid-report. Guardrail: Set an explicit [MAX_CYCLES] parameter and instruct the prompt to report only the top N cycles by severity. Add a post-processing validator that checks for complete file paths and a final summary count matching the requested limit.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and correctness of a circular dependency detection prompt output before integrating it into a CI/CD pipeline or architecture review workflow.

CriterionPass StandardFailure SignalTest Method

Cycle Completeness

All cycles in the provided [DEPENDENCY_GRAPH] are identified in the output.

A known cycle from a manually verified golden set is missing from the results.

Compare the output against a golden dataset of dependency graphs with pre-identified cycles.

False Positive Rate

Zero false positives for static import cycles. Dynamic imports and test-only cycles are flagged separately.

A reported cycle is disproven by static analysis of the actual import statements in the codebase.

For each reported cycle, verify the import chain exists in the source files. Check the [EXCLUSION_RULES] for dynamic imports.

Path Accuracy

Every reported cycle includes a correct, verifiable file path sequence forming the loop.

A reported cycle path contains a file that does not import the next file in the chain.

Parse the output and use a script to validate each edge in the cycle against the actual project's import map.

Severity Classification

Each cycle is assigned a severity (e.g., CRITICAL, HIGH, MEDIUM, LOW) consistent with the rules in [SEVERITY_RULES].

A cycle spanning core domain modules is classified as LOW, or a test-only cycle is classified as CRITICAL.

Apply the [SEVERITY_RULES] schema to the output and check for logical consistency based on cycle length and module type.

Output Schema Adherence

The output is valid JSON that strictly conforms to the provided [OUTPUT_SCHEMA].

The output is missing a required field like cycle_length, contains a string where an array is expected, or is not parseable JSON.

Validate the output string with a JSON schema validator configured with the [OUTPUT_SCHEMA].

Root Cause Identification

For each cycle, the output pinpoints the specific import edge that, if removed, would break the cycle.

The suggested break-point is not part of the cycle or would not resolve the circular dependency.

For a sample of cycles, manually verify that removing the suggested import edge eliminates the cycle in the dependency graph.

Abstention on Non-Cycles

The output correctly returns an empty list or a specific 'no cycles found' message when given an acyclic graph.

A random or hallucinated cycle is reported for a known acyclic dependency graph.

Provide a large, verified acyclic dependency graph as input and assert that the output contains zero cycles.

Handling of Large Graphs

The prompt processes a graph with over 500 nodes without timing out or exceeding token limits, producing a complete result.

The output is truncated mid-JSON, or the model reports an inability to complete the task due to input length.

Run the prompt with a synthetically generated acyclic graph of 500+ nodes and check for valid, complete JSON output.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a single repository scan and relaxed validation. Replace [LANGUAGE] and [REPO_ROOT] with concrete values. Accept plain-text output instead of strict JSON.

code
Analyze the codebase at [REPO_ROOT] for circular dependencies.
List each cycle with the files involved.

Watch for

  • False positives from dynamic imports and test-only cycles
  • Missing severity classification without the full schema
  • Large repositories hitting context limits; scan one module at a time
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.