# Legacy Agent - Comprehensive Legacy Interface Management

## Overview

The Legacy Agent is a comprehensive system for managing legacy interface compatibility and lifecycle in the MarkiTect project. Built on top of the existing legacy compatibility system from Issue #39, it provides intelligent automation for deprecation management, migration assistance, and cleanup operations.

## Architecture

The legacy agent system consists of several interconnected components:

### Core Components

1. **LegacyRegistry** (`markitect/legacy/registry.py`)
   - Central registry for all legacy interfaces and versions
   - Tracks git commit bindings, deprecation status, and timelines
   - Maintains SQLite database for persistence
   - Records usage statistics for informed decision making

2. **LegacyAgent** (`markitect/legacy/agent.py`)
   - Intelligent automation engine for legacy lifecycle management
   - Handles deprecation progression, cleanup scheduling, and notifications
   - Configurable automation policies
   - Task queue system for scheduled operations

3. **LegacySwitch System** (`markitect/legacy/switches.py`)
   - CLI switch management (`--legacy-v1`, `--legacy-v2`, etc.)
   - Automatic switch generation based on registry
   - Deprecation warning integration
   - Legacy routing to appropriate implementations

4. **DeprecationManager** (`markitect/legacy/deprecation.py`)
   - Graduated deprecation warning system
   - Timeline-based status progression
   - User notification management

5. **GitStateTracker** (`markitect/legacy/git_tracker.py`)
   - Binds legacy versions to specific git commits
   - Enables precise version restoration
   - Validates compatibility snapshots

## CLI Interface

The legacy agent exposes comprehensive CLI commands under the `markitect legacy` namespace:

### Core Commands

#### `markitect legacy status`
Shows status of all legacy interfaces with comprehensive metadata:
```bash
# Table view (default)
markitect legacy status

# JSON output
markitect legacy status --format json

# Include removed interfaces
markitect legacy status --include-removed
```

#### `markitect legacy analyze`
Performs intelligent analysis of legacy interfaces:
```bash
# Analyze all interfaces
markitect legacy analyze

# Analyze specific command
markitect legacy analyze query

# Analyze specific version
markitect legacy analyze query v1.0
```

#### `markitect legacy migrate`
Provides migration guidance with breaking change documentation:
```bash
# Get migration guide
markitect legacy migrate query v1.0

# Migrate to specific version
markitect legacy migrate query v1.0 --to-version v2.0
```

#### `markitect legacy cleanup`
Safely removes legacy interfaces with backup options:
```bash
# Interactive cleanup
markitect legacy cleanup query v1.0

# Force cleanup without confirmation
markitect legacy cleanup query v1.0 --force

# Cleanup without backup
markitect legacy cleanup query v1.0 --no-backup
```

### Agent Management

#### `markitect legacy agent-run`
Executes automated maintenance cycles:
```bash
# Run maintenance
markitect legacy agent-run

# Preview mode (dry run)
markitect legacy agent-run --dry-run
```

#### `markitect legacy agent-status`
Shows agent configuration and task queue status:
```bash
# Table view
markitect legacy agent-status

# JSON output
markitect legacy agent-status --format json
```

### Analytics & Reporting

#### `markitect legacy usage-stats`
Displays usage patterns for informed decision making:
```bash
# All interfaces (30 days)
markitect legacy usage-stats

# Specific command
markitect legacy usage-stats --command query

# Extended period
markitect legacy usage-stats --days 90
```

#### `markitect legacy generate-guide`
Creates detailed migration documentation:
```bash
# Output to stdout
markitect legacy generate-guide query v1.0

# Save to file
markitect legacy generate-guide query v1.0 --output migration_guide.md
```

## Legacy Interface Lifecycle

The system manages interfaces through a comprehensive lifecycle:

### Status Progression

1. **CURRENT** - Active implementation
2. **DEPRECATED** - Marked for eventual removal, warnings shown
3. **LEGACY** - Requires explicit `--legacy-vX` flag
4. **SUNSET** - Final warning phase, scheduled for removal
5. **REMOVED** - No longer available

### Automated Progression

The agent can automatically progress interfaces based on:
- Time-based rules (e.g., deprecated → legacy after 90 days)
- Usage patterns (e.g., unused interfaces move to sunset)
- Manual scheduling
- Policy configuration

