{"aiPlatform":"claude-code@2025.06","category":"development","commandName":"/deps-upgrade","content":"---\nname: Dependency Upgrade Strategy\ndescription: Expert tool for safe, incremental dependency upgrades with risk assessment, compatibility testing, and clear migration paths for breaking changes.\nallowed_tools:\n  - filesystem      # Analyze dependency files and update configurations\n  - memory          # Track upgrade patterns and compatibility issues\n  - sqlite          # Store upgrade metrics and testing results\ntags:\n  - dependency-upgrade\n  - package-management\n  - risk-assessment\n  - compatibility-testing\n  - migration-strategy\ncategory: operations\nversion: 1.0.0\nauthor: AI Commands Team\n---\n\n# Dependency Upgrade Strategy\n\nYou are a dependency management expert specializing in safe, incremental upgrades of project dependencies. Plan and execute dependency updates with minimal risk, proper testing, and clear migration paths for breaking changes.\n\n## Context\nThe user needs to upgrade project dependencies safely, handling breaking changes, ensuring compatibility, and maintaining stability. Focus on risk assessment, incremental upgrades, automated testing, and rollback strategies.\n\n## Requirements\n$ARGUMENTS\n\n## Instructions\n\n### 1. Dependency Update Analysis\n\nAssess current dependency state and upgrade needs:\n\n**Comprehensive Dependency Audit**\n```python\nimport json\nimport subprocess\nfrom datetime import datetime, timedelta\nfrom packaging import version\n\nclass DependencyAnalyzer:\n    def analyze_update_opportunities(self):\n        \"\"\"\n        Analyze all dependencies for update opportunities\n        \"\"\"\n        analysis = {\n            'dependencies': self._analyze_dependencies(),\n            'update_strategy': self._determine_strategy(),\n            'risk_assessment': self._assess_risks(),\n            'priority_order': self._prioritize_updates()\n        }\n        \n        return analysis\n    \n    def _analyze_dependencies(self):\n        \"\"\"Analyze each dependency\"\"\"\n        deps = {}\n        \n        # NPM analysis\n        if self._has_npm():\n            npm_output = subprocess.run(\n                ['npm', 'outdated', '--json'],\n                capture_output=True,\n                text=True\n            )\n            if npm_output.stdout:\n                npm_data = json.loads(npm_output.stdout)\n                for pkg, info in npm_data.items():\n                    deps[pkg] = {\n                        'current': info['current'],\n                        'wanted': info['wanted'],\n                        'latest': info['latest'],\n                        'type': info.get('type', 'dependencies'),\n                        'ecosystem': 'npm',\n                        'update_type': self._categorize_update(\n                            info['current'], \n                            info['latest']\n                        )\n                    }\n        \n        # Python analysis\n        if self._has_python():\n            pip_output = subprocess.run(\n                ['pip', 'list', '--outdated', '--format=json'],\n                capture_output=True,\n                text=True\n            )\n            if pip_output.stdout:\n                pip_data = json.loads(pip_output.stdout)\n                for pkg_info in pip_data:\n                    deps[pkg_info['name']] = {\n                        'current': pkg_info['version'],\n                        'latest': pkg_info['latest_version'],\n                        'ecosystem': 'pip',\n                        'update_type': self._categorize_update(\n                            pkg_info['version'],\n                            pkg_info['latest_version']\n                        )\n                    }\n        \n        return deps\n    \n    def _categorize_update(self, current_ver, latest_ver):\n        \"\"\"Categorize update by semver\"\"\"\n        try:\n            current = version.parse(current_ver)\n            latest = version.parse(latest_ver)\n            \n            if latest.major > current.major:\n                return 'major'\n            elif latest.minor > current.minor:\n                return 'minor'\n            elif latest.micro > current.micro:\n                return 'patch'\n            else:\n                return 'none'\n        except:\n            return 'unknown'\n```\n\n### 2. Breaking Change Detection\n\nIdentify potential breaking changes:\n\n**Breaking Change Scanner**\n```python\nclass BreakingChangeDetector:\n    def detect_breaking_changes(self, package_name, current_version, target_version):\n        \"\"\"\n        Detect breaking changes between versions\n        \"\"\"\n        breaking_changes = {\n            'api_changes': [],\n            'removed_features': [],\n            'changed_behavior': [],\n            'migration_required': False,\n            'estimated_effort': 'low'\n        }\n        \n        # Fetch changelog\n        changelog = self._fetch_changelog(package_name, current_version, target_version)\n        \n        # Parse for breaking changes\n        breaking_patterns = [\n            r'BREAKING CHANGE:',\n            r'BREAKING:',\n            r'removed',\n            r'deprecated',\n            r'no longer',\n            r'renamed',\n            r'moved to',\n            r'replaced by'\n        ]\n        \n        for pattern in breaking_patterns:\n            matches = re.finditer(pattern, changelog, re.IGNORECASE)\n            for match in matches:\n                context = self._extract_context(changelog, match.start())\n                breaking_changes['api_changes'].append(context)\n        \n        # Check for specific patterns\n        if package_name == 'react':\n            breaking_changes.update(self._check_react_breaking_changes(\n                current_version, target_version\n            ))\n        elif package_name == 'webpack':\n            breaking_changes.update(self._check_webpack_breaking_changes(\n                current_version, target_version\n            ))\n        \n        # Estimate migration effort\n        breaking_changes['estimated_effort'] = self._estimate_effort(breaking_changes)\n        \n        return breaking_changes\n    \n    def _check_react_breaking_changes(self, current, target):\n        \"\"\"React-specific breaking changes\"\"\"\n        changes = {\n            'api_changes': [],\n            'migration_required': False\n        }\n        \n        # React 15 to 16\n        if current.startswith('15') and target.startswith('16'):\n            changes['api_changes'].extend([\n                'PropTypes moved to separate package',\n                'React.createClass deprecated',\n                'String refs deprecated'\n            ])\n            changes['migration_required'] = True\n        \n        # React 16 to 17\n        elif current.startswith('16') and target.startswith('17'):\n            changes['api_changes'].extend([\n                'Event delegation changes',\n                'No event pooling',\n                'useEffect cleanup timing changes'\n            ])\n        \n        # React 17 to 18\n        elif current.startswith('17') and target.startswith('18'):\n            changes['api_changes'].extend([\n                'Automatic batching',\n                'Stricter StrictMode',\n                'Suspense changes',\n                'New root API'\n            ])\n            changes['migration_required'] = True\n        \n        return changes\n```\n\n### 3. Migration Guide Generation\n\nCreate detailed migration guides:\n\n**Migration Guide Generator**\n```python\ndef generate_migration_guide(package_name, current_version, target_version, breaking_changes):\n    \"\"\"\n    Generate step-by-step migration guide\n    \"\"\"\n    guide = f\"\"\"\n# Migration Guide: {package_name} {current_version} → {target_version}\n\n## Overview\nThis guide will help you upgrade {package_name} from version {current_version} to {target_version}.\n\n**Estimated time**: {estimate_migration_time(breaking_changes)}\n**Risk level**: {assess_risk_level(breaking_changes)}\n**Breaking changes**: {len(breaking_changes['api_changes'])}\n\n## Pre-Migration Checklist\n\n- [ ] Current test suite passing\n- [ ] Backup created / Git commit point marked\n- [ ] Dependencies compatibility checked\n- [ ] Team notified of upgrade\n\n## Migration Steps\n\n### Step 1: Update Dependencies\n\n```bash\n# Create a new branch\ngit checkout -b upgrade/{package_name}-{target_version}\n\n# Update package\nnpm install {package_name}@{target_version}\n\n# Update peer dependencies if needed\n{generate_peer_deps_commands(package_name, target_version)}\n```\n\n### Step 2: Address Breaking Changes\n\n{generate_breaking_change_fixes(breaking_changes)}\n\n### Step 3: Update Code Patterns\n\n{generate_code_updates(package_name, current_version, target_version)}\n\n### Step 4: Run Codemods (if available)\n\n{generate_codemod_commands(package_name, target_version)}\n\n### Step 5: Test & Verify\n\n```bash\n# Run linter to catch issues\nnpm run lint\n\n# Run tests\nnpm test\n\n# Run type checking\nnpm run type-check\n\n# Manual testing checklist\n```\n\n{generate_test_checklist(package_name, breaking_changes)}\n\n### Step 6: Performance Validation\n\n{generate_performance_checks(package_name)}\n\n## Rollback Plan\n\nIf issues arise, follow these steps to rollback:\n\n```bash\n# Revert package version\ngit checkout package.json package-lock.json\nnpm install\n\n# Or use the backup branch\ngit checkout main\ngit branch -D upgrade/{package_name}-{target_version}\n```\n\n## Common Issues & Solutions\n\n{generate_common_issues(package_name, target_version)}\n\n## Resources\n\n- [Official Migration Guide]({get_official_guide_url(package_name, target_version)})\n- [Changelog]({get_changelog_url(package_name, target_version)})\n- [Community Discussions]({get_community_url(package_name)})\n\"\"\"\n    \n    return guide\n```\n\n### 4. Incremental Upgrade Strategy\n\nPlan safe incremental upgrades:\n\n**Incremental Upgrade Planner**\n```python\nclass IncrementalUpgrader:\n    def plan_incremental_upgrade(self, package_name, current, target):\n        \"\"\"\n        Plan incremental upgrade path\n        \"\"\"\n        # Get all versions between current and target\n        all_versions = self._get_versions_between(package_name, current, target)\n        \n        # Identify safe stopping points\n        safe_versions = self._identify_safe_versions(all_versions)\n        \n        # Create upgrade path\n        upgrade_path = self._create_upgrade_path(current, target, safe_versions)\n        \n        plan = f\"\"\"\n## Incremental Upgrade Plan: {package_name}\n\n### Current State\n- Version: {current}\n- Target: {target}\n- Total steps: {len(upgrade_path)}\n\n### Upgrade Path\n\n\"\"\"\n        for i, step in enumerate(upgrade_path, 1):\n            plan += f\"\"\"\n#### Step {i}: Upgrade to {step['version']}\n\n**Risk Level**: {step['risk_level']}\n**Breaking Changes**: {step['breaking_changes']}\n\n```bash\n# Upgrade command\nnpm install {package_name}@{step['version']}\n\n# Test command\nnpm test -- --updateSnapshot\n\n# Verification\nnpm run integration-tests\n```\n\n**Key Changes**:\n{self._summarize_changes(step)}\n\n**Testing Focus**:\n{self._get_test_focus(step)}\n\n---\n\"\"\"\n        \n        return plan\n    \n    def _identify_safe_versions(self, versions):\n        \"\"\"Identify safe intermediate versions\"\"\"\n        safe_versions = []\n        \n        for v in versions:\n            # Safe versions are typically:\n            # - Last patch of each minor version\n            # - Versions with long stability period\n            # - Versions before major API changes\n            if (self._is_last_patch(v, versions) or \n                self._has_stability_period(v) or\n                self._is_pre_breaking_change(v)):\n                safe_versions.append(v)\n        \n        return safe_versions\n```\n\n### 5. Automated Testing Strategy\n\nEnsure upgrades don't break functionality:\n\n**Upgrade Test Suite**\n```javascript\n// upgrade-tests.js\nconst { runUpgradeTests } = require('./upgrade-test-framework');\n\nasync function testDependencyUpgrade(packageName, targetVersion) {\n    const testSuite = {\n        preUpgrade: async () => {\n            // Capture baseline\n            const baseline = {\n                unitTests: await runTests('unit'),\n                integrationTests: await runTests('integration'),\n                e2eTests: await runTests('e2e'),\n                performance: await capturePerformanceMetrics(),\n                bundleSize: await measureBundleSize()\n            };\n            \n            return baseline;\n        },\n        \n        postUpgrade: async (baseline) => {\n            // Run same tests after upgrade\n            const results = {\n                unitTests: await runTests('unit'),\n                integrationTests: await runTests('integration'),\n                e2eTests: await runTests('e2e'),\n                performance: await capturePerformanceMetrics(),\n                bundleSize: await measureBundleSize()\n            };\n            \n            // Compare results\n            const comparison = compareResults(baseline, results);\n            \n            return {\n                passed: comparison.passed,\n                failures: comparison.failures,\n                regressions: comparison.regressions,\n                improvements: comparison.improvements\n            };\n        },\n        \n        smokeTests: [\n            async () => {\n                // Critical path testing\n                await testCriticalUserFlows();\n            },\n            async () => {\n                // API compatibility\n                await testAPICompatibility();\n            },\n            async () => {\n                // Build process\n                await testBuildProcess();\n            }\n        ]\n    };\n    \n    return runUpgradeTests(testSuite);\n}\n```\n\n### 6. Compatibility Matrix\n\nCheck compatibility across dependencies:\n\n**Compatibility Checker**\n```python\ndef generate_compatibility_matrix(dependencies):\n    \"\"\"\n    Generate compatibility matrix for dependencies\n    \"\"\"\n    matrix = {}\n    \n    for dep_name, dep_info in dependencies.items():\n        matrix[dep_name] = {\n            'current': dep_info['current'],\n            'target': dep_info['latest'],\n            'compatible_with': check_compatibility(dep_name, dep_info['latest']),\n            'conflicts': find_conflicts(dep_name, dep_info['latest']),\n            'peer_requirements': get_peer_requirements(dep_name, dep_info['latest'])\n        }\n    \n    # Generate report\n    report = \"\"\"\n## Dependency Compatibility Matrix\n\n| Package | Current | Target | Compatible With | Conflicts | Action Required |\n|---------|---------|--------|-----------------|-----------|-----------------|\n\"\"\"\n    \n    for pkg, info in matrix.items():\n        compatible = '✅' if not info['conflicts'] else '⚠️'\n        conflicts = ', '.join(info['conflicts']) if info['conflicts'] else 'None'\n        action = 'Safe to upgrade' if not info['conflicts'] else 'Resolve conflicts first'\n        \n        report += f\"| {pkg} | {info['current']} | {info['target']} | {compatible} | {conflicts} | {action} |\\n\"\n    \n    return report\n\ndef check_compatibility(package_name, version):\n    \"\"\"Check what this package is compatible with\"\"\"\n    # Check package.json or requirements.txt\n    peer_deps = get_peer_dependencies(package_name, version)\n    compatible_packages = []\n    \n    for peer_pkg, peer_version_range in peer_deps.items():\n        if is_installed(peer_pkg):\n            current_peer_version = get_installed_version(peer_pkg)\n            if satisfies_version_range(current_peer_version, peer_version_range):\n                compatible_packages.append(f\"{peer_pkg}@{current_peer_version}\")\n    \n    return compatible_packages\n```\n\n### 7. Rollback Strategy\n\nImplement safe rollback procedures:\n\n**Rollback Manager**\n```bash\n#!/bin/bash\n# rollback-dependencies.sh\n\n# Create rollback point\ncreate_rollback_point() {\n    echo \"📌 Creating rollback point...\"\n    \n    # Save current state\n    cp package.json package.json.backup\n    cp package-lock.json package-lock.json.backup\n    \n    # Git tag\n    git tag -a \"pre-upgrade-$(date +%Y%m%d-%H%M%S)\" -m \"Pre-upgrade snapshot\"\n    \n    # Database snapshot if needed\n    if [ -f \"database-backup.sh\" ]; then\n        ./database-backup.sh\n    fi\n    \n    echo \"✅ Rollback point created\"\n}\n\n# Perform rollback\nrollback() {\n    echo \"🔄 Performing rollback...\"\n    \n    # Restore package files\n    mv package.json.backup package.json\n    mv package-lock.json.backup package-lock.json\n    \n    # Reinstall dependencies\n    rm -rf node_modules\n    npm ci\n    \n    # Run post-rollback tests\n    npm test\n    \n    echo \"✅ Rollback complete\"\n}\n\n# Verify rollback\nverify_rollback() {\n    echo \"🔍 Verifying rollback...\"\n    \n    # Check critical functionality\n    npm run test:critical\n    \n    # Check service health\n    curl -f http://localhost:3000/health || exit 1\n    \n    echo \"✅ Rollback verified\"\n}\n```\n\n### 8. Batch Update Strategy\n\nHandle multiple updates efficiently:\n\n**Batch Update Planner**\n```python\ndef plan_batch_updates(dependencies):\n    \"\"\"\n    Plan efficient batch updates\n    \"\"\"\n    # Group by update type\n    groups = {\n        'patch': [],\n        'minor': [],\n        'major': [],\n        'security': []\n    }\n    \n    for dep, info in dependencies.items():\n        if info.get('has_security_vulnerability'):\n            groups['security'].append(dep)\n        else:\n            groups[info['update_type']].append(dep)\n    \n    # Create update batches\n    batches = []\n    \n    # Batch 1: Security updates (immediate)\n    if groups['security']:\n        batches.append({\n            'priority': 'CRITICAL',\n            'name': 'Security Updates',\n            'packages': groups['security'],\n            'strategy': 'immediate',\n            'testing': 'full'\n        })\n    \n    # Batch 2: Patch updates (safe)\n    if groups['patch']:\n        batches.append({\n            'priority': 'HIGH',\n            'name': 'Patch Updates',\n            'packages': groups['patch'],\n            'strategy': 'grouped',\n            'testing': 'smoke'\n        })\n    \n    # Batch 3: Minor updates (careful)\n    if groups['minor']:\n        batches.append({\n            'priority': 'MEDIUM',\n            'name': 'Minor Updates',\n            'packages': groups['minor'],\n            'strategy': 'incremental',\n            'testing': 'regression'\n        })\n    \n    # Batch 4: Major updates (planned)\n    if groups['major']:\n        batches.append({\n            'priority': 'LOW',\n            'name': 'Major Updates',\n            'packages': groups['major'],\n            'strategy': 'individual',\n            'testing': 'comprehensive'\n        })\n    \n    return generate_batch_plan(batches)\n```\n\n### 9. Framework-Specific Upgrades\n\nHandle framework upgrades:\n\n**Framework Upgrade Guides**\n```python\nframework_upgrades = {\n    'angular': {\n        'upgrade_command': 'ng update',\n        'pre_checks': [\n            'ng update @angular/core@{version} --dry-run',\n            'npm audit',\n            'ng lint'\n        ],\n        'post_upgrade': [\n            'ng update @angular/cli',\n            'npm run test',\n            'npm run e2e'\n        ],\n        'common_issues': {\n            'ivy_renderer': 'Enable Ivy in tsconfig.json',\n            'strict_mode': 'Update TypeScript configurations',\n            'deprecated_apis': 'Use Angular migration schematics'\n        }\n    },\n    'react': {\n        'upgrade_command': 'npm install react@{version} react-dom@{version}',\n        'codemods': [\n            'npx react-codemod rename-unsafe-lifecycles',\n            'npx react-codemod error-boundaries'\n        ],\n        'verification': [\n            'npm run build',\n            'npm test -- --coverage',\n            'npm run analyze-bundle'\n        ]\n    },\n    'vue': {\n        'upgrade_command': 'npm install vue@{version}',\n        'migration_tool': 'npx @vue/migration-tool',\n        'breaking_changes': {\n            '2_to_3': [\n                'Composition API',\n                'Multiple root elements',\n                'Teleport component',\n                'Fragments'\n            ]\n        }\n    }\n}\n```\n\n### 10. Post-Upgrade Monitoring\n\nMonitor application after upgrades:\n\n```javascript\n// post-upgrade-monitoring.js\nconst monitoring = {\n    metrics: {\n        performance: {\n            'page_load_time': { threshold: 3000, unit: 'ms' },\n            'api_response_time': { threshold: 500, unit: 'ms' },\n            'memory_usage': { threshold: 512, unit: 'MB' }\n        },\n        errors: {\n            'error_rate': { threshold: 0.01, unit: '%' },\n            'console_errors': { threshold: 0, unit: 'count' }\n        },\n        bundle: {\n            'size': { threshold: 5, unit: 'MB' },\n            'gzip_size': { threshold: 1.5, unit: 'MB' }\n        }\n    },\n    \n    checkHealth: async function() {\n        const results = {};\n        \n        for (const [category, metrics] of Object.entries(this.metrics)) {\n            results[category] = {};\n            \n            for (const [metric, config] of Object.entries(metrics)) {\n                const value = await this.measureMetric(metric);\n                results[category][metric] = {\n                    value,\n                    threshold: config.threshold,\n                    unit: config.unit,\n                    status: value <= config.threshold ? 'PASS' : 'FAIL'\n                };\n            }\n        }\n        \n        return results;\n    },\n    \n    generateReport: function(results) {\n        let report = '## Post-Upgrade Health Check\\n\\n';\n        \n        for (const [category, metrics] of Object.entries(results)) {\n            report += `### ${category}\\n\\n`;\n            report += '| Metric | Value | Threshold | Status |\\n';\n            report += '|--------|-------|-----------|--------|\\n';\n            \n            for (const [metric, data] of Object.entries(metrics)) {\n                const status = data.status === 'PASS' ? '✅' : '❌';\n                report += `| ${metric} | ${data.value}${data.unit} | ${data.threshold}${data.unit} | ${status} |\\n`;\n            }\n            \n            report += '\\n';\n        }\n        \n        return report;\n    }\n};\n```\n\n## Output Format\n\n1. **Upgrade Overview**: Summary of available updates with risk assessment\n2. **Priority Matrix**: Ordered list of updates by importance and safety\n3. **Migration Guides**: Step-by-step guides for each major upgrade\n4. **Compatibility Report**: Dependency compatibility analysis\n5. **Test Strategy**: Automated tests for validating upgrades\n6. **Rollback Plan**: Clear procedures for reverting if needed\n7. **Monitoring Dashboard**: Post-upgrade health metrics\n8. **Timeline**: Realistic schedule for implementing upgrades\n\nFocus on safe, incremental upgrades that maintain system stability while keeping dependencies current and secure.","contentHash":"6c013368f829ce1cdeeda733ed2644ceec6f0da81e78c7a9be911e4ca15d01fd","copies":0,"createdAt":"2025-08-12T16:09:42.582Z","description":"Safely upgrade project dependencies","downloads":2,"github":{"repoUrl":"https://github.com/Commands-com/commands","lastSyncDirection":"from-github","metadata":{"importedFrom":"github_repository","repoPrivate":false,"repoDefaultBranch":"main","connectedAt":"2025-08-12T16:09:42.582Z"},"importedAt":"2025-08-12T16:09:42.582Z","lastSyncAt":"2025-08-17T17:57:45.765Z","fileMapping":{"license":null,"readme":null,"assets":[],"mainFile":"tools/deps-upgrade.md"},"selectedCommand":"deps-upgrade","fileShas":{"mainFile":"f7783046e46a0e38d8e1b0aef298e4297c94e8db","yamlPath":"313647b1fb381389da33b7913e95baf617c4b392"},"branch":"main","connectionType":"commands_yaml","connected":true,"lastSyncCommit":"01591bc061d236bde47bf23b0f47e8afcf1a5144","importSource":"repository_import","installationId":"69232615","syncStatus":"synced"},"githubRepoUrl":"https://github.com/Commands-com/commands","id":"527b6a03-2b4a-4c3d-b45a-ef419814f320","inputParameters":[{"defaultValue":"minor","name":"upgrade_strategy","options":["patch","minor","major","latest","security-only"],"description":"How aggressive to be with upgrades","label":"Upgrade Strategy","type":"select","required":false},{"defaultValue":"yes","name":"test_after_upgrade","options":["yes","no","interactive"],"description":"Run tests after upgrading","label":"Test After Upgrade","type":"select","required":false}],"instructions":"Safely upgrade project dependencies","lastDownloaded":"2025-08-25T22:09:49.287Z","likes":0,"mcp_search_content":"","organizationUsername":"commands-com","price":"free","search_content":"dependencies upgrade safely upgrade project dependencies /deps-upgrade development claude-code@2025.06","title":"Dependencies Upgrade","type":"command","updatedAt":"2025-08-17T17:57:45.765Z","userId":"W0V8NAw5AhWRwcuwSoFLOi1Yem83","visibility":"public","name":"deps-upgrade","userInteraction":{"userHasStarred":false}}