# Skill Updater System

Comprehensive system for keeping your Claude Code skills up to date with automatic backups, source tracking, and intelligent updates.

## Overview

The Skill Updater System provides:
- **Automatic Updates**: Fetch fresh content from configured sources
- **Version Control**: Track skill versions and changes over time
- **Backup Management**: Automatic backups before updates with easy restoration
- **Source Tracking**: Maintain list of sources for each skill
- **Change Detection**: Compare old vs new content and report differences
- **Intelligent Merging**: Preserve custom content while updating from sources

## Components

### 1. SOURCES.json
Each skill should have a `SOURCES.json` file tracking its content sources.

**Location**: `~/.claude/skills/{skill-name}/SOURCES.json`

**Structure**:
```json
{
  "skillName": "skill-name",
  "version": "1.0.0",
  "lastUpdated": "2024-12-13T08:47:00Z",
  "updateFrequency": "weekly|monthly",
  "sources": [
    {
      "id": "unique-source-id",
      "url": "https://docs.example.com/",
      "type": "documentation|api-catalog|blog|github",
      "targetFile": "references/filename.md",
      "fetchPrompt": "Prompt for WebFetch tool",
      "active": true,
      "lastFetched": "2024-12-13T08:32:00Z",
      "customProcessor": "script.py (optional)"
    }
  ],
  "backup": {
    "enabled": true,
    "keepVersions": 5,
    "backupLocation": "~/.claude/skills/.backups/{skill-name}/"
  },
  "updateStrategy": {
    "mode": "merge|replace",
    "preserveCustomContent": true,
    "notifyOnChanges": true
  }
}
```

### 2. Skill Updater Agent
Handles the complete update workflow.

**Location**: `~/.claude/agents/skill-updater.md`

**Capabilities**:
- Backup creation and management
- Source content fetching
- Change detection and comparison
- File updates and merging
- Validation and error handling
- Restoration from backups

### 3. Slash Commands

**Update Command**: `/update-skill <skill-name>`
- Updates skill with fresh content
- Creates automatic backup
- Reports changes

**Restore Command**: `/restore-skill <skill-name> [timestamp]`
- Lists available backups
- Restores from selected backup
- Creates pre-restore backup

### 4. Backup System

**Location**: `~/.claude/skills/.backups/`

**Structure**:
```
.backups/
├── n8n-comprehensive/
│   ├── 2024-12-13-083000/
│   │   ├── SKILL.md
│   │   ├── SOURCES.json
│   │   └── references/
│   ├── 2024-12-12-150000/
│   └── backup-manifest.json
└── api-catalog/
    └── 2024-12-13-082700/
```

**Manifest**: `backup-manifest.json`
```json
{
  "skillName": "n8n-comprehensive",
  "backups": [
    {
      "timestamp": "2024-12-13-083000",
      "version": "1.0.0",
      "fileCount": 6,
      "totalSize": "65KB",
      "createdBy": "skill-updater",
      "reason": "pre-update-backup"
    }
  ]
}
```

## Quick Start Guide

### Setting Up a Skill for Auto-Updates

1. **Create SOURCES.json**:
```bash
cd ~/.claude/skills/your-skill
# Create SOURCES.json with your skill's sources
```

2. **Define Sources**:
```json
{
  "skillName": "your-skill",
  "version": "1.0.0",
  "sources": [
    {
      "id": "main-docs",
      "url": "https://docs.example.com/",
      "targetFile": "references/main.md",
      "fetchPrompt": "Extract comprehensive documentation...",
      "active": true
    }
  ]
}
```

3. **Test Update**:
```
/update-skill your-skill --dry-run
```

4. **Apply Update**:
```
/update-skill your-skill
```

### Updating an Existing Skill

**Simple update**:
```
/update-skill n8n-comprehensive
```

**Preview changes first**:
```
/update-skill n8n-comprehensive --dry-run
```

**Add new source and update**:
```
/update-skill n8n-comprehensive --add-source https://docs.n8n.io/hosting/
```

### Restoring from Backup

**List backups**:
```
/restore-skill n8n-comprehensive --list
```

**Restore specific version**:
```
/restore-skill n8n-comprehensive 2024-12-13-083000
```

**Restore latest**:
```
/restore-skill n8n-comprehensive --latest
```

## Workflow Examples

### Example 1: Regular Skill Maintenance

```
User: /update-skill n8n-comprehensive

Claude:
1. Reading SOURCES.json configuration...
2. Creating backup at ~/.claude/skills/.backups/n8n-comprehensive/2024-12-13-143000/
3. Fetching content from 6 sources...
   ✅ https://docs.n8n.io/ - Fetched (234KB)
   ✅ https://docs.n8n.io/integrations/ - Fetched (156KB)
   ✅ https://docs.n8n.io/code/ - Fetched (89KB)
   ✅ https://docs.n8n.io/advanced-ai/ - Fetched (112KB)
   ✅ https://docs.n8n.io/api/ - Fetched (78KB)
   ✅ https://docs.n8n.io/embed/ - Fetched (23KB)
4. Analyzing changes...
5. Updating files...
   📝 references/core-concepts.md - 45 lines changed
   📝 references/advanced-ai.md - 123 lines changed
   ✓ references/code-expressions.md - No changes
6. Updating metadata...

✅ Update Complete!

Summary:
- Version: 1.0.0 → 1.1.0
- Files updated: 2
- Total changes: 168 lines
- Backup: ~/.claude/skills/.backups/n8n-comprehensive/2024-12-13-143000/

Key Changes:
+ Added new AI agent types
+ Updated API authentication methods
- Removed deprecated endpoints

To restore previous version:
/restore-skill n8n-comprehensive 2024-12-13-143000
```

### Example 2: Adding New Source

