Inferensys

Prompt

Dependency Drift Detection Prompt

A practical prompt playbook for using Dependency Drift Detection Prompt in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, the ideal user, required inputs, and the constraints that make this prompt appropriate or inappropriate for a given task.

This prompt is designed for platform engineers, architects, and technical leads who need to detect and quantify dependency drift in a codebase over time. The job-to-be-done is automated surveillance: comparing the declared dependencies in a project's manifest files (e.g., package.json, go.mod, Cargo.toml) against the actual import or require statements in the source code. The output is a structured drift report that surfaces stale declarations (packages declared but unused) and undeclared usage (packages used but not formally declared), which are primary vectors for supply chain risk, broken builds, and license non-compliance.

You should use this prompt when you have access to both a dependency manifest and a source tree, and you want to integrate the check into a CI/CD pipeline or a periodic scanning harness. The prompt assumes the input is a pre-processed, machine-readable diff or a structured list of declared vs. actual imports, not raw file trees. It is ideal for teams that want to enforce a policy where the manifest is the single source of truth. Do not use this prompt for initial architecture review, for evaluating the quality of a dependency, or for detecting circular dependencies—those are separate, specialized tasks. This prompt is also not a replacement for a Software Composition Analysis (SCA) tool that checks for known vulnerabilities; it focuses strictly on the delta between declaration and usage.

The prompt is most effective when the risk of undeclared dependencies is high, such as in regulated environments, monorepos with shared libraries, or projects with strict license auditing requirements. It requires a human-in-the-loop review step for any detected drift before auto-remediation, as a package might be intentionally used without a manifest entry during local development or testing. Before using this prompt, ensure you have a pre-processing step that extracts and normalizes package identifiers from both the manifest and the source code into a consistent format (e.g., namespace/package@version). The next section provides the exact prompt template you can adapt and embed in your scanning harness.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Dependency Drift Detection Prompt delivers value and where it creates noise. Use these cards to decide whether to run the prompt, skip it, or pair it with additional tooling.

01

Good Fit: Monitored Repositories with Build Manifests

Use when: you have a repository with a standard package manifest (package.json, Cargo.toml, requirements.txt, go.mod) and want to catch undeclared imports or stale declarations. Guardrail: the prompt requires a parseable manifest and a dependency graph as input. If your build system doesn't produce a standard graph, run a tool like dep-tree or madge first and feed its output into the prompt.

02

Bad Fit: Dynamic or Runtime-Only Dependency Resolution

Avoid when: dependencies are resolved at runtime via reflection, service locators, plugin systems, or dynamic imports that static analysis cannot see. Guardrail: the prompt relies on a static dependency graph. For runtime coupling, pair this with a Dynamic Analysis tool that captures actual import traces in staging before running the drift report.

03

Required Input: Parseable Dependency Graph

Risk: garbage in, garbage out. If the input graph is incomplete or incorrectly scoped (e.g., missing dev dependencies, including build artifacts), the drift report will flag false positives or miss real drift. Guardrail: validate the input graph before prompting. Ensure it includes all source directories and excludes generated code. A pre-prompt validation script should confirm node count and edge count match expectations.

04

Operational Risk: Alert Fatigue from Low-Severity Drift

Risk: running this prompt on every commit may produce drift reports full of test-only or type-stub dependencies that teams learn to ignore. Guardrail: configure severity thresholds in the prompt harness. Filter out devDependencies, test scopes, and type definition packages before generating the report. Only escalate drift in production-critical dependency scopes.

05

Operational Risk: Stale Declarations in Monorepos

Risk: in monorepos, a package may declare a dependency that is satisfied by another workspace package, appearing as "stale" when it's actually intentional. Guardrail: the prompt harness must accept a workspace map or monorepo configuration. Instruct the model to treat internal workspace references as satisfied declarations, not drift.

06

Not a Replacement for Supply-Chain Security Scanning

Risk: teams may confuse dependency drift detection with vulnerability or license scanning. Drift detection tells you what's declared vs. used, not whether a declared dependency has a CVE. Guardrail: run this prompt alongside tools like Dependabot, Snyk, or OWASP Dependency-Check. The drift report is a coupling hygiene tool, not a security audit.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for generating a dependency drift report by comparing declared dependencies against actual usage.

