Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Angular Migrator — AI-Powered Multi-Agent Migration System

An intelligent, multi-agent system that automates Angular version migrations using DeepSeek AI via LangChain. It scans your project, plans the migration, resolves dependencies, detects deprecated APIs, rewrites your source code, validates the results, and auto-fixes validation errors by routing them back to the responsible agent — all coordinated through a 6-phase orchestration pipeline with human-in-the-loop approval gates and an intelligent fix loop.


Table of Contents


Architecture Overview

The system follows a centralized multi-agent orchestration pattern built around an immutable state machine. A single OrchestratorAgent runs a 6-phase sequential pipeline, delegating each phase to a specialized agent. Each agent receives the current MigrationState, performs its work, and returns a partial state patch that gets merged back. State is immutable — every mutation produces a new object via mergeState().

All agents share a single DeepSeekChatClient (wrapping LangChain's ChatDeepSeek), which is the sole AI interface. The system uses DeepSeek Coder (temperature 0.05–0.1) for precise, deterministic outputs.

Phase 5 (Validation) contains a closed-loop auto-fix system: when validation detects errors, they are classified by type and routed back to the responsible agent (PackageMigrationAgent or MigrationAgent). Each agent has a fixErrors() method that uses AI with error-specific context to correct the issues. Validation then re-runs to verify the fixes, with the loop continuing until all errors are resolved or a maximum of 3 attempts is reached.

A human-in-the-loop approval gate exists at Phase 1 (planning) — the user must explicitly approve the generated migration plan before any changes are applied.


System Architecture Diagram

┌──────────────────────────────────────────────────────────────────────────────┐
│                              CLI (cli.ts)                                     │
│                       Interactive prompts for config                           │
└──────────────────────────────┬───────────────────────────────────────────────┘
                               │ CliOptions
                               ▼
┌──────────────────────────────────────────────────────────────────────────────┐
│                         OrchestratorAgent                                     │
│                      (orchestrator_agent.ts)                                   │
│                                                                                │
│  ┌──────────────────────────────────────────────────────────────────────┐    │
│  │                     Migration Pipeline (6 Phases)                      │    │
│  │                                                                       │    │
│  │  Phase 0 ──► Phase 1 ──► Phase 2 ──► Phase 3 ──► Phase 4 ──► Phase 5│    │
│  │  Discovery   Planning    Package     Code        Code       Validation│    │
│  │  Agent       Agent       Migration   Analysis    Migration  & Fix    │    │
│  │             (👤 approval  Agent       Agent       Agent      Loop     │    │
│  │              gate)                                        ┌────────┐ │    │
│  │                                                           │Auto-Fix│ │    │
│  │                                                           │ Loop   │ │    │
│  │                                                           │        │ │    │
│  │                                              ┌────────────┤Errors?─│ │    │
│  │                                              │            │ │  │   │ │    │
│  │                                              │            │ ▼  ▼   │ │    │
│  │                                              │   ┌────────┴─┐┌───┴─┐│    │
│  │                                              │   │Package   ││Migr-││    │
│  │                                              │   │Agent     ││ation││    │
│  │                                              │   │.fixErr() ││Agent││    │
│  │                                              │   │          ││.fix-││    │
│  │                                              │   │          ││Err()││    │
│  │                                              │   └────┬─────┘└──┬──┘│    │
│  │                                              │        └───┬────┘    │    │
│  │                                              │            │         │    │
│  │                                              └── Re-validate ──────┘    │
│  └──────────────────────────────────────────────────────────────────────┘    │
│                                                                                │
│  Central State: MigrationState (immutable, merged at each phase)               │
└──────────────────────────────────────────────────────────────────────────────┘
                               │
          ┌────────────────────┼──────────────────────────────┐
          ▼                    ▼                              ▼
┌─────────────────┐  ┌─────────────────┐  ┌───────────────────────────────┐
│ DiscoveryAgent  │  │ PlannerAgent    │  │ ValidationEngine              │
│                 │  │                 │  │                               │
│ • FS scanner    │  │ • Fetches       │  │ • PackageValidator ── AI+CLI  │
│ • Structure     │  │   update.angu-  │  │ • CompatibilityChecker ── AI  │
│   classifier    │  │   lar.io data   │  │ • CodeValidator ── AI+static │
│ • AI risk       │  │ • Generates     │  │ • TypeChecker ── tsc --noEmit│
│   assessment    │  │   step-by-step  │  │ • BuildValidator ── ng build  │
│                 │  │   plan          │  │                               │
│                 │  │ • Human         │  │ + ValidationReporter          │
│                 │  │   approval      │  │   → validation-report.md      │
└─────────────────┘  └─────────────────┘  └───────────────────────────────┘
          │                                       │
          ▼                                       ▼
┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐
│ AnalysisAgent   │  │ DeprecationAgent│  │ MigrationAgent  │
│                 │  │                 │  │                 │
│ • Orchestrates  │  │ • Builds AI     │  │ • AI rewrites   │
│   deprecation   │  │   deprecation   │  │   source files  │
│   scan          │  │   catalogue     │  │ • Shows diffs   │
│ • Generates     │  │ • Per-file AI   │  │ • Creates .back-│
│   markdown      │  │   scan          │  │   up files      │
│   report        │  │ • Caching       │  │ • fixErrors()   │
└─────────────────┘  └─────────────────┘  │   for re-migra- │
          │                                │   tion with err │
          ▼                                │   context       │
┌─────────────────┐                        └─────────────────┘
│ PackageAgent    │
│                 │
│ • AI resolves   │
│   compatible    │
│   versions      │
│ • Writes        │
│   package.json  │
│ • fixErrors()   │
│   for version   │
│   correction    │
└─────────────────┘

Agents

OrchestratorAgent

File: src/agents/orchestrator/orchestrator_agent.ts

Role: Central coordinator and pipeline executor.

The OrchestratorAgent is the entry point of the system. It:

  • Initializes all sub-agents (6 agents + validation engine + 5 validators) with shared AI client
  • Creates the initial MigrationState via createInitialState()
  • Executes the 6-phase pipeline sequentially, checking state.halted before each phase
  • Merges state patches from each agent back into the central state
  • Handles the planning approval gate — if the user rejects the plan, the pipeline stops gracefully
  • Runs the validation → fix → re-validate loop in Phase 5, routing errors to the responsible agent
  • Prints a comprehensive summary at the end (complexity, risks, plan steps, files changed, validation status, fix attempts, duration)

Key Design Decisions:

  • Each agent is instantiated once and reused (no per-run overhead)
  • The pipeline is linear and sequential — each phase depends on the previous phase's output
  • Error handling: if any agent sets halted: true, subsequent phases are skipped
  • Validation fix loop: errors from package-validator / compatibility-checker route to PackageMigrationAgent.fixErrors(); errors from code-validator / type-checker / build-validator route to MigrationAgent.fixErrors() with a max of 3 attempts

DiscoveryAgent

File: src/agents/discovery_agent.ts

Role: Deep-scan the Angular project and assess migration complexity.

The DiscoveryAgent is the first agent to run. It performs both filesystem analysis and AI-assisted risk assessment.

Filesystem Capabilities:

  • Recursive directory scanner (scanDirectory): walks the project tree up to 8 levels deep, skipping node_modules, dist, .git, .angular, coverage, and other non-source directories
  • File classifier (classifyFile): categorizes each file as component, service, module, directive, pipe, template, style, spec, or other based on naming conventions
  • Structural detectors: finds angular.json, all tsconfig*.json files, lazy-loaded modules (files containing loadChildren/loadComponent), and standalone components (files with standalone: true)
  • Framework detector (detectFrameworks): reads package.json and detects RxJS, NgRx, Angular Material, Angular CDK, AngularFire, ngx-translate, ng-bootstrap, PrimeNG, ngx-charts, and Apollo GraphQL
  • Angular version detector: parses @angular/core version from package.json
  • Linting config checker: detects ESLint and TSLint configurations

AI Capabilities:

  • Sends the complete scan data to DeepSeek for risk assessment
  • AI returns a structured JSON with estimated complexity (low/medium/high), specific migration risks, key observations, and a recommended approach
  • The AI guidance considers version jump magnitude, detected frameworks, file counts, and project structure

Output to State:

  • currentAngularVersion, projectStructure, detectedFrameworks, discoverySummary
  • Appends risks as warnings

PlannerAgent

File: src/agents/planner_agent.ts

Role: Generate a structured, step-by-step migration plan with human approval.

The PlannerAgent is the strategic brain of the system. It combines official Angular documentation with AI reasoning.

Key Capabilities:

  • Fetches Angular's official update guide from https://update.angular.io/data.json via HTTPS
    • Parses the JSON response and extracts steps relevant to the specific version range
    • Falls back to a built-in generic guide if the fetch fails (network issues, redirect loops, etc.)
    • Handles HTTP redirects (301/302) automatically
  • AI plan generation: sends project context (version range, frameworks, complexity, risks, dependency map, file types, lazy-loaded modules, standalone components, and the official update guide) to DeepSeek
  • Structured plan parsing: AI returns a JSON array of MigrationStep objects, each with a unique step ID, order, description, categorizing agent (package/code/config/test), CLI command, affected files, breaking change flag, approval requirement, and rollback command
  • Fallback plan: if AI returns an empty or invalid response, generates a minimal 2-step plan (update packages → fix deprecated code)

Human-in-the-Loop Gate:

  • After generating the plan, the agent displays it in a formatted table with color-coded tags ([BREAKING], [REVIEW])
  • The plan is saved to migration-plan.json in the project directory
  • The user is prompted: "Proceed with migration? (y/n)"
  • If rejected, the pipeline halts with planApproved: false and halted: true
  • Breaking changes are highlighted in red before the prompt for informed decision-making

PackageMigrationAgent

File: src/agents/package_agent.ts

Role: Resolve compatible package versions and update package.json.

The PackageMigrationAgent handles the dependency side of migration. It uses AI to determine the correct target version for every package.

Key Capabilities:

  • Reads package.json and detects the current Angular version
  • AI version resolution (resolveTargetVersions): sends ALL current dependencies to DeepSeek and asks it to return compatible versions for the target Angular release
    • Rules encoded in the prompt: Angular packages get exact compatible versions, TypeScript gets the required version, RxJS/zone.js get compatible versions, third-party packages get compatible versions, unrelated packages keep their current version
    • AI returns structured JSON with dependencies and devDependencies maps
  • Generates a human-readable migration plan summary (display-only, for user awareness)
  • Breaking change detection: compares major version numbers between current and target — any major version bump is flagged as breaking
  • Package.json update: creates a .backup file, applies version changes, updates npm scripts (ng, start, build, test)
  • Dry-run mode: displays what would change without writing to disk
  • fixErrors(state, errors): called by the orchestrator's auto-fix loop to re-resolve package versions when validation finds incompatibilities. Sends error context to AI for targeted version correction, updates package.json and dependencyMap

AnalysisAgent

File: src/agents/analysis_agent.ts

Role: Orchestrate deprecated API scanning across the entire project.

The AnalysisAgent is a thin orchestration layer that delegates to DeprecationAgent for the actual scanning. It focuses on reporting and state management.

Key Capabilities:

  • Delegates to DeprecationAgent.analyzeProject() for the core analysis
  • Displays results in a structured format with color-coded severity levels
  • Generates a comprehensive markdown report (migration-report.md) containing:
    • Summary statistics (total files, files needing attention, total deprecated usages)
    • Per-file tables with API name, version, severity, and replacement for each issue
  • Passes file analysis results to downstream agents (specifically MigrationAgent) by serializing them into state.warnings
  • Also exposes detectCurrentVersion() and analyzeFiles() as direct utility methods

DeprecationAgent

File: src/agents/deprecation_agent.ts

Role: Build an AI-powered deprecation catalogue and scan files for deprecated API usage.

The DeprecationAgent is the most AI-intensive agent. It performs a two-stage process: first building a catalogue of all deprecated APIs for the version range, then scanning each file.

Key Capabilities:

Stage 1 — Deprecation Catalogue:

  • Asks DeepSeek to generate a complete list of ALL deprecated, removed, or changed Angular APIs between the source and target versions
  • The AI returns a JSON array of DeprecationCatalogueEntry objects, each with an exact searchable string (api), the Angular version of deprecation, severity level (removed/deprecated/changed), and replacement guidance
  • Caching: the catalogue is cached in-memory keyed by version range (fromVersion-toVersion), so multiple files don't trigger redundant AI calls
  • AI is instructed to return at minimum 10 items per major version jump
  • Prompt covers ALL Angular packages: core, router, forms, common, platform-browser, etc.
  • Includes template syntax changes (e.g., *ngIf@if)

Stage 2 — Per-File Scanning:

  • Walks the src/ directory recursively, finding all .ts files (excluding .spec.ts)
  • Pre-filtering optimization: only sends files to AI that contain at least one string from the deprecation catalogue — clean files skip the AI round-trip
  • For each candidate file, sends the full file content to DeepSeek with the version range for precise deprecation detection
  • AI returns a JSON array of DeprecatedUsage objects with the exact API, line number, version, severity, and replacement
  • Files are processed sequentially with a 500ms delay to respect API rate limits
  • Each file receives a colored status indicator: green "clean" or red with issue count

Additional Features:

  • Extracts all imports from each file for framework detection
  • Classifies files by Angular type (component, service, module, directive, pipe)
  • Detects frameworks from import patterns

MigrationAgent

File: src/agents/migration_agent.ts

Role: AI-powered source code rewriting to fix deprecated API usages.

The MigrationAgent is the execution agent that actually modifies source code. It reads file analyses from the previous phase and rewrites files using AI.

Key Capabilities:

  • Extracts file analyses from state warnings (serialized by AnalysisAgent)
  • Constructs a breaking changes list from all deprecated usages across all files (deduplicated)
  • Sequential file migration: processes each file one at a time with a 1-second delay between files
  • For each file, sends the original content plus the list of breaking changes to DeepSeek
  • AI returns the fully migrated TypeScript code (the prompt instructs it to preserve business logic, comments, variable names, and only update Angular-specific code)
  • Response cleaning (cleanGeneratedCode): strips markdown code fences and trims any non-code text before the first import/export/decorator/class/function declaration
  • Diff preview: shows line-by-line diffs with - (removed) in red and + (added) in green
  • Dry-run mode: displays changes without writing files
  • Live mode: creates .backup copies, then writes migrated code to the original files
  • Tracks linesChanged count per file for the summary

Direct Methods:

  • migrateFile() — migrate a single file (usable standalone)
  • migrateFiles() — batch migrate multiple files (used by the orchestrator)
  • fixErrors(state, errors) — called by the orchestrator's auto-fix loop to re-migrate specific files when validation finds code/type/build errors. Groups errors by file, sends each to AI with the current (broken) code, original code, and specific error details for targeted fixes. Updates fileChanges and writes to disk (creates .fix-backup copies)

Validation Engine

File: src/validators/validation-engine.ts

Role: Run all validators, aggregate results, compute overall status, and generate reports.

The ValidationEngine implements a Validator interface ({ name, validate(state) → ValidatorResult }) and coordinates 5 specialized validators. It is instantiated by the OrchestratorAgent with the shared DeepSeek client and runs during Phase 5.

Key Capabilities:

  • Runs all validators sequentially, measuring duration per validator
  • Computes an overall status: pass if all pass, fail if any fail, warn if any warn, skipped if all skipped
  • Prints a color-coded per-validator result line with status icon and duration
  • Delegates to ValidationReporter for console summary and markdown report generation
  • Updates buildSuccess, testSuccess, lintSuccess flags from validator results
  • Returns validationReport, validatorResults, and sets halted: true if critical errors found

Validator Interface:

interface Validator {
  readonly name: string;
  validate(state: MigrationState): Promise<ValidatorResult>;
}

PackageValidator

File: src/validators/package-validator.ts

Role: Validate that resolved package versions are correct and compatible.

Checks performed:

  • Static checks: verifies package.json exists and is valid JSON; checks all @angular/* packages share the same major version as the target; validates TypeScript version meets minimum requirements for the target Angular
  • AI compatibility check: sends the full dependency map to DeepSeek for peer dependency conflict detection and version compatibility validation
  • npm install simulation: runs npm install --dry-run and parses output for ERESOLVE errors, 404s, and other installation failures
  • Gracefully handles missing npm CLI

CompatibilityChecker

File: src/validators/compatibility-checker.ts

Role: Verify cross-ecosystem compatibility for all dependencies.

Checks performed:

  • Node.js version: compares current Node.js against Angular's minimum requirement (v15→Node 16, v17+→Node 18, v19+→Node 20)
  • Framework matrix: validates Angular Material, CDK, NgRx versions against the target Angular major; verifies RxJS version compatibility (v7+ required for Angular 16+)
  • Zoneless detection: for Angular 18+, notes that zone.js may not be needed with zoneless change detection
  • AI cross-compatibility: sends all dependencies to DeepSeek for comprehensive compatibility analysis, including Node.js and TypeScript version recommendations

CodeValidator

File: src/validators/code-validator.ts

Role: Validate migrated TypeScript code for correctness.

Checks performed:

  • AI per-file review: for each migrated file, sends the original and migrated content to DeepSeek with version context for detailed review — AI checks for remaining deprecated APIs, correct imports, valid template syntax, preserved business logic, and correct decorator options
  • Static pattern checks: scans migrated code for known deprecated patterns (entryComponents, @angular/http, @ViewChild({ static: false }), Renderer2)
  • Safety checks: detects empty output files (when original had content), invalid import statements containing undefined or null
  • File existence: verifies all migrated files still exist on disk

TypeChecker

File: src/validators/type-checker.ts

Role: Run TypeScript compiler checks on migrated code.

Checks performed:

  • tsc --noEmit: runs the TypeScript compiler in check-only mode using the project's tsconfig.json
  • Error parsing: parses both TS error formats (file.ts(12,5): error TS2345: and file.ts:12:5 - error TS2345:)
  • Import validation: checks for removed packages (@angular/http) and changed APIs (TestBed.initTestEnvironment)
  • Smart suggestions: maps known TS error codes (TS2304, TS2307, TS2339, TS2345, TS2554, TS2740, TS2769) to Angular-specific fix suggestions
  • Gracefully handles missing tsc CLI

BuildValidator

File: src/validators/build-validator.ts

Role: Run Angular production build to verify compilation succeeds.

Checks performed:

  • angular.json detection: skips if no angular.json found (not an Angular project)
  • ng build: runs ng build --configuration production via local node_modules/.bin/ng or npx fallback
  • Error parsing: parses Angular build error format (Error: src/app/file.ts:12:5 - message) and generic ERROR lines
  • Warning capture: captures WARNING lines from build output
  • Handles missing ng CLI gracefully

ValidationReporter

File: src/reporters/validation-reporter.ts

Role: Generate console output and markdown/JSON reports from validation results.

Key Capabilities:

  • Console summary: prints each validator's result with color-coded status icons (✅ PASS, ❌ FAIL, ⚠️ WARN, ⊙ SKIPPED), duration, and summary; shows up to 3 most severe inline issues per validator; displays total stats (errors, warnings, info, duration)
  • Markdown report (validation-report.md): generates a full report with summary table, per-validator results with severity-badged issue tables, and actionable "Action Items" sections grouped by errors and warnings
  • JSON report: generates machine-readable JSON with all timestamps, issues, and metadata for programmatic consumption
  • Falls back to writing to CWD if project directory is not writable

Auto-Fix Loop

The orchestrator's Phase 5 implements a closed-loop validation → fix → re-validate cycle that automatically corrects detected errors.

Error Classification & Routing

The classifyValidationErrors() method in the orchestrator inspects each validator's results and routes errors to the responsible agent:

Validator Error Type Routed To Fix Method
package-validator Version mismatches, peer conflicts, npm install failures PackageMigrationAgent fixErrors() — AI re-resolves package versions with error context
compatibility-checker Framework incompatibilities, Node/TS version issues PackageMigrationAgent fixErrors() — AI corrects incompatible version combinations
code-validator Remaining deprecated APIs, malformed code, empty output MigrationAgent fixErrors() — AI re-migrates specific files with error details
type-checker TS type errors (TS23xx), import errors, API signature mismatches MigrationAgent fixErrors() — AI fixes type errors in specific files
build-validator Angular compilation errors, build warnings MigrationAgent fixErrors() — AI fixes build-breaking code issues

Fix Methods

PackageMigrationAgent.fixErrors(state, errors):

  1. Reads current package.json
  2. Builds error context from validation issues (message, code, suggestion)
  3. Sends AI prompt with: target Angular version, current dependency map, original package.json, and specific errors
  4. AI returns corrected versions only for the problematic packages
  5. Merges corrections into dependencyMap and writes package.json (unless dry-run)

MigrationAgent.fixErrors(state, errors):

  1. Groups validation errors by file
  2. For each file, reads the current (broken) migrated content and original content
  3. Sends AI prompt with: version range, specific errors to fix (with line numbers and suggestions), original code, and current code
  4. AI returns fixed code with only the errors addressed
  5. Updates fileChanges, writes to disk with .fix-backup safety copy (unless dry-run)

Loop Behavior

┌─────────────────────────────────────────────────────┐
│                  Phase 5 Loop                        │
│                                                      │
│  while (fixAttempt < 3) {                            │
│    1. Run all 5 validators                           │
│    2. If pass or 0 errors → BREAK (done)            │
│    3. Extract errors/warnings                        │
│    4. Detect no-progress (same errors) → BREAK       │
│    5. classifyValidationErrors()                     │
│       ├─ package+compat errors → PackageAgent.fix    │
│       └─ code+type+build errors → MigrationAgent.fix │
│    6. fixAttempt++                                   │
│    7. Continue loop (re-validate)                    │
│  }                                                   │
└─────────────────────────────────────────────────────┘

Safety mechanisms:

  • Max 3 attempts: prevents infinite loops
  • No-progress detection: if the exact same issue set persists between attempts, the loop breaks (detected via file|code|message dedup key)
  • Dry-run aware: fixes are displayed but not written to disk in dry-run mode
  • Rate limiting: 1-second delay between per-file AI fix calls
  • Fix backup: MigrationAgent creates .fix-backup files before overwriting
  • Non-routable errors: if errors can't be classified to a known validator, the loop breaks and suggests manual intervention

Migration Pipeline (Phases)

The OrchestratorAgent runs the pipeline in 6 sequential phases:

Phase Agent(s) Description Output
0 — Discovery DiscoveryAgent Filesystem scan, version detection, AI risk assessment projectStructure, discoverySummary, detectedFrameworks, currentAngularVersion
1 — Planning PlannerAgent Fetch official update guide, generate step-by-step plan, human approval gate migrationPlan, planApproved (may halt pipeline)
2 — Package Migration PackageMigrationAgent AI resolve compatible versions, update package.json dependencyMap, updated package.json
3 — Code Analysis AnalysisAgent (→ DeprecationAgent) Scan all TS files for deprecated API usage, generate report warnings (serialized file analyses), migration-report.md
4 — Code Migration MigrationAgent AI rewrite files to fix deprecated usages, apply changes fileChanges, diffReport, migrated source files
5 — Validation & Auto-Fix ValidationEngine (5 validators) → PackageMigrationAgent / MigrationAgent Run all validators, auto-fix detected errors by routing to responsible agent, re-validate (up to 3 attempts) validationReport, validatorResults, validation-report.md, corrected files/packages

Each phase checks state.halted before executing. If a phase fails or the user rejects the plan, subsequent phases are skipped. Phase 5 contains an inner fix loop that can re-invoke Phase 2 and Phase 4 agents with error context.


State Management

The entire system is built around a single immutable state object (MigrationState).

Design Principles

  • Single source of truth: all agents read from and write to the same state
  • Immutable updates: mergeState() creates a new object via spread ({ ...state, ...patch })
  • Partial patches: agents return Partial<MigrationState> — only the fields they modify
  • Logging: logEntry() appends timestamped messages to migrationLog[]
  • Error tracking: recordError() appends structured errors to errors[]
  • Halt propagation: any agent can set halted: true to stop the pipeline

State Shape

interface MigrationState {
  // Input
  inputPath: string;
  outputPath: string;
  dryRun: boolean;

  // Discovery
  currentAngularVersion: string;
  targetAngularVersion: string;
  projectStructure: ProjectNode[];
  detectedFrameworks: string[];
  discoverySummary: DiscoverySummary | null;

  // Dependencies
  dependencyMap: Record<string, DependencyInfo>;
  peerConflictResolutions: string[];

  // Planning
  migrationPlan: MigrationStep[];
  planApproved: boolean | null;  // null=pending, true/false=decided

  // Execution
  fileChanges: FileChange[];
  appliedSchematics: string[];
  buildErrors: BuildError[];
  testResults: TestResult[];

  // Validation
  buildSuccess: boolean;
  testSuccess: boolean;
  lintSuccess: boolean;
  validationReport: ValidationReport | null;
  validatorResults: ValidatorResult[];

  // Output
  diffReport: string;
  migrationLog: string[];
  finalReviewApproved: boolean | null;

  // Control
  retryCount: Partial<Record<AgentName, number>>;
  currentAgent: AgentName;
  halted: boolean;
  errors: AgentError[];
  startedAt: Date;
  completedAt: Date | null;
  warnings: string[];
}

AI / LLM Integration

DeepSeekChatClient

File: src/deepseek-client.ts

A thin wrapper around LangChain's ChatDeepSeek:

  • Model: deepseek-coder (optimized for code generation)
  • Temperature: 0.1 (default, for deterministic outputs), 0.05 for MigrationAgent (most deterministic)
  • Max tokens: 4000 for code migration
  • API key: read from DEEPSEEK_API_KEY environment variable

Prompt Strategy

All AI prompts follow a strict pattern:

  1. SystemMessage: establishes the agent's role and enforces JSON-only output
  2. HumanMessage: contains the task description, project data, and response format specification

The system uses structured JSON output for all AI responses — each prompt specifies an exact JSON schema, and responses are parsed with fallback regex extraction if the JSON is wrapped in markdown or prose.

AI Usage by Agent

Agent AI Calls Purpose
DiscoveryAgent 1 Risk assessment & complexity estimation
PlannerAgent 1 Generate migration plan JSON
PackageMigrationAgent 2 + F Migration plan summary + version resolution JSON + fix package errors per fix attempt
DeprecationAgent 1 + N 1 catalogue call + per-file scan for files with potential hits
MigrationAgent N + F Per-file code migration + per-file fix calls for code/type/build errors per fix attempt
PackageValidator 1 AI compatibility check of resolved versions
CompatibilityChecker 1 AI cross-ecosystem compatibility analysis
CodeValidator M Per-migrated-file AI code review

F = number of files/packages that need fixing during the auto-fix loop. M = number of migrated files. N = number of files with potential deprecation hits.


Project Structure

angular-migrator/
├── src/
│   ├── index.ts                          # Entry point, exports, bootstrap
│   ├── cli.ts                            # Interactive CLI prompts
│   ├── deepseek-client.ts                # DeepSeek LLM wrapper (LangChain)
│   ├── agents/
│   │   ├── orchestrator/
│   │   │   └── orchestrator_agent.ts     # Central pipeline coordinator + fix loop
│   │   ├── discovery_agent.ts            # Filesystem scanning & AI risk analysis
│   │   ├── planner_agent.ts             # Migration plan generation & approval
│   │   ├── package_agent.ts             # Dependency version resolution + fixErrors()
│   │   ├── analysis_agent.ts            # Deprecated API scanning orchestrator
│   │   ├── deprecation_agent.ts         # AI deprecation catalogue & per-file scan
│   │   └── migration_agent.ts           # AI code rewriting engine + fixErrors()
│   ├── validators/
│   │   ├── validation-engine.ts          # Validator coordinator, interface, aggregation
│   │   ├── package-validator.ts          # Validates package.json + AI compatibility
│   │   ├── code-validator.ts             # Validates migrated code + static checks
│   │   ├── build-validator.ts            # Runs ng build + parses errors
│   │   ├── type-checker.ts               # Runs tsc --noEmit + parses TS errors
│   │   └── compatibility-checker.ts      # Cross-ecosystem version compatibility
│   ├── reporters/
│   │   └── validation-reporter.ts        # Console, markdown, and JSON report generation
│   ├── prompts/
│   │   ├── discovery_prompts.ts         # Risk assessment prompt builder
│   │   ├── planner_prompts.ts           # Migration plan prompt builder
│   │   ├── analysis_prompts.ts          # Version resolution, plan summary, package fix prompts
│   │   ├── deprecation_prompts.ts       # Catalogue & file scan prompts
│   │   ├── migration_prompts.ts         # Code migration + fix-file prompts
│   │   └── validation_prompts.ts        # Package validation, code validation, compatibility prompts
│   └── types/
│       └── migration-state.ts           # All types (incl. validation), state factory, helpers
├── package.json
├── tsconfig.json
└── .env                                 # DEEPSEEK_API_KEY (user-created)

Key Features

Filesystem Intelligence

  • Recursive project scanning with smart directory exclusion
  • Automatic file type classification (component, service, module, directive, pipe, template, style, spec)
  • Detection of lazy-loaded modules and standalone components via source code analysis
  • Framework detection from both package.json and import statements

AI-Powered Analysis

  • Migration complexity estimation (low/medium/high) with contextual risk assessment
  • Comprehensive deprecation catalogue generation covering ALL Angular packages
  • Per-file deprecated API detection with exact line numbers and severity levels
  • Intelligent version compatibility resolution for all project dependencies

AI-Powered Code Migration

  • Automatic code rewriting to fix deprecated API usages
  • Preserves business logic, comments, and variable names
  • Line-by-line diff preview before applying changes
  • Automated backup creation before any file modification
  • fixErrors() method: re-migrates specific files when validation finds issues, with error context for targeted fixes

Multi-Layer Validation Engine

  • 5 specialized validators: Package, Compatibility, Code, TypeScript, Build
  • Static + AI + CLI checks: combines pattern matching, AI-powered review, and actual compiler/build execution
  • Comprehensive reporting: color-coded console output, markdown report with severity-badged issue tables, machine-readable JSON
  • Build and type-check integration: runs tsc --noEmit and ng build --configuration production with error parsing

Auto-Fix Loop

  • Closed-loop validation → fix → re-validate cycle (up to 3 attempts)
  • Intelligent error routing: classifyValidationErrors() maps each validator's errors to the responsible fixing agent
  • No-progress detection: breaks the loop if fixes aren't resolving errors (dedup via file|code|message keys)
  • Targeted AI fixes: each fix call includes only the specific errors for that file/package, not the full context
  • Fix backup safety: creates .fix-backup copies before overwriting files during the fix loop

Safety & Control

  • Human-in-the-loop approval gate at the planning phase
  • Dry-run mode to preview all changes without writing files
  • Automatic backups (.backup files) before any modification, .fix-backup during fixes
  • Immutable state with full audit trail (migrationLog, errors)
  • Halt propagation — any error stops the entire pipeline
  • Step-level approval flags in the migration plan
  • Rollback commands in each migration step
  • Max fix attempts guard — prevents infinite fix loops

Developer Experience

  • Color-coded terminal output via kleur
  • Formatted plan display with breaking change and review tags
  • Markdown report generation (migration-report.md, validation-report.md)
  • JSON plan export (migration-plan.json)
  • Progress indicators during file scanning, migration, and validation
  • Fix attempt counter in final summary

Prerequisites

  • Node.js 18+
  • DeepSeek API Key — set in .env as DEEPSEEK_API_KEY=your_key_here
  • npm or yarn

Installation

# Clone the repository
git clone <repo-url>
cd angular-migrator

# Install dependencies
npm install

# Create .env file with your DeepSeek API key
echo "DEEPSEEK_API_KEY=sk-your-key-here" > .env

# Build the TypeScript
npm run build

Usage

Interactive Mode

npm start

You'll be prompted for:

  1. Angular project path — path to the Angular project to migrate
  2. Target Angular version — e.g., 18 (default: 18)
  3. Dry run?y to preview without writing, n to apply changes

Example Session

🔧 Angular Migration Tool

Enter Angular project path: /home/user/my-angular-app
Target Angular version (e.g., 18): 18
Dry run? (y/n): n

🚀 Angular Migration System
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
  Project: /home/user/my-angular-app
  Target:  Angular 18
  Mode:    LIVE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

── Phase 0/4: Project Discovery ──
🔭 Phase 0: Project Discovery
   Scanning: /home/user/my-angular-app
   Found 247 files
✅ Angular version detected: 14

📁 Project structure:
   component    42
   service      18
   module       12
   ...

🤖 Asking AI for migration risk assessment...
🎯 Migration complexity: MEDIUM
⚠️  Migration risks:
   • NgRx store interface changed in v15
   • Router API breaking changes in v16
   ...

── Phase 1/4: Migration Planning ──
📐 Planning: Generating Migration Plan
🤖 Generating step-by-step migration plan...

📋 Migration Plan — 8 steps
   Breaking changes: 3  |  Requires approval: 5

   step-01 [package]
     Update Angular core and CLI to v15
   step-02 [code] [BREAKING] [REVIEW]
     Migrate NgRx store to v15 createAction pattern
   ...

⚡ Human Approval Required
   3 breaking change(s) detected:
   • step-02: Migrate NgRx store to v15 createAction pattern

   Proceed with migration? (y/n): y
✅ Plan approved. Proceeding with migration...

── Phase 2/4: Package Migration ──
...
── Phase 3/4: Code Analysis ──
...
── Phase 4/4: Code Migration ──
...

✅ Migration complete!
  Complexity:       medium
  Migration risks:  4
  Plan steps:       8 (3 breaking)
  Files changed:    14
  Packages updated: 23
  Frameworks:       RxJS, NgRx, Angular Material
  Duration:         127s

Output Files

The system generates the following files in the target project:

File Created By Description
migration-plan.json PlannerAgent Structured JSON migration plan with all steps
migration-report.md AnalysisAgent Detailed markdown report of all deprecated API usages
validation-report.md ValidationReporter Comprehensive validation report with per-validator results and action items
package.json.backup PackageMigrationAgent Backup of original package.json
*.ts.backup MigrationAgent Backup of each migrated TypeScript file
*.ts.fix-backup MigrationAgent Backup before fix-loop modifications to each file

Public API / Exports

The package exports all major classes and types for programmatic use:

// Client
export { DeepSeekChatClient } from './deepseek-client';

// Agents
export { DiscoveryAgent }     from './agents/discovery_agent';
export { PlannerAgent }       from './agents/planner_agent';
export { PackageMigrationAgent } from './agents/package_agent';
export { AnalysisAgent }      from './agents/analysis_agent';
export { DeprecationAgent }   from './agents/deprecation_agent';
export { MigrationAgent }     from './agents/migration_agent';
export { OrchestratorAgent }  from './agents/orchestrator/orchestrator_agent';

// Validation engine
export { ValidationEngine }   from './validators/validation-engine';
export { PackageValidator }   from './validators/package-validator';
export { CodeValidator }      from './validators/code-validator';
export { BuildValidator }     from './validators/build-validator';
export { TypeChecker }        from './validators/type-checker';
export { CompatibilityChecker } from './validators/compatibility-checker';
export { ValidationReporter } from './reporters/validation-reporter';

// Types
export type {
  MigrationState,
  ProjectNode,
  DiscoverySummary,
  DependencyInfo,
  MigrationStep,
  FileChange,
  BuildError,
  TestResult,
  AgentError,
  AgentName,
  ValidationStatus,
  ValidationIssue,
  ValidatorResult,
  ValidationReport,
} from './types/migration-state';

Each agent also exposes direct methods for standalone use — you can use any agent independently without the orchestrator pipeline.


Error Handling & Resilience

  • Graceful degradation: If the Angular update guide fetch fails, the PlannerAgent falls back to LLM knowledge
  • JSON parsing resilience: All AI response parsing uses regex fallback extraction if the JSON is wrapped in markdown code blocks or prose
  • Rate limiting: File scanning and migration insert delays (500ms–1000ms) between API calls
  • Halt propagation: Any agent that encounters an unrecoverable error sets halted: true, preventing subsequent phases from running
  • Error recording: All errors are timestamped and stored in state.errors[] with agent attribution
  • File operation safety: All file writes are preceded by .backup file creation; fix-loop writes create .fix-backup copies; dry-run mode prevents any writes entirely
  • Auto-fix resilience: Validation errors are automatically routed to the fixing agent with error-specific context; no-progress detection prevents infinite loops; max 3 fix attempts; non-routable errors trigger manual intervention guidance
  • Validator fallbacks: CLI-based validators (build-validator, type-checker) gracefully skip if the required tools (ng, tsc, npm) are unavailable; AI validators fall back to static checks if the AI call fails

Type System

The system defines 9 agent roles (AgentName), each corresponding to a phase in the migration lifecycle:

orchestrator → discovery → planner → package → analysis → deprecation → migration → validation → reporting

Supporting types include:

  • ProjectNode — a file with path, Angular type classification, and size
  • DiscoverySummary — aggregated project scan results with AI complexity assessment
  • DependencyInfo — before/after version with breaking change flag
  • MigrationStep — an atomic step in the migration plan with agent type, command, and rollback
  • FileChange — original vs migrated content with changed line count
  • BuildError / TestResult — structured build and test output
  • AgentError — structured error with agent attribution and timestamp
  • ValidationStatus'pass' | 'fail' | 'warn' | 'skipped'
  • ValidationIssue — a single issue with validator name, severity, message, file, line, code, and suggestion
  • ValidatorResult — per-validator result with status, duration, issues, and summary
  • ValidationReport — aggregated report with overall status, all validator results, issue counts, and duration

How It Works (End-to-End Walkthrough)

  1. User launches npm start and provides project path, target version, and dry-run preference
  2. OrchestratorAgent creates initial MigrationState and begins the pipeline
  3. Phase 0 (DiscoveryAgent):
    • Recursively scans the project directory, classifying all files
    • Detects Angular version, frameworks, lazy-loaded modules, standalone components
    • Sends scan data to DeepSeek for AI-powered risk assessment
    • Populates projectStructure, detectedFrameworks, discoverySummary
  4. Phase 1 (PlannerAgent):
    • Fetches Angular's official update guide from update.angular.io
    • Combines official guidance with project context and sends to DeepSeek
    • DeepSeek returns a structured JSON migration plan
    • Plan is displayed and saved to migration-plan.json
    • User must approve — if rejected, pipeline stops
  5. Phase 2 (PackageMigrationAgent):
    • Reads current package.json
    • Asks DeepSeek to resolve ALL packages to compatible target versions
    • AI returns structured JSON with dependencies and devDependencies maps
    • Updates package.json (creates .backup first in live mode)
  6. Phase 3 (AnalysisAgent → DeprecationAgent):
    • DeprecationAgent asks DeepSeek for the complete deprecation catalogue for this version range
    • Walks all .ts files in src/, pre-filters using catalogue strings
    • Sends each candidate file to DeepSeek for precise deprecation detection
    • AnalysisAgent generates migration-report.md with findings
    • Results serialized into state.warnings for the next phase
  7. Phase 4 (MigrationAgent):
    • Extracts file analyses from state
    • For each file with deprecated usages, sends content + breaking changes to DeepSeek
    • AI returns migrated TypeScript code
    • Shows line-by-line diffs
    • Writes migrated code (creates .backup in live mode)
  8. Phase 5 (ValidationEngine → Auto-Fix Loop):
    • Runs all 5 validators: PackageValidator, CompatibilityChecker, CodeValidator, TypeChecker, BuildValidator
    • If all pass → exits loop
    • If errors found → classifyValidationErrors() routes them:
      • Package/compatibility errors → PackageMigrationAgent.fixErrors() re-resolves versions with error context
      • Code/type/build errors → MigrationAgent.fixErrors() re-migrates specific files with error details
    • Re-runs validation to verify fixes
    • Repeats up to 3 attempts, with no-progress detection to prevent infinite loops
    • Generates validation-report.md with full results and action items
  9. OrchestratorAgent prints the final summary with stats (complexity, risks, steps, files changed, validation status, fix attempts, duration)

About

AI-Powered Multi-Agent Migration System for Angular version update

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages