---
name: dependency-manager
description: Intelligent dependency management that audits packages, updates safely, and resolves conflicts automatically.
isolation: worktree
---

# dependency-manager

Intelligent dependency management that audits packages, updates safely, and resolves conflicts automatically.

## Usage

Ask me to manage dependencies. I'll audit your packages, update them safely, and fix any issues.

## Interactive Dependency Strategy

### Management Questions

```
Q1: Update strategy?
   - Security patches only
   - Minor updates (safe)
   - Major updates (breaking)
   - Everything latest
   - Custom selection

Q2: Risk tolerance?
   - Zero risk (test everything)
   - Low risk (stable only)
   - Moderate (recommended)
   - High (bleeding edge)

Q3: Testing approach?
   - Full test suite
   - Smoke tests only
   - Build verification
   - Skip tests (dangerous)

Q4: Rollback capability?
   - Automatic rollback
   - Manual approval
   - Create backup branch
   - YOLO mode

Q5: Special requirements?
   - License compliance
   - Bundle size limits
   - Security audit
   - All checks
```

## Automated Dependency Management

### Phase 1: Dependency Audit

```javascript
const auditResults = {
  // Security vulnerabilities
  vulnerabilities: {
    critical: findCriticalVulns(),
    high: findHighVulns(),
    moderate: findModerateVulns(),
    low: findLowVulns(),
  },

  // Update availability
  updates: {
    major: findMajorUpdates(),
    minor: findMinorUpdates(),
    patch: findPatchUpdates(),
  },

  // Health metrics
  health: {
    outdated: findOutdatedPackages(),
    deprecated: findDeprecatedPackages(),
    unmaintained: findUnmaintainedPackages(),
    duplicates: findDuplicatePackages(),
  },

  // License compliance
  licenses: {
    allowed: checkAllowedLicenses(),
    restricted: checkRestrictedLicenses(),
    unknown: checkUnknownLicenses(),
  },
};
```

### Phase 2: Smart Updates

#### Safe Update Strategy

```bash
#!/bin/bash
# smart-update.sh

echo "📦 Smart Dependency Update Starting..."

# Backup current state
cp package.json package.json.backup
cp package-lock.json package-lock.json.backup

# Update in stages
echo "Stage 1: Security patches..."
npm audit fix

echo "Stage 2: Patch updates..."
npx npm-check-updates -u --target patch
npm install

echo "Stage 3: Testing patch updates..."
if ! npm test; then
  echo "❌ Tests failed, rolling back patch updates"
  mv package.json.backup package.json
  mv package-lock.json.backup package-lock.json
  npm install
  exit 1
fi

echo "Stage 4: Minor updates..."
npx npm-check-updates -u --target minor
npm install

echo "Stage 5: Testing minor updates..."
if ! npm test; then
  echo "⚠️ Tests failed, keeping only patch updates"
  exit 1
fi

echo "Stage 6: Major updates (with confirmation)..."
npx npm-check-updates -u --target major --interactive

echo "✅ Updates complete!"
```

#### Automated Conflict Resolution

```javascript
// resolve-conflicts.js
async function resolveConflicts() {
  const conflicts = await detectConflicts();

  for (const conflict of conflicts) {
    console.log(`Resolving conflict: ${conflict.package}`);

    // Try resolution strategies
    const strategies = [
      () => useLatestCompatible(conflict),
      () => usePeerDependency(conflict),
      () => createResolution(conflict),
      () => installBothVersions(conflict),
    ];

    for (const strategy of strategies) {
      if (await strategy()) {
        console.log(`✅ Resolved using ${strategy.name}`);
        break;
      }
    }
  }
}

// Example: Resolving peer dependency conflicts
function createResolution(conflict) {
  const resolutions = {
    "**/react": "^18.0.0",
    "**/webpack": "^5.0.0",
    "**/@types/node": "^20.0.0",
  };

  // Add to package.json
  packageJson.resolutions = {
    ...packageJson.resolutions,
    ...resolutions,
  };

  return true;
}
```

### Phase 3: Dependency Optimization

#### Remove Unused Dependencies

```javascript
// Find and remove unused packages
async function cleanupDependencies() {
  const used = await findUsedPackages();
  const installed = Object.keys(packageJson.dependencies);

  const unused = installed.filter((pkg) => !used.has(pkg));

  if (unused.length > 0) {
    console.log("Removing unused packages:", unused);

    for (const pkg of unused) {
      await exec(`npm uninstall ${pkg}`);
    }

    // Verify nothing broke
    await runTests();
  }

  // Find better alternatives
  const replacements = {
    moment: "date-fns",
    lodash: "lodash-es",
    request: "axios",
    "node-sass": "sass",
  };

  for (const [old, replacement] of Object.entries(replacements)) {
    if (installed.includes(old)) {
      console.log(`Replacing ${old} with ${replacement}`);
      await exec(`npm uninstall ${old}`);
      await exec(`npm install ${replacement}`);
      await updateImports(old, replacement);
    }
  }
}
```

#### Bundle Size Optimization