This prompt template is the core instruction set for a Dependency Drift Detection scan. It is designed to be parameterized with your project's specific package manifest, import graph, and output requirements. The model is instructed to act as a meticulous build engineer, cross-referencing two structured inputs to produce a precise, actionable drift report. The primary goal is to identify 'stale declarations' (packages declared but not used) and 'undeclared usage' (packages used but not declared), which are the two most common forms of dependency rot that lead to broken builds, security vulnerabilities, and difficult onboarding.

text
You are a build system auditor. Your task is to compare a project's declared dependencies against its actual import statements to detect drift.

# INPUTS
[DECLARED_DEPENDENCIES]
[ACTUAL_IMPORTS]

# OUTPUT_SCHEMA
Return a single JSON object with the following structure:
{
  "project": "[PROJECT_NAME]",
  "scan_timestamp": "[SCAN_TIMESTAMP]",
  "drift_report": {
    "stale_declarations": [
      {
        "package": "string",
        "declared_version": "string",
        "last_used_date": "string or null",
        "removal_risk": "LOW | MEDIUM | HIGH",
        "notes": "string"
      }
    ],
    "undeclared_usage": [
      {
        "package": "string",
        "imported_in_file": "string",
        "estimated_version_used": "string or null",
        "integration_risk": "LOW | MEDIUM | HIGH",
        "notes": "string"
      }
    ],
    "version_mismatches": [
      {
        "package": "string",
        "declared_version": "string",
        "locked_version": "string or null",
        "latest_version": "string or null",
        "notes": "string"
      }
    ]
  },
  "summary": {
    "total_stale": "integer",
    "total_undeclared": "integer",
    "total_mismatches": "integer",
    "overall_health": "HEALTHY | WARNING | CRITICAL"
  }
}

# CONSTRAINTS
- Classify a package as 'stale' only if it has zero imports across the entire codebase provided in [ACTUAL_IMPORTS].
- Classify a package as 'undeclared' if it appears in [ACTUAL_IMPORTS] but not in [DECLARED_DEPENDENCIES].
- For `removal_risk`, use 'HIGH' if the package is a core framework, 'MEDIUM' if it's a utility library, and 'LOW' if it's a type definition or development-only tool.
- For `integration_risk`, use 'HIGH' if the undeclared package is a transitive dependency that could be removed by a parent package update, 'MEDIUM' if it's a direct but undeclared dependency, and 'LOW' if it's a standard library or universally available package.
- Do not invent or assume any import that is not present in the provided [ACTUAL_IMPORTS] list.
- If a package is declared but its usage is only in test files, note this in the `notes` field but still flag it as stale for the main application.

To adapt this template, replace the placeholders with data from your build system and code analysis tools. [DECLARED_DEPENDENCIES] should be populated with the parsed contents of your package.json, requirements.txt, Cargo.toml, or equivalent manifest. [ACTUAL_IMPORTS] should be a structured list of all import statements extracted from your codebase, typically generated by a static analysis tool or a simple grep command. The [PROJECT_NAME] and [SCAN_TIMESTAMP] fields should be injected by your automation harness to ensure every report is traceable to a specific scan. The output schema is strict JSON to allow for direct ingestion into a monitoring dashboard or CI/CD pipeline.

IMPLEMENTATION TABLE

Prompt Variables

Placeholders required by the Dependency Drift Detection Prompt. Each variable must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[DECLARED_DEPENDENCIES]

The project's declared dependency manifest, typically from a lock file or package specification

package-lock.json, Cargo.lock, go.sum, requirements.txt with pinned versions

Parse check: must be valid JSON, TOML, or plain text matching the expected manifest format. Reject if empty or unparseable.

[ACTUAL_IMPORTS]

The set of import statements extracted from source files in the repository

import numpy as np; from flask import Flask; require('lodash')

Parse check: must be a non-empty list of import strings with file-path provenance. Reject if no file paths are attached to imports.

[SCAN_TIMESTAMP]

ISO-8601 timestamp of when the scan was performed, used for drift comparison over time

2025-03-15T14:30:00Z

