Vibe Coding
Dev ArchitectureProduction86% · Ready

Progressive Refactoring of a Legacy TypeScript Monorepo: Non-Breaking Rules and Boundary Locking Strategy

Achieving 86% completion in type strictness and dependency decoupling through path-scoped rules and unit test regression constraints, ensuring zero-downtime merges.

Est. time: 2 hUpdated: 2026-11-26
Cursor IDEpnpm / TurborepoTypeScript StrictVitest.cursor/rules
Progressive Refactoring of a Legacy TypeScript Monorepo: Non-Breaking Rules and Boundary Locking Strategy

Completion Score

The 86% completion rate indicates that AI excels in type completion, dependency graph mapping, and unit test generation, efficiently handling repetitive refactoring tasks. However, for complex business logic decoupling, cross-package contract changes, and large PR splitting strategies, AI still requires deep human intervention to ensure business semantic correctness.

86%Ready

Dimension breakdown

Cross-Package Dependency Graph Mapping90%

AI efficiently parses `package.json` and `tsconfig.json` path aliases to generate accurate dependency graphs, but implicit dependencies require human confirmation.

Strict Type Completion and Migration88%

AI excels at replacing `any` with specific types or `unknown`, but complex generic inference and business-semantic types require manual fine-tuning.

Regression Unit Tests and Behavioral Consistency84%

AI can generate basic unit tests, but boundary conditions and exception path coverage require manual supplementation to ensure behavioral consistency.

Large PR Splitting and Zero-Downtime Merging80%

AI can identify refactoring boundaries, but large PR splitting strategies and merge conflict resolution require manual planning to ensure zero downtime.

Human checkpoint

Before merging any PR involving public API changes in `packages/core` or `packages/api-client`, an architect must review type signature changes and downstream impact scope. All `@ts-expect-error` comments and `any` type usages must be confirmed for necessity and safety via Code Review.

Upgrade / downgrade path

If hardware resources are constrained, downgrade to strict type checking for core packages only, keeping non-core packages in loose mode. If budget is tight, reuse existing test cases and write unit tests only for new logic, rather than performing full regression.

When to use & prerequisites

Ideal for large TS monorepo teams with 50+ internal packages and codebases exceeding 100,000 lines. The environment requires pre-installed pnpm, Turborepo, and Vitest, with CI/CD pipelines configured for type checking and unit test gates. Best suited for legacy code modernization, technical debt cleanup, and new architecture migration scenarios.

Ready-to-copy configs

.cursor/rules/monorepo-boundaries.mdcmarkdown

定义 Monorepo 中跨包依赖的只读契约与禁止修改的边界文件,防止 AI 意外破坏公共 API。

---
alwaysApply: true
---

# Monorepo 边界与依赖规则

## 1. 依赖方向约束
- **禁止**:`packages/app` 直接依赖 `packages/core` 的内部实现(`src/` 下的非导出文件)。
- **允许**:仅通过 `packages/core` 的 `index.ts` 导出的公共 API 进行交互。
- **禁止**:在 `packages/shared` 中引入任何 UI 框架或业务逻辑依赖。

## 2. 只读契约文件 (Read-Only Contracts)
以下文件被视为“契约”,AI 不得直接修改其导出签名,除非用户明确指令:
- `packages/core/src/types/index.ts`
- `packages/api-client/src/contracts.ts`
- `packages/shared/src/constants.ts`

若需修改上述文件,必须先在 PR 描述中说明破坏性变更(Breaking Change)及迁移方案。

## 3. 类型严格性
- 所有新代码必须遵循 `strict: true` 配置。
- 禁止使用 `any` 类型,除非有明确的 `// @ts-expect-error` 注释并附带原因说明。
- 优先使用 `unknown` 并进行类型收窄(Type Narrowing)。

## 4. 依赖管理
- 新增依赖必须通过 `pnpm add` 命令,禁止手动编辑 `package.json`。
- 内部包依赖必须使用 `workspace:*` 协议。
- 禁止在 `package.json` 中硬编码版本号,应使用 `^` 或 `~` 范围。

## 5. 测试约束
- 修改任何 `src/` 下的文件,必须同步更新或新增对应的 `*.test.ts` 文件。
- 测试文件必须位于 `__tests__` 目录或同级目录下,命名为 `*.test.ts`。
- 禁止在测试中 mock 内部模块,应使用集成测试验证行为一致性。
.cursor/skills/safe-refactor/SKILL.mdmarkdown

指导 AI 执行渐进式重构的技能文件,包含分步验证、回滚策略及单测回归检查流程。

---
name: safe-refactor
description: 执行安全的渐进式重构,确保类型收严与依赖解耦不破坏现有功能。
---

# Safe Refactor Skill

## 核心原则
1. **小步快跑**:每次重构只处理一个模块或一个函数。
2. **测试先行**:在修改代码前,确保现有测试覆盖关键路径。
3. **类型驱动**:利用 TypeScript 编译器错误作为重构指南。
4. **零中断**:保持公共 API 兼容,避免破坏下游依赖。

## 执行流程

### 1. 预检查 (Pre-check)
- 运行 `pnpm run type-check` 确认当前基线无类型错误。
- 运行 `pnpm run test:unit` 确认所有单元测试通过。
- 识别目标模块的依赖图谱,列出所有导入/导出关系。