```
User: Add https://docs.n8n.io/hosting/ to n8n-comprehensive and update

Claude:
1. Adding new source to SOURCES.json...
2. Validating source URL...
3. Creating backup...
4. Fetching new source content...
   ✅ https://docs.n8n.io/hosting/ - Fetched (67KB)
5. Creating new reference file: references/hosting.md
6. Updating SKILL.md to reference new content...
7. Fetching updates from existing sources...

✅ Source Added & Skill Updated!

New Source:
- URL: https://docs.n8n.io/hosting/
- Target: references/hosting.md
- Status: Active

Summary:
- New file created: references/hosting.md (67KB)
- SKILL.md updated with hosting reference
- Other files: 2 updated, 3 unchanged
```

### Example 3: Restoring from Backup

```
User: /restore-skill n8n-comprehensive --list

Claude:
Available backups for n8n-comprehensive:

1. 2024-12-13-143000 (Latest)
   - Version: 1.1.0
   - Files: 7
   - Size: 72KB
   - Reason: Regular update

2. 2024-12-13-083000
   - Version: 1.0.0
   - Files: 6
   - Size: 65KB
   - Reason: Initial backup

3. 2024-12-12-150000
   - Version: 0.9.5
   - Files: 5
   - Size: 58KB
   - Reason: Pre-update backup

Which backup would you like to restore? (1-3 or 'cancel')

User: 2

Claude:
1. Creating pre-restore backup of current state...
   ✅ Backed up to 2024-12-13-144500/
2. Validating backup integrity...
3. Restoring from 2024-12-13-083000...
   📁 Copying 6 files...
   ✅ SKILL.md
   ✅ SOURCES.json
   ✅ references/ (4 files)
4. Verifying restoration...

✅ Restoration Complete!

Restored:
- From: 2024-12-13-083000 (v1.0.0)
- To: Current
- Files restored: 6
- Backup of previous state: 2024-12-13-144500

If you want to undo this restoration:
/restore-skill n8n-comprehensive 2024-12-13-144500
```

## Best Practices

### Source Management
1. **URL Stability**: Use stable, versioned documentation URLs when possible
2. **Fetch Prompts**: Write specific prompts that target exact content needed
3. **Target Files**: Organize content into logical reference files
4. **Active Flag**: Disable sources temporarily without removing them

### Update Frequency
- **Documentation**: Weekly or monthly
- **API Catalogs**: Weekly (APIs change frequently)
- **Blog Content**: Monthly or on-demand
- **Stable Platforms**: Monthly or quarterly

### Backup Strategy
1. **Always backup**: Keep `backup.enabled: true`
2. **Retention**: Keep 5-10 versions for safety
3. **Storage**: Monitor backup directory size
4. **Testing**: Periodically test restoration process

### Update Strategy
- **merge**: Best for skills with custom content
- **replace**: Best for auto-generated catalogs
- **preserveCustomContent**: Enable for hybrid skills

### Custom Content Preservation

Mark custom sections in reference files:
```markdown
<!-- CUSTOM CONTENT START -->
Your custom notes and examples here
<!-- CUSTOM CONTENT END -->
```

The updater will preserve these sections during merge updates.

## Maintenance

### Cleanup Old Backups
```bash
# List backups older than 90 days
find ~/.claude/skills/.backups -type d -mtime +90

# Remove old backups (be careful!)
find ~/.claude/skills/.backups -type d -mtime +90 -exec rm -rf {} +
```

### Check Backup Disk Usage
```bash
du -sh ~/.claude/skills/.backups/*
```

### Validate All Skills
```bash
# List all skills with SOURCES.json
find ~/.claude/skills -name "SOURCES.json" -exec dirname {} \;
```

## Troubleshooting

### Update Fails
1. Check backup was created successfully
2. Review error messages in agent output
3. Verify source URLs are accessible
4. Try dry-run mode to preview changes
5. Restore from backup if needed

### Source Fetch Fails
- Verify URL is accessible
- Check if website requires authentication
- Adjust fetch prompt for better results
- Consider custom processor for complex sites

### Backup Restoration Issues
- Verify backup directory exists
- Check file permissions
- Ensure backup wasn't corrupted
- Try restoring to different location first

### Merge Conflicts
- Review updateStrategy settings
- Check custom content markers
- Consider replace mode for problematic files
- Manual merge may be needed for complex conflicts

## Advanced Features

### Custom Processors
For complex source parsing, create custom scripts:

```python
# ~/.claude/skills/my-skill/processors/custom_parser.py
import sys
import json

def process(raw_content):
    # Your custom parsing logic
    processed = parse_content(raw_content)
    return processed

if __name__ == "__main__":
    content = sys.stdin.read()
    result = process(content)
    print(result)
```

Reference in SOURCES.json:
```json
{
  "customProcessor": "processors/custom_parser.py"
}
```

### Automated Updates
Set up cron job or scheduled task:

```bash
# Daily skill updates at 2 AM
0 2 * * * /path/to/claude-code "/update-skill n8n-comprehensive --force"
```

### Change Notifications
Enable notifications in SOURCES.json:
```json
{
  "updateStrategy": {
    "notifyOnChanges": true
  }
}
```

The updater will generate detailed change reports.

## Support

For issues or questions:
1. Check agent output for error details
2. Review backup manifest for history
3. Try dry-run mode to debug
4. Consult skill-updater agent documentation
5. Test with simple skill first

## Future Enhancements

Potential improvements:
- [ ] Automated scheduling of updates
- [ ] Diff viewing before applying updates
- [ ] Integration with version control (git)
- [ ] Collaborative skill updating
- [ ] Source health monitoring
- [ ] Update success metrics
- [ ] Automated testing after updates

---

**Remember**: Always review changes after updates and test your skills to ensure they work as expected!