Format check: must match ISO-8601 with timezone. Reject if missing or in an ambiguous local time format.

[PREVIOUS_DRIFT_REPORT]

The prior drift report output, used to detect new drift versus pre-existing drift

JSON object matching the output schema from a previous run

Schema check: must conform to the expected drift report output schema. Null allowed on first run. Reject if present but unparseable.

[REPOSITORY_ROOT]

Absolute path or identifier for the repository being scanned, used for traceability

/home/ci/projects/payments-service or github.com/org/payments-service

Non-empty string required. Reject if null or whitespace-only. Used to anchor file paths in the output.

[EXCLUSION_PATTERNS]

Glob patterns for files or directories to exclude from import scanning

["/test/", "/node_modules/", "/vendor/"]

Must be a valid JSON array of glob strings. Reject if not an array. Empty array allowed for no exclusions.

[DRIFT_THRESHOLD]

Minimum severity level for including a drift finding in the report

warning

Enum check: must be one of 'info', 'warning', 'critical'. Reject if not in the allowed set. Controls report verbosity.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Dependency Drift Detection Prompt into an automated scanning workflow with validation, retries, and human review gates.

The Dependency Drift Detection Prompt is designed to run as a periodic batch job, not a one-off chat interaction. You should wire it into a scheduled pipeline (e.g., a CI/CD cron job, a GitHub Actions workflow, or an internal platform task runner) that executes weekly or per-release. The harness must collect three inputs before each run: the declared dependency manifest (e.g., package.json, requirements.txt, Cargo.toml), the actual import graph extracted from the codebase via a static analysis tool (e.g., depcruise, madge, pydeps), and a set of [DRIFT_RULES] that define what constitutes a violation (e.g., 'undeclared production dependency is a HIGH severity drift', 'stale declaration unused for >90 days is MEDIUM'). The prompt itself should never scrape the codebase; the harness is responsible for producing a clean, structured diff between declared and actual dependencies before the model ever sees it.

Build the harness with a three-stage pipeline: Extract, Detect, and Report. In the Extract stage, run your static analysis tool to produce a machine-readable dependency graph (JSON or CSV) and parse your manifest files into the same format. Compute a mechanical diff that identifies three categories: declared_but_unused, used_but_undeclared, and version_mismatch. This diff is the [DEPENDENCY_DIFF] input to the prompt. In the Detect stage, call the LLM with the prompt template, passing the diff, the [CODEBASE_CONTEXT] (repository name, primary language, build system), and the [DRIFT_RULES]. Configure your model client with temperature=0 and a low top_p value to maximize deterministic output. Set a timeout of 30 seconds and implement a retry strategy: one immediate retry on 5xx or timeout, then a single retry with exponential backoff (2s delay) on malformed JSON output. If the second retry also produces invalid JSON, log the raw response and escalate to a human reviewer rather than silently failing.

The model output must conform to a strict JSON schema. Implement a post-processing validator that checks: every drift item has a non-empty dependency_name, drift_type is one of the allowed enum values (undeclared_usage, stale_declaration, version_drift), severity is one of HIGH, MEDIUM, LOW, and every evidence field contains at least one file path that can be verified against the repository. If validation fails, do not silently accept the output. Route the failure to a dead-letter queue for manual inspection. For high-severity drifts (undeclared production dependencies, stale declarations in security-critical packages), the harness should automatically open a ticket in your issue tracker (e.g., Jira, GitHub Issues) with the drift details and evidence paths pre-populated. For medium and low drifts, append the findings to a running drift log that the team reviews during sprint planning.

Choose your model based on the complexity of your dependency graph. For repositories with fewer than 100 dependencies, a fast model like claude-3-haiku or gpt-4o-mini is sufficient and cost-effective. For monorepos or projects with 200+ dependencies and complex version ranges, use a more capable model like claude-3.5-sonnet or gpt-4o to reduce false positives in drift classification. Always log the model version, prompt version, and input hash alongside each run's output. This audit trail is essential when a team member questions why a dependency was flagged—you can replay the exact run. Store results in a structured format (e.g., a database table or a JSON log file) so you can track drift trends over time. A dashboard showing drift count by severity and by sprint gives engineering leads a leading indicator of dependency hygiene decay before it causes a production incident.

