This prompt is for platform engineers and architects who need to enforce the Acyclic Dependencies Principle (ADP) across a codebase. It takes a pre-computed dependency graph as input and produces a structured violation report identifying every cycle between packages or components, ranked by severity. The primary job-to-be-done is integrating architectural validation into a build pipeline, CI/CD gate, or pre-merge review so that cycles are caught before they compound into untestable, unbuildable tangles. The ideal user already has a dependency extraction tool in their toolchain and needs a deterministic, repeatable analysis step that produces machine-readable results.
Prompt
Acyclic Dependencies Principle Validation Prompt

When to Use This Prompt
Understand the job-to-be-done, required inputs, and operational boundaries for the Acyclic Dependencies Principle validation prompt.
The prompt is designed to be deterministic: it does not guess about dependencies, infer missing edges, or explore the codebase live. It requires a complete dependency graph in a defined format as the [INPUT] and focuses entirely on cycle detection, severity classification, and refactoring guidance. The output schema includes cycle length, participating nodes, entry points for breaking the cycle, and a severity score based on cycle size and the stability of the involved components. This makes the output suitable for automated gating—if the severity exceeds a configured threshold, the build can fail with a detailed report.
Do not use this prompt for live codebase exploration, for generating the dependency graph itself, or for analyzing runtime call graphs that include dynamic dispatch, reflection, or service meshes. It assumes the graph already exists and needs validation. For codebases with intentional cycles (such as test utilities that import from production code), provide those exemptions as part of the [CONSTRAINTS] input so the prompt can exclude them from violation reporting. The next step after reading this section is to prepare your dependency graph in the expected input format and configure the severity thresholds that match your team's architectural standards.
Use Case Fit
Where the Acyclic Dependencies Principle Validation Prompt delivers reliable value and where it introduces risk or wasted effort.
Strong Fit: Build-Time Governance Gates
Use when: You need to block PRs that introduce dependency cycles. The prompt excels at producing structured violation reports with specific file paths and cycle-breaking options that can be parsed by CI/CD tooling. Guardrail: Always pair the prompt output with a deterministic static analysis tool (e.g., Madge, JDepend) as a hard gate; use the LLM for the refactoring narrative, not as the sole cycle detector.
Strong Fit: Refactoring Sprint Planning
Use when: You have a known tangled package structure and need to sequence cycle-breaking work across multiple teams. The prompt generates ranked, actionable refactoring options with rationale. Guardrail: Require the output to cite specific import statements for every cycle claimed. A cycle without a source-grounded path is a hallucination risk and must be rejected.
Poor Fit: Dynamic or Runtime Dependency Graphs
Avoid when: Dependencies are resolved at runtime via service locators, reflection, or dynamic imports. The prompt analyzes static structure and will produce false negatives for runtime cycles. Guardrail: If your language or framework relies heavily on dynamic resolution, supplement this prompt with runtime tracing data and explicitly constrain the analysis to statically analyzable imports only.
Poor Fit: Single-Repository Monoliths Without Modular Boundaries
Avoid when: The codebase has no declared package or module boundaries. Without explicit structural rules, the prompt will either find trivial cycles or invent architectural violations that don't reflect team conventions. Guardrail: Define a minimum module boundary specification (e.g., packages/, src/modules/) before running the prompt. If no boundaries exist, use a dependency structure matrix generation prompt first.
Required Input: Explicit Dependency Graph or Build Manifest
Risk: Without a concrete dependency graph, the prompt will reason from inferred or hallucinated relationships, producing a convincing but incorrect violation report. Guardrail: The prompt harness must accept a pre-computed dependency graph (JSON or CSV) or a parsed build manifest (e.g., package.json, Cargo.toml, go.mod) as the [DEPENDENCY_GRAPH] input. Never ask the model to guess the graph from memory.
Operational Risk: False Positives from Test-Only or Dev Cycles
Risk: The prompt may flag cycles that exist only in test code, development tools, or shared kernel exceptions, causing teams to waste effort on benign tangles. Guardrail: Configure an [EXEMPTION_LIST] input that defines allowed cycles (e.g., test utilities <-> core). The output must include an exempted_cycles field so reviewers can distinguish intentional exceptions from new violations.
Copy-Ready Prompt Template
A ready-to-use prompt for validating that a codebase or design adheres to the Acyclic Dependencies Principle, producing a structured violation report with cycle-breaking options.
This prompt template is the core engine for an automated ADP gate. It is designed to be dropped into a CI/CD pipeline or a local pre-commit hook. The prompt instructs the model to act as a strict architecture validator, analyzing a provided dependency graph or package structure to find cycles. It does not just list cycles; it requires the model to propose concrete, actionable refactoring options for each one, making the output directly useful for an engineering team.
textYou are an expert software architect enforcing the Acyclic Dependencies Principle (ADP). Your task is to analyze the provided dependency graph for a codebase and produce a strict violation report. # INPUT [DEPENDENCY_GRAPH] # CONSTRAINTS - A dependency graph is a directed graph where nodes are components/packages and edges represent 'depends on' relationships. - A cycle is any path where you can start at a node and follow directed edges to return to the same node. - Ignore self-referencing edges (a node depending on itself). - If a cycle exists only within a test scope, flag it with a lower severity. - Do not invent dependencies. Only use the provided [DEPENDENCY_GRAPH]. # OUTPUT_SCHEMA You must respond with a valid JSON object conforming to this structure: { "summary": { "total_components": <integer>, "total_dependencies": <integer>, "cyclic_groups_found": <integer>, "is_acyclic": <boolean> }, "cycles": [ { "cycle_id": "<string>", "severity": "<CRITICAL|WARNING>", "components_in_cycle": ["<string>"], "cycle_length": <integer>, "violating_edges": [ {"from": "<string>", "to": "<string>"} ], "refactoring_options": [ { "strategy": "<Dependency Inversion|Extract Interface|Move Component|Break Edge>", "description": "<string>", "target_edge": {"from": "<string>", "to": "<string>"} } ] } ] } # INSTRUCTIONS 1. Parse the [DEPENDENCY_GRAPH] to identify all strongly connected components. 2. For each cycle found, generate a unique `cycle_id`. 3. Assign a `CRITICAL` severity to cycles in production code and `WARNING` to cycles that exist only in test code. 4. For each cycle, propose at least one concrete refactoring option by specifying a target edge to break and a standard architectural strategy. 5. If no cycles are found, return an empty `cycles` array and set `is_acyclic` to true.
To adapt this template, replace the [DEPENDENCY_GRAPH] placeholder with a machine-readable representation of your package structure. This could be a JSON object mapping package names to lists of their dependencies, a list of edge objects, or even a raw adjacency list. The critical adaptation is ensuring the input format is consistent and unambiguous for the model. For high-risk production gates, always follow this prompt with a validation step that programmatically verifies the reported cycles exist in the original graph to catch model hallucinations before blocking a build.
Prompt Variables
Each placeholder required by the Acyclic Dependencies Principle Validation Prompt, its purpose, an example value, and actionable validation notes for build-time integration.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DEPENDENCY_GRAPH] | Machine-readable representation of all components and their import relationships | JSON: {"nodes":["src/auth","src/billing"],"edges":[{"from":"src/auth","to":"src/billing"}]} | Parse check: must be valid JSON with nodes array and edges array. Each edge must reference existing node IDs. Reject if graph contains self-loops or duplicate edges. |
[COMPONENT_DEFINITION] | Rules for what constitutes a component boundary in this codebase | "Directory-level packages matching src/**/init.py" | Schema check: must be a non-empty string. Validate that the definition is resolvable against the actual repository structure. Reject if definition matches zero components. |
[EXCLUSION_PATTERNS] | Glob patterns for files or directories to exclude from cycle detection | ["/test_*.py","/conftest.py","**/migrations/*"] | Parse check: must be a valid JSON array of strings. Each pattern must be a valid glob. Warn if exclusion patterns remove more than 30% of total edges. Test-only cycles should be excluded by default. |
[CYCLE_SEVERITY_THRESHOLD] | Minimum cycle length or component count that triggers a violation | 3 | Schema check: must be a positive integer. Validate that threshold is at least 2. Cycles of length 2 are often intentional bidirectional dependencies and may produce false positives if flagged. |
[OUTPUT_FORMAT] | Desired structure for the violation report | "json" or "markdown" or "sarif" | Enum check: must be one of ["json","markdown","sarif"]. SARIF output requires additional field mapping for tool integration. Reject unknown format values. |
[REFACTORING_OPTIONS_COUNT] | Maximum number of cycle-breaking suggestions to generate per violation | 3 | Schema check: must be an integer between 1 and 10. Higher values increase token usage and latency. Validate that suggestions reference actual edges in the dependency graph. |
[BUILD_INTEGRATION_MODE] | Whether the prompt runs as a blocking gate or advisory check in CI/CD | "blocking" or "advisory" | Enum check: must be one of ["blocking","advisory"]. Blocking mode requires exit code mapping. Advisory mode should still produce structured output for dashboard ingestion. |
[KNOWN_INTENTIONAL_CYCLES] | Pre-approved cycle exceptions that should not appear in violation output | [{"cycle":["src/types","src/utils"],"reason":"Shared kernel for DTOs"}] | Parse check: must be a valid JSON array of cycle objects with cycle and reason fields. Validate that each intentional cycle actually exists in the dependency graph. Reject if reason field is empty. |
Implementation Harness Notes
How to wire the Acyclic Dependencies Principle Validation Prompt into a build-time validation workflow.
This prompt is designed to be integrated into a CI/CD pipeline as a non-blocking or blocking quality gate, depending on your team's tolerance for dependency debt. The harness should invoke the LLM after a dependency graph has been extracted from the codebase using a deterministic tool like madge, dependency-cruiser, or a language-specific analyzer. The LLM's role is not to discover cycles—the static analysis tool does that with perfect accuracy—but to interpret the results, classify severity, and propose refactoring options that a tool cannot. The harness must therefore supply the prompt with a pre-computed list of cycles, not raw source code.
The implementation flow should follow a strict sequence: (1) run the static analysis tool to generate a JSON dependency graph and a list of cycles; (2) filter out known false positives using a configurable allowlist of test-only cycles, dynamic imports, or intentional exceptions; (3) construct the prompt payload by injecting the filtered cycle list into the [CYCLE_LIST] placeholder, along with the [PACKAGE_RULES] describing your architectural boundaries; (4) call the model with a low temperature setting (0.0–0.2) to maximize deterministic output; (5) validate the response against the expected [OUTPUT_SCHEMA] before accepting it; and (6) publish the validated report as a build artifact or PR comment. If validation fails, retry once with the error message appended to the prompt context, then fail the check and alert the platform team.
The output schema must be strictly validated before the report is surfaced to developers. Each cycle entry must contain a cycle_id, a severity from the allowed enum (BLOCKER, HIGH, MEDIUM, LOW), a cycle_path array of package names, and at least one refactoring_option with a strategy field. If the model returns a cycle not present in the input [CYCLE_LIST], reject the entire response as a hallucination. If a severity value is outside the allowed enum, map it to MEDIUM and flag the anomaly in logs. The harness should also check that refactoring_option suggestions reference actual packages from the input and do not invent package names. For high-risk repositories where a false positive could block a release, route BLOCKER and HIGH severity findings to a human reviewer via a PR comment or ticketing system before the build gate enforces the block.
Model choice matters for this workflow. Use a model with strong reasoning capabilities and structured output support, such as Claude 3.5 Sonnet or GPT-4o, configured with JSON mode or structured outputs enabled. Avoid smaller or older models that may struggle with the multi-step reasoning required to propose viable refactoring strategies. Log every invocation with the prompt version, model identifier, cycle count, validation pass/fail status, and any schema violations. This trace data is essential for debugging false positives, tuning severity thresholds, and defending architectural decisions during team discussions. Start with a non-blocking advisory mode for two sprints to calibrate severity thresholds against your team's actual tolerance before promoting the check to a blocking gate.
Expected Output Contract
The fields, types, and validation rules for the model response when validating the Acyclic Dependencies Principle. Use this contract to parse the model output into a structured violation report for build-time integration.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
violations | Array of objects | Must be a JSON array. If no cycles are found, return an empty array. Schema check: every element must match the violation_object schema. | |
violations[].cycle_id | String | Must be a unique identifier for the cycle, e.g., 'CYCLE-001'. Regex check: ^CYCLE-\d{3}$. | |
violations[].cycle_path | Array of strings | Must contain at least 3 fully qualified package or file paths representing the cycle. The first and last element must be identical. Parse check: verify the path strings match the format of [INPUT] paths. | |
violations[].severity | Enum: 'BLOCKER', 'CRITICAL', 'WARNING' | Must be one of the defined enum values. 'BLOCKER' for cycles in core domain packages. 'CRITICAL' for cycles crossing major architectural boundaries. 'WARNING' for cycles in test or utility packages. | |
violations[].breaking_suggestion | String or null | If severity is 'BLOCKER' or 'CRITICAL', a non-null string describing a refactoring approach (e.g., 'Extract Interface', 'Dependency Inversion') is required. If 'WARNING', the value may be null. Null check: reject if null for high-severity violations. | |
analysis_summary.total_packages_analyzed | Integer | Must be a positive integer matching the count of distinct packages provided in [DEPENDENCY_GRAPH]. Schema check: must be > 0. | |
analysis_summary.total_cycles_found | Integer | Must be a non-negative integer. Must equal the length of the 'violations' array. Consistency check: total_cycles_found === violations.length. | |
analysis_confidence | Enum: 'HIGH', 'MEDIUM', 'LOW' | Must be 'LOW' if the [DEPENDENCY_GRAPH] input is incomplete or contains dynamic imports. Must be 'HIGH' only if all dependencies are statically resolvable. Confidence threshold: if 'LOW', a human review flag must be raised by the harness. |
Common Failure Modes
When validating the Acyclic Dependencies Principle, these failures surface most often in production. Each card pairs a specific failure with a concrete guardrail you can implement before the prompt reaches a CI/CD gate.
False Positives from Test-Only Imports
What to watch: The prompt flags a cycle because test files import from production packages that import test utilities. This inflates violation counts and wastes engineering time on non-issues. Guardrail: Pre-filter the dependency graph to exclude *_test.*, *.test.*, and paths under test/ or tests/ directories before passing the graph to the prompt. Add a --exclude-test-paths flag to your harness.
Dynamic Import Blindness
What to watch: Static analysis misses cycles created by import(), require() inside functions, or reflection-based loading. The prompt reports a clean graph while runtime cycles still cause deadlocks or initialization failures. Guardrail: Augment the input with a runtime dependency trace or dynamic import manifest. If unavailable, add a constraint to the prompt: 'If dynamic imports are present but not analyzed, flag this as a known blind spot and do not assert acyclicity.'
Cycle Severity Misclassification
What to watch: The prompt treats a 2-node cycle between sibling utility packages the same as a 12-node cycle spanning domain and infrastructure layers. Teams waste effort on low-risk cycles while ignoring architecture-breaking tangles. Guardrail: Require the output schema to include a severity field calculated from cycle length, layer boundary crossings, and package stability metrics. Add eval criteria that verify high-severity cycles always involve layer violations or stable-package involvement.
Refactoring Suggestions That Create New Cycles
What to watch: The prompt suggests extracting a shared interface to break a cycle, but the suggested location creates a new cycle with a third package. The fix replaces one violation with another. Guardrail: Add a post-generation validation step that re-runs the cycle detection algorithm on the proposed refactored graph. Only accept suggestions that produce a strictly lower cycle count. Include this as a **Refactoring Safety Check** in the prompt's output schema.
Monorepo Tooling Boundary Confusion
What to watch: Build tooling packages (e.g., shared ESLint configs, TypeScript path aliases, bundler plugins) appear in the dependency graph and create apparent cycles with application code. The prompt treats tooling configuration as architectural coupling. Guardrail: Provide a --tooling-packages allowlist or regex pattern in the harness. Pre-label these packages as category: tooling in the input graph so the prompt can exclude them from architectural violation reporting.
Output Drift Toward Generic Advice
What to watch: When the graph is large or complex, the prompt abandons specific cycle-breaking refactorings and produces vague guidance like 'consider using dependency inversion' without naming specific interfaces or packages. Guardrail: Constrain the output schema to require at least one concrete file path or package name per suggested action. Add an eval check that rejects responses where refactoring suggestions lack a target_package or new_dependency_direction field.
Evaluation Rubric
Criteria for evaluating the quality and correctness of the Acyclic Dependencies Principle validation output before integrating the prompt into a CI pipeline. Each row defines a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Cycle Detection Completeness | All cycles in the provided [DEPENDENCY_GRAPH] are reported with no false negatives. | A known cycle from a ground-truth test fixture is missing from the output. | Compare the output's cycle list against a pre-computed golden set of cycles for a small, controlled graph. |
False Positive Rate | Zero false positives. No acyclic paths are reported as cycles. | A reported cycle contains a node that is not part of an actual cycle in the input graph. | Validate each reported cycle path by tracing the edges in the [DEPENDENCY_GRAPH] to confirm a closed loop exists. |
Output Schema Validity | The output is valid JSON that strictly conforms to the [OUTPUT_SCHEMA]. | JSON parsing fails, or a required field like | Validate the raw output string against the [OUTPUT_SCHEMA] using a JSON schema validator. |
Cycle Path Accuracy | Every | A | For each reported cycle, programmatically verify that an edge exists in [DEPENDENCY_GRAPH] from each node to the next, including from the last node back to the first. |
Severity Classification | Severity is correctly classified as | A direct 2-node cycle is classified as | Check the |
Refactoring Suggestion Relevance | Each | A suggestion is generic (e.g., 'fix the cycle'), irrelevant to the specific components, or missing for a reported cycle. | Perform a manual review of suggestions for a sample of reported cycles, or use an LLM-as-judge with a rubric to assess relevance and concreteness. |
Idempotency | Running the prompt twice on the same [DEPENDENCY_GRAPH] produces an identical set of cycles and suggestions. | The number of reported cycles or the specific paths differ between two runs with the same input. | Execute the prompt twice with the same input and a temperature of 0. Compare the sorted JSON outputs for exact equality. |
Instruction Adherence | The output contains only the requested JSON and no other text, markdown fences, or commentary. | The output is wrapped in markdown code fences (```json) or contains explanatory text before or after the JSON object. | Check if the trimmed output string starts with |
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
Add strict JSON schema validation, retry logic on malformed output, structured logging, and a golden dataset of known dependency graphs for regression testing. Integrate with build-time validation via a CI/CD harness.
Prompt modification
- Enforce [OUTPUT_SCHEMA] with required fields:
cycle_id,cycle_path,cycle_length,severity,breaking_options. - Add [CONSTRAINTS]: "Only report cycles where all edges are confirmed by static import analysis. Exclude test-only imports unless they create production-facing cycles."
- Include [EXEMPTION_RULES] placeholder for team-specific allowlists.
- Add retry instruction: "If output fails schema validation, re-examine the graph and correct field types."
Watch for
- Silent format drift when model changes versions.
- Missing
breaking_optionsfor long cycles. - Performance degradation on large dependency graphs; consider chunking.

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