```javascript
// Analyze and optimize bundle size
async function optimizeBundleSize() {
  const analysis = await analyzeBundles();

  // Find large dependencies
  const largePackages = analysis.packages
    .filter((pkg) => pkg.size > 100000) // 100KB
    .sort((a, b) => b.size - a.size);

  for (const pkg of largePackages) {
    console.log(`📦 ${pkg.name}: ${(pkg.size / 1024).toFixed(2)}KB`);

    // Try to find lighter alternatives
    const alternative = await findLighterAlternative(pkg.name);
    if (alternative) {
      console.log(
        `  → Suggest: ${alternative.name} (${(alternative.size / 1024).toFixed(2)}KB)`,
      );

      // Auto-replace if safe
      if (alternative.compatible) {
        await replacePackage(pkg.name, alternative.name);
      }
    }

    // Check if tree-shakeable
    if (!pkg.treeShakeable) {
      console.log(`  ⚠️ Not tree-shakeable, consider dynamic import`);
      await convertToDynamicImport(pkg.name);
    }
  }
}
```

### Phase 4: License Compliance

```javascript
// Ensure license compliance
async function checkLicenseCompliance() {
  const allowed = ["MIT", "Apache-2.0", "BSD", "ISC"];
  const restricted = ["GPL", "AGPL", "LGPL"];

  const licenses = await analyzeLicenses();

  for (const [pkg, license] of Object.entries(licenses)) {
    if (restricted.includes(license)) {
      console.error(`❌ Restricted license: ${pkg} (${license})`);

      // Find alternative
      const alternative = await findAlternativeWithLicense(pkg, allowed);
      if (alternative) {
        await replacePackage(pkg, alternative);
      } else {
        throw new Error(`No alternative for ${pkg} with acceptable license`);
      }
    }
  }

  // Generate license report
  await generateLicenseReport(licenses);
}
```

## Continuous Monitoring

```javascript
// Monitor dependencies continuously
class DependencyMonitor {
  constructor() {
    this.schedule = "0 9 * * 1"; // Every Monday at 9 AM
  }

  async run() {
    const report = {
      date: new Date(),
      vulnerabilities: await this.checkVulnerabilities(),
      updates: await this.checkUpdates(),
      health: await this.checkHealth(),
    };

    // Auto-fix critical issues
    if (report.vulnerabilities.critical > 0) {
      await this.autoFixCritical();
      await this.notifyTeam("Critical vulnerabilities fixed");
    }

    // Create PR for updates
    if (report.updates.available > 0) {
      await this.createUpdatePR(report.updates);
    }

    return report;
  }

  async autoFixCritical() {
    await exec("npm audit fix --force");
    await this.runTests();
    await this.commit("fix: critical security vulnerabilities");
  }
}
```

## Dependency Report

```markdown
# Dependency Report

## Summary

- **Total packages**: 847
- **Direct dependencies**: 42
- **Dev dependencies**: 28
- **Vulnerabilities**: 0 (23 fixed)
- **Outdated**: 8 packages
- **Bundle impact**: Reduced by 35%

## Security Fixes Applied

1. ✅ next@14.2.23 → 14.2.32 (CVE-2024-XXXX)
2. ✅ ws@7.4.6 → 8.11.0 (ReDoS vulnerability)
3. ✅ jsonwebtoken@8.5.1 → 9.0.0 (Security fix)

## Updates Applied

### Production Dependencies

- react@18.2.0 → 18.3.1 (patch)
- typescript@5.0.4 → 5.3.3 (minor)
- tailwindcss@3.3.0 → 3.4.1 (minor)

### Dev Dependencies

- eslint@8.42.0 → 8.56.0 (minor)
- jest@29.5.0 → 29.7.0 (patch)

## Optimizations

- Replaced moment (329KB) with date-fns (73KB)
- Replaced lodash (71KB) with lodash-es (43KB)
- Removed 5 unused dependencies
- Tree-shaking improved by 40%

## License Compliance

✅ All packages comply with MIT/Apache-2.0
✅ No GPL/copyleft licenses
✅ License file generated

## Recommendations

1. Consider upgrading to React 19 (major update)
2. Remove deprecated package 'request'
3. Update Node.js to v20 LTS
```

## Example Output

```
📦 Dependency Management Started

Understanding your requirements...
✓ Strategy: Minor updates
✓ Risk: Low
✓ Testing: Full suite
✓ Rollback: Automatic
✓ Checks: All

Auditing dependencies...
🔍 Scanning 847 packages
⚠️ Found 3 critical vulnerabilities
⚠️ Found 8 high vulnerabilities
📊 42 packages outdated
📊 5 packages unused

Fixing vulnerabilities...
✅ Fixed: next security vulnerability
✅ Fixed: ws ReDoS vulnerability
✅ Fixed: jsonwebtoken vulnerability

Updating packages...
📦 Updating 15 patch versions...
✅ All tests passing

📦 Updating 12 minor versions...
✅ All tests passing

Optimizing dependencies...
✅ Removed 5 unused packages
✅ Replaced heavy dependencies
✅ Bundle size: 450KB → 292KB (-35%)

Running final verification...
✅ No vulnerabilities
✅ All tests passing
✅ Build successful
✅ License compliance OK

📊 Dependency Health Score: 94/100

Cleanup saved:
- 158KB bundle size
- 23 vulnerabilities fixed
- 5 unused packages removed
- 100% license compliance
```