Avoid running this prompt on every commit. Dependency drift detection is a trend analysis tool, not a per-PR gate. Running it too frequently generates noise and desensitizes the team to drift alerts. Instead, schedule it weekly or align it with your release cadence. Also avoid the temptation to auto-fix drifts. The prompt identifies problems; it does not have the context to decide whether an undeclared dependency is intentional (e.g., a peer dependency provided by a parent project) or a stale declaration is kept for documentation purposes. Every drift item should require human triage. The harness's job is to surface the right information, at the right time, with enough evidence that a human can decide in under a minute.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structure, types, and validation rules for the Dependency Drift Detection Report. Use this contract to parse, validate, and integrate the model's output into automated scanning pipelines.

Field or ElementType or FormatRequiredValidation Rule

report_title

string

Must be exactly 'Dependency Drift Detection Report'.

scan_timestamp

ISO 8601 datetime string

Must parse to a valid datetime. Must be within the last 24 hours if the scan is part of an automated pipeline.

analysis_scope

object

Must contain a 'root_directory' string and a 'manifest_files' array of strings. Each string in 'manifest_files' must be a valid relative file path.

drift_instances

array of objects

Must be a JSON array. If empty, the report must include a 'no_drift_found' field set to true. Each object must conform to the 'drift_instance' schema below.

drift_instance.dependency_name

string

Must be a non-empty string matching the declared package name.

drift_instance.declared_version

string or null

If declared, must be a valid semantic version string. If null, indicates an undeclared dependency.

drift_instance.actual_version

string or null

If found, must be a valid semantic version string. If null, indicates a declared but unused dependency.

drift_instance.drift_type

enum string

Must be one of: 'STALE_DECLARATION', 'UNDECLARED_USAGE', 'VERSION_MISMATCH', 'MISSING_DEPENDENCY'.

drift_instance.evidence

array of objects

Must contain at least one object with 'file_path' (string) and 'line_number' (integer) fields. 'file_path' must be a relative path that exists in the repository context.

PRACTICAL GUARDRAILS

Common Failure Modes

Dependency drift detection fails silently in production when assumptions about the codebase, build system, or runtime environment are violated. These are the most common failure modes and how to guard against them before the report reaches an architect.

01

False Positives from Test-Only Imports

