# Circular Import & TDZ Surgeon

> Trace and cut circular imports, barrel-file cycles and TDZ crashes in TypeScript, JavaScript, Python and Go — 5 deterministic DAG patterns, patch-ready diffs, no lint ignores, plus a CI regression gate.

Circular Import & TDZ Surgeon is a paid AI agent skill on Agensi by Badung, in Code Quality & Review. It loads into your AI agent through the Agensi MCP server, always in its latest approved version.

- Price: $3.99 (one-time purchase)
- Creator: [Badung](https://www.agensi.io/creators/badung)
- Category: [Code Quality & Review](https://www.agensi.io/skills/code-quality-review)
- Version: 1.0
- Last updated: 2026-11-23
- Security: scan passed (2026-11-23); every new listing is also reviewed by a person
- Listing: https://www.agensi.io/skills/circular-import-tdz-surgeon
- Tags: code-review, api, typescript, python, refactoring, go, backend, circular-imports

## About this skill

Your app dies at startup with `ReferenceError: Cannot access 'UserService' before initialization`. Or FastAPI refuses to boot with `ImportError: cannot import name 'Order' from partially initialized module`. The cause is rarely the file you were editing — it is a cycle running through a barrel file, a class inheritance chain, or a type hint that was imported eagerly.

The usual fixes (disable `import/no-cycle`, add `# noqa`, cast to `any`, shuffle code until the error moves) hide the cycle and leave the next one to find you in production.

### What this skill does

It treats your imports as a dependency graph and operates on the graph, not on guesses.

- **Maps the exact loop** from the real `import` / `require` / `from ... import` lines you paste. You get the literal chain, for example `users/index.ts -> users/user.service.ts -> audit/audit.service.ts -> users/index.ts`.
- **Classifies every edge** as type-only, top-level value (executed at module load: `extends`, decorators, singletons) or deferred (used only inside a function), then rates the cycle CRITICAL / HIGH / MEDIUM by real runtime risk.
- **Cuts it with one of five deterministic patterns**, always picking the smallest DAG cut:
  - **C1 Type-only decoupling** — `import type`, `TYPE_CHECKING`, `from __future__ import annotations`
  - **C2 Shared leaf extraction** — move types, constants and pure helpers into a zero-dependency module both sides import
  - **C3 Dependency inversion** — a narrow interface in the lower layer, implemented at the composition root
  - **C4 Internal barrel bypass** — internal files import the leaf directly; `index.ts` stays for external consumers only
  - **C5 Controlled lazy boundary** — only a genuinely mutual runtime import moves inside the calling function, with the reason documented in the code
- **Delivers patch-ready diffs**, not advice: per-file `Before -> After` hunks with the new one-way graph spelled out, and public exports (`src/index.ts`, package `exports`, `__init__.py`) kept intact.
- **Hands you the regression gate**: `dpdm --circular`, `madge --circular`, ESLint `import/no-cycle`, Python `import-linter`, `go build ./...`, so the cycle cannot quietly come back.
### Guardrails it refuses to break

- No silencing: no `eslint-disable`, `# noqa`, `tsconfig` path hacks or blind `any` casts just to make the warning disappear.
- No public API breakage: the barrel that outside consumers depend on stays; cycles are cut inside the package by stopping internal files from importing through their own barrel.
- No unverified claims: if your build, test runner or cycle scanner cannot run in the session, the verification commands are marked `NOT RUN` and handed back to you verbatim.
- No over-engineering: a type-only cycle gets `import type`, not a dependency-injection rewrite.

### Stacks covered

- **TypeScript / ESM** — `ReferenceError: Cannot access 'X' before initialization` (TDZ), class inheritance and top-level singleton cycles
- **Node CommonJS** — imported symbol arrives as `undefined` or `{}` from a partially built `module.exports`
- **Next.js / Vite / Webpack** — internal modules importing through `index.ts` barrels, broken tree-shaking, slow HMR, `'use client'` bundle bleed
- **Python** — `ImportError: cannot import name ... from partially initialized module` in FastAPI, Django and SQLAlchemy model/schema layers
- **Go** — `import cycle not allowed`, fixed by extracting a shared contract package

### Who it is for

Developers inheriting a legacy codebase that crashes at boot, teams whose bundle quietly grew after a refactor, backend engineers fighting FastAPI or SQLAlchemy cycles, and reviewers who want a real DAG change instead of one more suppression comment.

One skill file, no install and no network: paste the error and the files involved, get the loop, the cut, the diff and the gate.

## Requires

- dpdm
- Node.js
- madge

Paste the error and the files in the cycle — no CLI or account needed. The dpdm / madge / import-linter commands in the output are optional checks for your own CI; when they cannot be run, the output marks them NOT RUN.

## Known limitations

Verification commands are marked as NOT RUN if the environment lacks the specific toolchain. Requires manual execution of generated CI gate commands for final validation.

## How to use this skill

1. Connect your AI agent to Agensi once: add the MCP server https://mcp.agensi.io/mcp/auth and sign in with your Agensi account (OAuth, no API key). Steps for Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and other agents: https://www.agensi.io/docs/mcp-setup
2. Ask your agent: "Use the Circular Import & TDZ Surgeon skill from Agensi" and describe your task.
3. Buy it on the listing or let your agent ask you first; your agent then loads it from Agensi when it needs it. Every paid skill has a money-back guarantee: https://www.agensi.io/docs/money-back-guarantee

## Frequently asked questions

### How does this skill differ from simply using lint-ignore or lazy imports to bypass errors?

This skill identifies the specific chain of files creating a loop and applies five architectural DAG (Directed Acyclic Graph) patterns, such as shared leaf extraction or dependency inversion, to permanently restructure the code rather than just hiding the error.

### Which programming languages and frameworks can this skill handle?

The Circular Import Surgeon is compatible with TypeScript (ESM/CommonJS), JavaScript, Python (including FastAPI and Django), and Go environments.

### What information do I need to provide for the skill to begin the refactoring process?

Simply provide your build error logs and the contents of the files involved; the skill then generates a Cycle Inventory Table and the specific diffs needed to fix the architecture.

### Can I use the output of this skill to set up automated gates in my CI/CD pipeline?

Yes, the skill provides specific verification commands compatible with tools like dpdm, madge, and import-linter so you can integrate the fix into your CI/CD pipeline and prevent future regressions.

### Will the refactoring process break my public API or existing barrel file exports?

The skill is designed to recognize and preserve your existing public entrypoints, such as index.ts or __init__.py files, ensuring that your external API remains stable while the internal structure is cleaned up.

---

Source: [Agensi](https://www.agensi.io), the marketplace of skills for AI agents. Any MCP-compatible agent (Claude, ChatGPT, Claude Code, Codex, Cursor, VS Code and more) connects at https://mcp.agensi.io/mcp/auth and signs in with an Agensi account; setup for every agent: https://www.agensi.io/docs/mcp-setup. Append .md to any skill, guide or docs address on agensi.io for its markdown version.
