> ## Documentation Index
> Fetch the complete documentation index at: https://chatcli.edilsonfreitas.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Configuration Migration

> Versioned configuration migration system with automatic backup, rollback, and sequential migration execution.

ChatCLI includes a **versioned configuration migration** system that ensures safe and automatic upgrades between versions. When the configuration schema changes, migrations are applied sequentially, with a full backup before any modifications.

***

## How It Works

Each ChatCLI version defines a `CurrentConfigVersion`. When the user updates the binary, the system compares the saved version with the current version and applies the necessary migrations:

```text theme={"system"}
v0 (sem arquivo de versao)
  -> migracao v0 -> v1
v1 (CurrentConfigVersion)
  -> futuras migracoes
v2, v3, ...
```

### Migration Cycle

<Steps>
  <Step title="Detects need">
    Compares the current version with `CurrentConfigVersion`.
  </Step>

  <Step title="Creates backup">
    Saves the full configuration to `~/.chatcli/backups/config_backup_<timestamp>.json`.
  </Step>

  <Step title="Applies migrations">
    Executes each migration in sequence (v0 -> v1, v1 -> v2, ...).
  </Step>

  <Step title="Updates version">
    Writes the new version to `~/.chatcli/config_version.json`.
  </Step>

  <Step title="In case of failure">
    Preserves the original values and the backup remains available.
  </Step>
</Steps>

***

## Migration v0 -> v1

The included migration normalizes legacy configurations:

| Transformation     | Before            | After                          |
| :----------------- | :---------------- | :----------------------------- |
| Normalize provider | `openai`          | `OPENAI`                       |
| Rename API key     | `CHATCLI_API_KEY` | `OPENAI_API_KEY`               |
| Rename model       | `CHATCLI_MODEL`   | `OPENAI_MODEL`                 |
| Default skills     | (absent)          | `CHATCLI_SKILLS_ENABLED=true`  |
| Default safety     | (absent)          | `CHATCLI_SAFETY_ENABLED=false` |
| Default tool use   | (absent)          | `CHATCLI_NATIVE_TOOL_USE=true` |

***

## API

### Check Migration Need

```go theme={"system"}
registry := config.NewMigrationRegistry(configDir, logger)
needs, current, target, err := registry.NeedsMigration()
if needs {
    fmt.Printf("Migracao necessaria: v%d → v%d\n", current, target)
}
```

### Run Migration

```go theme={"system"}
values := map[string]interface{}{
    "LLM_PROVIDER":    "openai",
    "CHATCLI_API_KEY": "sk-test",
}

result, err := registry.Migrate(values)
// result["LLM_PROVIDER"] == "OPENAI"
// result["OPENAI_API_KEY"] == "sk-test"
// result["CHATCLI_SKILLS_ENABLED"] == "true"
```

### Backup and Rollback

```go theme={"system"}
// Manual backup
path, err := registry.Backup(values)
fmt.Println("Backup salvo em:", path)

// Rollback
err = registry.Rollback(backupPath)
```

### Register Custom Migration

```go theme={"system"}
registry.Register(1, func(v map[string]interface{}) (map[string]interface{}, error) {
    // Migracao v1 → v2
    v["NEW_FEATURE_ENABLED"] = "true"
    return v, nil
})
```

***

## Version File

The version is stored in `~/.chatcli/config_version.json`:

```json theme={"system"}
{
  "version": 1,
  "migrated_at": "2026-03-04T14:30:00Z"
}
```

***

## Backups

Backups are stored in `~/.chatcli/backups/` with a timestamp:

```text theme={"system"}
~/.chatcli/backups/
|-- config_backup_20260304_143000.json
|-- config_backup_20260301.172.00.json
+-- ...
```

Each backup contains the complete snapshot of configuration values before the migration.

***

## Safety

<CardGroup cols={2}>
  <Card title="Atomicity" icon="atom">
    Each migration is applied on a copy of the values. If it fails, the originals are preserved.
  </Card>

  <Card title="Sequentiality" icon="list-ol">
    Migrations are executed strictly in ascending version order.
  </Card>

  <Card title="Mandatory backup" icon="floppy-disk">
    A backup is automatically created before any migration.
  </Card>

  <Card title="Idempotency" icon="rotate">
    If already at the current version, `Migrate()` returns the values unchanged.
  </Card>
</CardGroup>