What to watch: The prompt flags undeclared dependencies that are only used in test files, leading to noise and alert fatigue. Guardrail: Pre-filter the dependency graph to exclude paths matching **/test/**, **/tests/**, **/spec/**, or a configurable exclusion list before passing the manifest to the model.

02

Stale Declaration Blindness in Monorepos

What to watch: The prompt misses stale declarations because it only compares declared vs. imported packages, ignoring that monorepo packages may declare dependencies they no longer use. Guardrail: Include a pre-processing step that extracts all internal import statements and cross-references them against the package.json dependencies list before the model sees the data.

03

Dynamic Import and Reflection Gaps

What to watch: The prompt cannot detect dependencies loaded via import(), require.resolve(), reflection, or plugin systems, producing an incomplete drift report. Guardrail: Augment static analysis with a runtime import trace or a known-dynamic-imports manifest. Flag any module with dynamic loading patterns as "unverified" in the output schema.

04

Version Range Resolution Mismatch

What to watch: The prompt treats a declared version range (e.g., ^2.1.0) as equivalent to the installed version, missing drift caused by lockfile resolution differences. Guardrail: Require the lockfile as a required input. Compare the resolved version from the lockfile against the declared range, and flag any resolution that pulls in a version outside the declared major/minor intent.

05

Transitive Dependency Confusion

What to watch: The prompt misclassifies a direct dependency as undeclared because it arrives via a transitive path, or vice versa, recommending unnecessary direct declarations. Guardrail: Build a full dependency tree before analysis. Classify each import as "direct" or "transitive" based on the caller's own manifest. Only flag undeclared usage when the importer does not declare the package and no direct dependency re-exports it.

06

Output Drift Across Scans

What to watch: Running the same prompt on the same codebase a week apart produces different severity classifications or inconsistent recommendations, eroding trust in automated governance. Guardrail: Pin the severity rubric in the prompt with explicit thresholds (e.g., "Critical: undeclared production dependency in >5 files"). Run the prompt against a golden dataset before each scan and fail the pipeline if classification consistency drops below 95%.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of a Dependency Drift Detection report before integrating it into a CI/CD pipeline or architecture governance dashboard. Each criterion maps to a pass standard, a failure signal, and a test method that can be automated.

CriterionPass StandardFailure SignalTest Method

Declared vs Actual Parity

Every entry in [DECLARED_MANIFEST] is matched to an import statement in [CODEBASE_SCAN] with identical version or a documented override

A declared dependency has no corresponding import (stale declaration) or an import has no declaration (undeclared usage) without an exception note

Parse output JSON; confirm stale_declarations and undeclared_usages arrays are empty or every entry includes a non-null exception_rationale

Version Drift Accuracy

For every dependency present in both sources, the version_delta field matches the semantic version difference between [DECLARED_MANIFEST] and [LOCK_FILE] or installed package metadata

A version delta is reported as null when both sources exist, or a delta is reported for a dependency that is pinned identically in both sources

Sample 5 dependencies from the output; compare version_delta against a scripted diff of manifest and lockfile for those packages

Source Grounding

Every finding in stale_declarations, undeclared_usages, and version_drifts includes a non-empty evidence object with declared_source_file, actual_source_file, and line_reference

A finding has an empty evidence object, a null line reference, or a file path that does not exist in [REPOSITORY_ROOT]

Validate output schema; for each finding, check that evidence.declared_source_file and evidence.actual_source_file resolve to real paths in the repository snapshot

Severity Classification Consistency

Every finding has a severity field set to critical, high, medium, or low matching the rules in [SEVERITY_RULES]: undeclared usage is at least high, stale declaration is at most medium, major version drift is critical

An undeclared production dependency is marked low, or a stale test-only dependency is marked critical

Validate severity against a lookup table of finding type and dependency scope; flag any mismatch for human review

False Positive Resistance

Test-only imports, dynamic imports with runtime guards, and type-only imports are not reported as undeclared usage unless they violate [STRICT_MODE] rules

A devDependency used only in test files appears in undeclared_usages, or a require inside an if block is flagged without noting the guard condition

Run the prompt against a repository with known test-only and guarded imports; confirm those imports do not appear in the output or appear with exception_rationale populated

Output Schema Validity

The output is valid JSON that conforms to [OUTPUT_SCHEMA] with all required fields present and no extra fields at the root level

JSON parsing fails, a required field like drift_summary or findings is missing, or an unexpected field appears at the root

Validate output with a JSON Schema validator using [OUTPUT_SCHEMA]; reject any output that fails validation before further processing

Drift Summary Correctness

The drift_summary.total_findings equals the sum of stale_declarations_count, undeclared_usages_count, and version_drifts_count, and drift_summary.risk_score is between 0 and 100

Counts do not add up, or risk_score is outside the 0-100 range

Compute expected counts from the findings array; assert equality with summary fields; assert risk_score is a number between 0 and 100

Actionability of Recommendations

Every finding in the remediation_plan array includes a concrete action (add_dependency, remove_dependency, update_version, or investigate_manual) and a target file path

A recommendation says review dependency without specifying which file to change, or suggests removing a dependency that is actively imported

Check that each remediation_plan entry has a non-null action from the allowed enum and a target_file that exists in [REPOSITORY_ROOT]

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single repository scan. Replace [PACKAGE_MANIFEST] with a hardcoded file path. Remove the [OUTPUT_SCHEMA] constraint and ask for a markdown table instead. Run against one project to validate the drift detection logic before adding automation.

code
Analyze [PACKAGE_MANIFEST] and [IMPORT_STATEMENTS] from [CODEBASE_PATH].
List every dependency where the declared version differs from the imported version.
Flag any import that has no corresponding declaration.
Return results as a markdown table.

Watch for

  • False positives from peer dependencies and transitive re-exports
  • Dev dependencies flagged as undeclared production usage
  • Monorepo symlinks and workspace protocols misinterpreted as drift
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.