This prompt is designed for architects and platform engineers who need to audit a codebase for violations of the Stable Dependencies Principle (SDP). The SDP states that a package should only depend on packages that are more stable than itself. When a stable package depends on an unstable package, that unstable package becomes difficult to change without breaking its dependents, creating a rigidity that slows delivery. The ideal user has already computed stability metrics (such as Martin instability) and has a dependency graph available, either from a static analysis tool or a build system. The prompt takes this graph and metrics as input and produces a ranked violation report with concrete refactoring direction, turning raw numbers into architectural judgment.
Prompt
Stable Dependencies Principle Compliance Review Prompt

When to Use This Prompt
A practical guide for architects and platform engineers to audit a codebase for Stable Dependencies Principle violations before a refactoring cycle or architecture review gate.
Use this prompt before a planned refactoring cycle, as part of an architecture review gate, or when a team reports that a supposedly stable module keeps breaking on upstream changes. It is most effective when you have a clear, machine-readable representation of your dependency graph and stability values. The prompt expects structured input, such as a JSON object mapping each package to its instability score and its direct dependencies. It will then reason about the direction of dependencies and flag cases where a more stable package depends on a less stable one. The output is a ranked list of violations, each with a severity assessment and a suggested refactoring direction, such as dependency inversion, extracting an interface, or moving the unstable package into a more stable layer.
Do not use this prompt for runtime coupling analysis, for greenfield design where no dependency graph exists yet, or as a substitute for static analysis tools that compute the raw metrics. This prompt adds architectural judgment on top of the metrics; it does not generate them. It is also not suitable for analyzing coupling in non-code systems, such as organizational dependencies or infrastructure topologies. For those, use a dedicated prompt from the System Boundary or Microservice Coupling playbooks. Before running this prompt, ensure your input data is accurate and complete. A missing dependency or an incorrectly calculated instability score will lead to false positives or missed violations. If your codebase uses stable abstractions (e.g., interfaces or abstract classes that are intentionally stable), include that context in the input to avoid flagging legitimate patterns as violations.
Use Case Fit
Where the Stable Dependencies Principle Compliance Review Prompt delivers reliable architectural insight and where it introduces noise or false confidence.
Good Fit: Package-Level Architecture Audits
Use when: you need to audit a monorepo or multi-package system against the Stable Dependencies Principle (SDP) before a major refactor or release. The prompt excels at identifying unstable packages that stable packages depend on, producing a ranked violation report with specific import paths. Guardrail: Ground every violation in actual import statements from build manifests or AST analysis, not inferred dependencies.
Bad Fit: Runtime or Dynamic Dependency Analysis
Avoid when: you need to analyze runtime coupling, service-to-service call patterns, or dynamic imports resolved at execution time. This prompt targets static package dependency graphs and will miss temporal coupling, feature flag gating, or reflection-based loading. Guardrail: Pair with runtime tracing tools for production coupling analysis; use this prompt only for build-time dependency structure.
Required Inputs: Dependency Graph and Stability Metrics
What you must provide: a dependency graph showing which packages depend on which, plus stability metrics (fan-in, fan-out, instability scores) for each package. Without these, the model cannot distinguish stable from unstable packages. Guardrail: Pre-compute metrics with a tool like dependency-cruiser or madge before feeding the graph into the prompt. Never ask the model to invent metrics from package names alone.
Operational Risk: False Positives from Stable Abstractions
What to watch: abstract base classes, interface packages, and protocol definitions often have high fan-in and low fan-out, appearing stable. The prompt may flag dependencies on these as SDP violations when they are intentional design choices. Guardrail: Include an explicit exemptions list for abstract packages, shared kernels, and stable abstractions. Require the prompt to check each violation against this list before reporting.
Operational Risk: Stale Dependency Graph Data
What to watch: if the dependency graph was generated from a stale build or incomplete scan, the prompt will produce violations that don't reflect the current codebase. Guardrail: Automate graph generation as part of the review pipeline. Include a timestamp and commit hash in the input context so reviewers can verify freshness before acting on results.
Integration Point: CI/CD Architecture Gates
Use when: you want to block merges that introduce new SDP violations. The prompt output can be parsed for pass/fail decisions in CI. Guardrail: Start with advisory mode only. Require human review for at least two sprint cycles before promoting to a blocking gate. Track false positive rate and adjust exemption rules before enforcement.
Copy-Ready Prompt Template
A reusable prompt template for auditing package stability against the Stable Dependencies Principle, ready to adapt with your codebase context.
This prompt template is designed to be copied directly into your AI harness, IDE, or orchestration layer. It uses square-bracket placeholders for all variable inputs—your dependency graph, stability metrics, and output format requirements. The template enforces a structured violation report format so you can parse results programmatically, feed them into CI/CD gates, or route them to an architect for review. Before using it, ensure you have computed or extracted the necessary inputs: a list of packages/components, their incoming and outgoing dependencies, and any declared stability classifications (e.g., 'stable', 'unstable', 'abstract').
textYou are an architecture compliance auditor. Your task is to review a dependency graph against the Stable Dependencies Principle (SDP), which states that a stable package (high fan-in, low fan-out) should not depend on an unstable package (low fan-in, high fan-out). ## INPUT - Package dependency graph: [DEPENDENCY_GRAPH] - Stability metrics per package (fan-in, fan-out, instability score I = fan-out / (fan-in + fan-out)): [STABILITY_METRICS] - Declared stability classifications or allowed exceptions: [STABILITY_CLASSIFICATIONS] - Known stable abstractions (interfaces, abstract classes) that may produce false positives: [STABLE_ABSTRACTIONS] ## CONSTRAINTS - Flag only direct dependencies, not transitive ones, unless [INCLUDE_TRANSITIVE] is set to true. - For each violation, check whether the unstable target is a stable abstraction (interface or abstract class). If so, classify it as a FALSE_POSITIVE and explain why. - Ignore test-only dependencies unless [INCLUDE_TEST_DEPS] is true. - Ignore dependencies on packages marked as [EXEMPT_PACKAGES]. ## OUTPUT_SCHEMA Return a JSON object with the following structure: { "summary": { "total_packages_analyzed": <int>, "total_violations": <int>, "false_positives": <int>, "true_violations": <int> }, "violations": [ { "stable_package": "<package name>", "unstable_package": "<package name>", "stable_instability_score": <float>, "unstable_instability_score": <float>, "violation_severity": "HIGH" | "MEDIUM" | "LOW", "is_false_positive": <bool>, "false_positive_reason": "<explanation if applicable, else null>", "refactoring_direction": "<concrete suggestion: invert dependency, introduce abstraction, merge packages, or move code>" } ] } ## RISK_LEVEL [RISK_LEVEL] ## INSTRUCTIONS 1. For each stable package (I < [STABILITY_THRESHOLD]), examine its outgoing dependencies. 2. If a dependency target has I > [INSTABILITY_THRESHOLD], flag it as a potential violation. 3. Cross-reference flagged violations against [STABLE_ABSTRACTIONS] to identify false positives. 4. Assign severity: HIGH if the unstable package has I > 0.8 and the stable package has I < 0.2; MEDIUM if the gap is moderate; LOW if near the threshold. 5. For each true violation, provide a refactoring direction that reduces coupling in the stable-to-unstable direction. 6. If [RISK_LEVEL] is HIGH, include a warning that human review is required before any automated refactoring.
To adapt this template, replace each square-bracket placeholder with data from your build system, dependency analyzer, or architecture documentation. The [DEPENDENCY_GRAPH] can be a JSON adjacency list, a Mermaid diagram, or a structured text description—the model will parse any reasonable format. The [STABILITY_METRICS] should include at minimum fan-in, fan-out, and the computed instability score (I) for each package. If you don't have these pre-computed, pair this prompt with a dependency analysis tool like dependency-cruiser, jdeps, or a custom script that outputs the required metrics. The [STABLE_ABSTRACTIONS] list is critical for reducing false positives: include all interface packages, abstract base classes, and protocol definitions that are intentionally unstable but safe to depend on. For CI/CD integration, set [RISK_LEVEL] to "HIGH" to force a human-in-the-loop review gate; for informational dashboards, set it to "LOW" to suppress warnings. Test the prompt first against a known-clean module and a known-violating module to calibrate your [STABILITY_THRESHOLD] and [INSTABILITY_THRESHOLD] values before running it across the full codebase.
Prompt Variables
Required inputs for the Stable Dependencies Principle compliance review. Each placeholder must be populated before the prompt is sent. Validation notes describe how to confirm the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[DEPENDENCY_GRAPH] | Machine-readable representation of all components and their dependency relationships | JSON adjacency list: {"stable.core": ["unstable.utils"], "unstable.utils": []} | Parse check: must be valid JSON. Schema check: keys are component names, values are arrays of dependency names. Null allowed: false. |
[STABILITY_METRICS] | Pre-computed stability scores for each component in the graph | {"stable.core": {"instability": 0.1, "fanIn": 9, "fanOut": 1}} | Schema check: each entry must contain instability (float 0-1), fanIn (int), fanOut (int). Range check: instability must equal fanOut/(fanIn+fanOut) within 0.01 tolerance. Null allowed: false. |
[COMPONENT_CATALOG] | Metadata about each component including type, owner, and declared layer | {"stable.core": {"type": "library", "layer": "domain", "owner": "platform-team"}} | Schema check: each entry must have type and layer fields. Enum check: type must be in [library, service, adapter, shared-kernel]. Null allowed: false. |
[ABSTRACTION_WHITELIST] | List of stable components that are exempt from violation reporting because they are abstract interfaces or contracts | ["stable.contracts.api", "stable.spi.interfaces"] | Parse check: must be a JSON array of strings. Membership check: each entry must exist in [DEPENDENCY_GRAPH] keys. Null allowed: true. If null, no exemptions are applied. |
[VIOLATION_THRESHOLD] | Minimum instability difference that triggers a violation report | 0.3 | Range check: must be a float between 0.0 and 1.0. Default: 0.2. Lower values produce more violations and may include false positives from near-stable dependencies. |
[OUTPUT_SCHEMA] | Expected structure for the violation report output | {"violations": [{"stableComponent": string, "unstableDependency": string, "instabilityGap": float, "severity": string}]} | Schema check: must be a valid JSON Schema or example object. Field check: severity must use enum [critical, high, medium, low]. Null allowed: false. |
[CONTEXT] | Optional architectural rules or team conventions that modify violation interpretation | "Shared kernel packages are exempt from SDP checks when both components are in the domain layer." | Free text. Null allowed: true. If provided, the prompt must apply these rules after the base SDP check. Approval required: false. |
Implementation Harness Notes
How to wire the Stable Dependencies Principle compliance review into an automated architecture governance pipeline.
This prompt is designed to operate as a batch analysis step within a CI/CD pipeline or a scheduled architecture audit job. It expects a structured manifest of package metadata—stability metrics, dependency lists, and abstraction ratios—rather than raw source code. The application layer is responsible for extracting this data from the build system (e.g., JDepend, NDepend, or a custom dependency graph parser) and formatting it into the [PACKAGE_MANIFEST] input block. The model's role is pure reasoning over pre-computed metrics, not codebase exploration.
Validation and retry logic is critical because the output is a structured violation report intended for automated gating. Implement a JSON schema validator that checks for the presence of required fields (violating_package, depends_on, stability_metrics, refactoring_direction) and rejects malformed responses. On validation failure, retry once with a repair prompt that includes the schema and the raw output. If the second attempt fails, log the failure and fail the pipeline step open (warning) or closed (blocking) based on your risk tolerance. For high-assurance environments, route all violations to a human review queue before merging any refactoring PRs.
Model choice and grounding are straightforward here. Use a model with strong structured output capabilities (GPT-4o, Claude 3.5 Sonnet, or equivalent) and set temperature=0 for deterministic results. The prompt does not require retrieval-augmented generation (RAG) or tool use because all evidence is self-contained in the input manifest. However, you must ensure the upstream data extraction step is trustworthy—if the stability metrics fed into the prompt are wrong, the violation report will be wrong. Add a pre-flight check that verifies the instability values in the manifest sum correctly against the declared dependency counts before sending the payload to the model.
Expected Output Contract
Defines the structure, types, and validation rules for the Stable Dependencies Principle compliance report. Use this contract to parse, validate, and integrate the model output into downstream tooling or CI/CD gates.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
violations | Array of objects | Must be a JSON array. If no violations exist, return an empty array, not null or a string. | |
violations[].stable_package | String | Must match the fully qualified package name from [PACKAGE_LIST]. Regex check against allowed package name characters. | |
violations[].unstable_dependency | String | Must match a fully qualified package name. Must not be present in the [STABLE_PACKAGES] set if strict mode is enabled. | |
violations[].instability_score | Number (float, 0.0-1.0) | Must be a float between 0.0 and 1.0 inclusive. Instability = Ce / (Ca + Ce). Parse check: value must be calculable from provided [DEPENDENCY_METRICS]. | |
violations[].violation_type | Enum string | Must be one of: 'DIRECT_DEPENDENCY', 'TRANSITIVE_DEPENDENCY'. Schema check against allowed enum values. | |
violations[].refactoring_direction | String | Must be a non-empty string suggesting a concrete action (e.g., 'Introduce an interface in [STABLE_PACKAGE]'). Null or empty string is a failure. | |
violations[].false_positive_risk | Enum string | Must be one of: 'LOW', 'MEDIUM', 'HIGH', 'NONE'. If absent, default to 'NONE'. Indicates if the dependency is on a stable abstraction. | |
summary.total_violations | Integer | Must equal the length of the 'violations' array. Parse check: count mismatch triggers a validation error. |
Common Failure Modes
What breaks first when auditing package stability and how to prevent false positives, missed violations, and unactionable reports.
False Positives from Stable Abstractions
What to watch: The prompt flags abstract classes or interfaces as 'stable' and then reports every concrete dependency on them as a violation. This happens when the model fails to distinguish between abstract stability (interfaces, abstract base classes) and concrete volatility. Guardrail: Include explicit instructions that abstract classes, interfaces, and protocol definitions are exempt from the 'stable should not depend on unstable' rule. Add a pre-check step that classifies each package as abstract-stable, concrete-stable, or unstable before applying the dependency rule.
Missing Violations in Multi-Language Repositories
What to watch: The prompt analyzes only one language's import graph (e.g., Python) while ignoring dependencies expressed through shared schemas, gRPC definitions, or message queues that cross language boundaries. This produces a clean report for a system that is deeply coupled. Guardrail: Require the prompt to inventory all dependency mechanisms present in the repository (imports, schema references, message formats, shared configs) before beginning the stability analysis. Flag any dependency mechanism that was not analyzed.
Stability Metric Miscalculation
What to watch: The model computes fan-in and fan-out incorrectly, especially when import paths are aliased, re-exported through barrel files, or when test files are counted as dependents. This leads to wrong stability classifications and cascading false violations. Guardrail: Provide explicit counting rules: exclude test directories, resolve aliases to canonical paths, treat barrel re-exports as pass-through (count the original source, not the barrel). Include a validation step that spot-checks computed metrics against manual counts for 3-5 packages.
Unactionable Violation Volume
What to watch: The prompt reports every single violation without prioritization, producing a 200-item list that teams ignore. Common in large monorepos where some coupling is intentional and accepted. Guardrail: Add severity tiers based on violation characteristics: critical (stable package depends on highly volatile package), warning (stable depends on moderately unstable), and info (marginal stability difference). Include a configurable threshold so teams can suppress violations below a certain severity or in explicitly allowed dependency paths.
Ignoring Transitive Stability Contamination
What to watch: The prompt checks only direct dependencies. A stable package depends on a moderately stable package, which in turn depends on a highly unstable package. The direct check passes, but the transitive instability is missed. Guardrail: Include a transitive analysis mode that propagates instability scores through the dependency graph. Flag packages whose effective instability (considering all transitive dependents) exceeds their declared stability. Make this mode optional but clearly documented.
Outdated Dependency Graph Input
What to watch: The prompt runs against a stale dependency graph (e.g., a manually provided list or a cached build graph) that doesn't reflect the current state of the codebase. Violations are reported for code that has already been refactored, or new violations are missed. Guardrail: Require the dependency graph to be generated fresh from the current build system or import analyzer as a pre-step. Include a timestamp and commit hash in the prompt context so reviewers can verify freshness. Add a warning in the output if the graph source is older than a configurable threshold.
Evaluation Rubric
Criteria for evaluating the quality and correctness of the Stable Dependencies Principle compliance report before integrating it into a CI/CD gate or architecture review workflow.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Violation Completeness | Every stable package depending on an unstable package is listed with a specific import path. | A known violation from a manual spot-check is missing from the report. | Compare report violations against a manually curated golden set of 5 known SDP violations in a test repository. |
Stability Metric Accuracy | The calculated instability (I = Ce / (Ca + Ce)) for each reported package matches a manual calculation from the dependency graph. | A package's reported instability metric differs from the independently calculated value by more than 0.05. | Extract the reported I value for 3 packages; compute I independently from the dependency graph and assert the absolute difference is < 0.05. |
False Positive Handling | Stable packages depending on stable abstractions (interfaces or abstract classes) are correctly excluded from the violation list. | A stable package depending on a stable interface is incorrectly flagged as an SDP violation. | Include a test case with a stable package depending on a stable abstract class; assert the package is absent from the violations list. |
Refactoring Direction Quality | Each violation includes a concrete, actionable refactoring suggestion (e.g., 'extract interface', 'invert dependency', 'move to shared kernel'). | A violation entry contains a generic suggestion like 'fix coupling' or no suggestion at all. | Parse the refactoring field for each violation; assert it is non-empty and contains at least one recognized pattern from a predefined list of dependency-inversion techniques. |
Source Grounding | Every violation entry cites the specific file path and line number of the import statement causing the violation. | A violation entry has a null or missing source location, or the cited location does not contain an import statement. | For 3 randomly selected violations, open the cited file at the cited line and assert an import statement exists that matches the reported dependency. |
Output Schema Compliance | The report is valid JSON matching the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed. | The output fails JSON schema validation or a required field like 'violations' is missing or null. | Validate the entire output against the [OUTPUT_SCHEMA] using a JSON schema validator; assert no errors. |
Severity Classification Consistency | Violations are classified as 'critical', 'high', or 'medium' based on a documented heuristic combining the stable package's fan-in and the unstable package's volatility. | Two violations with identical stability metrics and fan-in receive different severity classifications. | Extract severity and metrics for all violations; group by metrics and assert consistent severity assignment within each group. |
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 package manifest or dependency graph input. Skip strict schema validation on the output. Focus on getting a readable violation list with package names and stability metrics.
Simplify the prompt by removing the false-positive checks for stable abstractions. Accept a plain-text dependency list instead of requiring a structured graph format.
Watch for
- The model may flag abstract classes or interface packages as unstable when they are intentionally designed that way
- Output format will drift across runs without a schema constraint
- No source grounding means violations can't be traced back to specific import statements

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