### Agent Configuration

The agent behavior is configurable via `AgentConfig`:

```python
config = AgentConfig(
    auto_progression=True,                    # Auto-progress deprecations
    cleanup_unused_days=180,                 # Cleanup after 6 months unused
    migration_guide_auto_generation=True,    # Auto-generate guides
    notification_threshold_days=30,          # Notify 30 days before removal
    max_concurrent_migrations=3,             # Limit concurrent operations
    backup_before_cleanup=True               # Always backup before removal
)
```

## Integration with Existing Legacy System

The agent builds on the foundation from Issue #39:

### Existing Components (Issue #39)
- `markitect/legacy_compat.py` - Basic legacy switches and warnings
- `LegacyVersions` registry with git commit binding
- `LegacyMode` state management
- Environment-based test detection

### New Agent Components
- Advanced registry with database persistence
- Intelligent lifecycle automation
- Comprehensive CLI interface
- Usage analytics and reporting
- Migration assistance tools

### Compatibility
The new system is fully backward compatible with existing legacy switches:
- `--legacy-v39-pre` continues to work as before
- Existing deprecation warnings are preserved
- Test environment detection still functions

## Usage Examples

### Setting Up Legacy Interface

```python
from markitect.legacy import LegacyRegistry, LegacyStatus

registry = LegacyRegistry()

# Register a legacy version
registry.register_legacy_interface(
    command='query',
    version='v1.0',
    git_commit='a1b2c3d4',
    status=LegacyStatus.DEPRECATED,
    deprecated_date='2025-09-30',
    removal_date='2025-12-30',
    breaking_changes=['Parameter renamed', 'Output format changed'],
    description='Legacy query with old parameter names'
)
```

### Adding Legacy Support to CLI Command

```python
from markitect.legacy import legacy_option, with_legacy_support

@click.command()
@click.argument('sql', type=str)
@legacy_option('v1.0', 'Use v1.0 legacy behavior')
@with_legacy_support('query')
def query_command(sql, legacy_v1_0=False):
    # Modern implementation - legacy routing is automatic
    return execute_modern_query(sql)
```

### Running Maintenance

```bash
# Check what would be done
markitect legacy agent-run --dry-run

# Execute maintenance
markitect legacy agent-run

# Check results
markitect legacy agent-status
```

## Benefits

1. **Automated Management** - Reduces manual overhead of legacy maintenance
2. **Data-Driven Decisions** - Usage analytics inform deprecation timelines
3. **User Experience** - Clear migration paths and gradual warnings
4. **Safety** - Backup and rollback capabilities
5. **Comprehensive Tracking** - Complete audit trail of all operations
6. **Policy Enforcement** - Consistent application of deprecation policies

## Technical Implementation

### Database Schema
The registry uses SQLite with tables for:
- `legacy_interfaces` - Interface definitions and metadata
- `legacy_usage` - Usage tracking for analytics

### Task System
The agent uses a persistent task queue for:
- Scheduled deprecation progressions
- Cleanup operations
- Notification delivery
- Migration guide generation

### Git Integration
Version bindings enable:
- Precise restoration of legacy behavior
- Validation of compatibility snapshots
- Audit trail of changes

## Future Enhancements

1. **Integration with CI/CD** - Automated testing of legacy interfaces
2. **User Notification System** - Email/webhook notifications
3. **Migration Assistance** - Interactive migration wizards
4. **Advanced Analytics** - Usage heat maps and trend analysis
5. **Policy Templates** - Pre-configured deprecation policies
6. **Cross-Project Support** - Legacy management across multiple projects

## Getting Started

1. **Check Current Status**:
   ```bash
   markitect legacy status
   ```

2. **Run Analysis**:
   ```bash
   markitect legacy analyze
   ```

3. **Configure Agent**:
   ```bash
   markitect legacy agent-status
   ```

4. **Run Maintenance**:
   ```bash
   markitect legacy agent-run --dry-run
   markitect legacy agent-run
   ```

The legacy agent provides a complete solution for managing the entire lifecycle of deprecated interfaces, ensuring smooth transitions while maintaining backward compatibility.