### 2. 重构执行 (Refactor)
- **类型收严**:将 `any` 替换为具体类型或 `unknown`,添加必要的类型断言。
- **依赖解耦**:将内部实现细节封装,仅暴露必要的公共接口。
- **代码提取**:将复杂逻辑提取为独立函数或类,提高可测试性。

### 3. 后验证 (Post-verify)
- 运行 `pnpm run type-check` 确保无新增类型错误。
- 运行 `pnpm run test:unit` 确保所有测试通过。
- 运行 `pnpm run lint` 确保代码风格一致。

### 4. 回滚策略 (Rollback)
- 若验证失败,立即回滚到上一个提交。
- 分析失败原因,调整重构策略后重试。
- 若多次失败,暂停重构并请求人工介入。

## 示例 Prompt
"请重构 `packages/core/src/utils.ts` 中的 `parseData` 函数,将其类型从 `any` 收严为 `unknown`,并添加类型收窄逻辑。确保不改变函数行为,并更新对应的单元测试。"

AI Vibe Coding in 4 steps

  1. 1

    Dependency Graph Audit and Boundary Locking

    Goal: Generate a cross-package dependency graph, identify implicit dependencies, and lock public API boundaries.

    Prompt
    Analyze the dependency relationship between `packages/core` and `packages/app` and generate a dependency graph. Identify all implicit dependencies (e.g., packages imported via `tsconfig` path aliases but not declared in `package.json`). List all functions and types in `packages/core` directly imported by `packages/app`, mark them as 'Public API', and generate a list of read-only contract files in `.cursor/rules/monorepo-boundaries.mdc`.

    Verify: Run `pnpm run dep-check` to confirm no implicit dependency warnings; check if `.cursor/rules/monorepo-boundaries.mdc` includes all identified public API file paths.

  2. 2

    Type Strictness and `any` Elimination

    Goal: Replace `any` types in target modules with specific types or `unknown`, and add type narrowing logic.

    Prompt
    Refactor the `parseData` function in `packages/core/src/utils.ts`, tightening its parameter type from `any` to `unknown`. Add type narrowing logic to handle different input types. Ensure function behavior remains unchanged and update corresponding unit tests to cover new type branches.

    Verify: Run `pnpm run type-check` to confirm no new type errors; run `pnpm run test:unit -- --filter=core` to confirm all unit tests pass.

  3. 3

    Dependency Decoupling and Internal Implementation Encapsulation

    Goal: Encapsulate internal implementation details, exposing only necessary public interfaces to reduce cross-package coupling.

    Prompt
    Refactor `packages/core/src/services.ts` by encapsulating `UserManager` class internal methods as private, exposing only public interfaces via `index.ts`. Remove direct calls to `UserManager` internal methods in `packages/app`, replacing them with interactions through public interfaces. Ensure business logic remains unchanged and update relevant tests in `packages/app`.

    Verify: Run `pnpm run type-check` to confirm no type errors; run `pnpm run test:unit -- --filter=app` to confirm `packages/app` tests pass; check if `packages/core/src/index.ts` exports only public interfaces.

  4. 4

    Large PR Splitting and Zero-Downtime Merge Verification

    Goal: Split refactoring tasks into multiple small PRs, ensuring each PR is independently mergeable with no downtime risk.

    Prompt
    Split the above refactoring tasks into 3 independent PRs: 1) Type strictness; 2) Dependency decoupling; 3) Test updates. Generate detailed change descriptions and rollback strategies for each PR. Ensure that after merging each PR, `pnpm run type-check` and `pnpm run test:unit` pass, with no breaking changes.

    Verify: Check if the generated 3 PR descriptions include change descriptions and rollback strategies; simulate merging each PR, run `pnpm run type-check` and `pnpm run test:unit` to confirm no errors.

Pitfalls & fixes

  • Undeclared implicit dependencies: AI may ignore packages imported via `tsconfig` path aliases but not declared in `package.json`. Fix: Enforce in `.cursor/rules` that all dependencies must be explicitly declared in `package.json`, and run `pnpm run dep-check` to verify.
  • Over-narrowing types: AI may overuse `as` assertions, reducing type safety. Fix: Prohibit `as` assertions in Rules unless accompanied by a clear `// @ts-expect-error` comment with a reason.
  • Insufficient test coverage: AI-generated unit tests may only cover happy paths, ignoring boundary conditions. Fix: Explicitly require coverage of boundary conditions and exception paths in Prompts, and manually review test cases.

FAQ

How to handle existing `any` types in `packages/core`?

Prioritize replacing `any` with `unknown` and adding type narrowing logic. If the specific type cannot be determined, retain `any` and add a `// TODO: replace with specific type` comment, replacing it gradually later.

How to ensure refactoring does not break downstream dependencies?

Lock public API boundaries via `.cursor/rules`, prohibiting AI from modifying read-only contract files. Before merging, run `pnpm run test:unit` and `pnpm run type-check` to ensure all downstream package tests pass.

After splitting large PRs, how to ensure each PR is independently mergeable?

Each PR should contain only one refactoring dimension (e.g., type strictness or dependency decoupling) and include complete test updates. Before merging, simulate merging each PR, run type checks and unit tests to ensure no conflicts or errors.

Related blueprints

Progressive Refactoring of a Legacy TypeScript Monorepo: Non-Breaking Rules and Boundary Locking Strategy · CursorHome