# Workspace Enforcement and Version Tracking Guide

**Version**: 1.0.0
**Last Updated**: 2025-10-06
**System Version**: 2.0.5+

---

## Table of Contents

1. [Overview](#overview)
2. [Workspace Requirement](#workspace-requirement)
3. [Version Tracking](#version-tracking)
4. [Migration Framework](#migration-framework)
5. [Command Reference](#command-reference)
6. [Troubleshooting](#troubleshooting)
7. [Best Practices](#best-practices)

---

## Overview

The provisioning system now enforces **mandatory workspace requirements** for all infrastructure operations. This ensures:

- **Consistent Environment**: All operations run in a well-defined workspace
- **Version Compatibility**: Workspaces track provisioning and schema versions
- **Safe Migrations**: Automatic migration framework with backup/rollback support
- **Configuration Isolation**: Each workspace has isolated configurations and state

### Key Features

- ✅ **Mandatory Workspace**: Most commands require an active workspace
- ✅ **Version Tracking**: Workspaces track system, schema, and format versions
- ✅ **Compatibility Checks**: Automatic validation before operations
- ✅ **Migration Framework**: Safe upgrades with backup/restore
- ✅ **Clear Error Messages**: Helpful guidance when workspace is missing or incompatible

---

## Workspace Requirement

### Commands That Require Workspace

Almost all provisioning commands now require an active workspace:

- **Infrastructure**: `server`, `taskserv`, `cluster`, `infra`
- **Orchestration**: `workflow`, `batch`, `orchestrator`
- **Development**: `module`, `layer`, `pack`
- **Generation**: `generate`
- **Configuration**: Most `config` commands
- **Test**: `test` environment commands

### Commands That Don't Require Workspace

Only informational and workspace management commands work without a workspace:

- `help` - Help system
- `version` - Show version information
- `workspace` - Workspace management commands
- `guide` / `sc` - Documentation and quick reference
- `nu` - Start Nushell session
- `nuinfo` - Nushell information

### What Happens Without a Workspace

If you run a command without an active workspace, you'll see:

```plaintext
✗ Workspace Required

No active workspace is configured.

To get started:

  1. Create a new workspace:
     provisioning workspace init <name>

  2. Or activate an existing workspace:
     provisioning workspace activate <name>

  3. List available workspaces:
     provisioning workspace list
```plaintext

---

## Version Tracking

### Workspace Metadata

Each workspace maintains metadata in `.provisioning/metadata.yaml`:

```yaml
workspace:
  name: "my-workspace"
  path: "/path/to/workspace"

version:
  provisioning: "2.0.5"    # System version when created/updated
  schema: "1.0.0"          # KCL schema version
  workspace_format: "2.0.0" # Directory structure version

created: "2025-10-06T12:00:00Z"
last_updated: "2025-10-06T13:30:00Z"

migration_history: []

compatibility:
  min_provisioning_version: "2.0.0"
  min_schema_version: "1.0.0"
```plaintext

### Version Components

#### 1. Provisioning Version

- **What**: Version of the provisioning system (CLI + libraries)
- **Example**: `2.0.5`
- **Purpose**: Ensures workspace is compatible with current system

#### 2. Schema Version

- **What**: Version of KCL schemas used in workspace
- **Example**: `1.0.0`
- **Purpose**: Tracks configuration schema compatibility

#### 3. Workspace Format Version

- **What**: Version of workspace directory structure
- **Example**: `2.0.0`
- **Purpose**: Ensures workspace has required directories and files

### Checking Workspace Version

View workspace version information:

```bash
# Check active workspace version
provisioning workspace version

# Check specific workspace version
provisioning workspace version my-workspace

# JSON output
provisioning workspace version --format json
```plaintext

**Example Output**:

```plaintext
Workspace Version Information

System:
  Version: 2.0.5

Workspace:
  Name: my-workspace
  Path: /Users/user/workspaces/my-workspace
  Version: 2.0.5
  Schema Version: 1.0.0
  Format Version: 2.0.0
  Created: 2025-10-06T12:00:00Z
  Last Updated: 2025-10-06T13:30:00Z

Compatibility:
  Compatible: true
  Reason: version_match
  Message: Workspace and system versions match

Migrations:
  Total: 0
```plaintext

---

## Migration Framework

### When Migration is Needed

Migration is required when:

1. **No Metadata**: Workspace created before version tracking (< 2.0.5)
2. **Version Mismatch**: System version is newer than workspace version
3. **Breaking Changes**: Major version update with structural changes

### Compatibility Scenarios

#### Scenario 1: No Metadata (Unknown Version)

```plaintext
Workspace version is incompatible:
  Workspace: my-workspace
  Path: /path/to/workspace

Workspace metadata not found or corrupted

This workspace needs migration:

  Run workspace migration:
     provisioning workspace migrate my-workspace
```plaintext

#### Scenario 2: Migration Available

```plaintext
ℹ Migration available: Workspace can be updated from 2.0.0 to 2.0.5
  Run: provisioning workspace migrate my-workspace
```plaintext

#### Scenario 3: Workspace Too New

```plaintext
Workspace version (3.0.0) is newer than system (2.0.5)

Workspace is newer than the system:
  Workspace version: 3.0.0
  System version: 2.0.5

  Upgrade the provisioning system to use this workspace.
```plaintext

### Running Migrations

#### Basic Migration

Migrate active workspace to current system version:

```bash
provisioning workspace migrate
```plaintext

#### Migrate Specific Workspace

```bash
provisioning workspace migrate my-workspace
```plaintext

#### Migration Options

```bash
# Skip backup (not recommended)
provisioning workspace migrate --skip-backup

# Force without confirmation
provisioning workspace migrate --force

# Migrate to specific version
provisioning workspace migrate --target-version 2.1.0
```plaintext

### Migration Process

When you run a migration:

1. **Validation**: System validates workspace exists and needs migration
2. **Backup**: Creates timestamped backup in `.workspace_backups/`
3. **Confirmation**: Prompts for confirmation (unless `--force`)
4. **Migration**: Applies migration steps sequentially
5. **Verification**: Validates migration success
6. **Metadata Update**: Records migration in workspace metadata

**Example Migration Output**:

```plaintext
Workspace Migration

Workspace: my-workspace
Path: /path/to/workspace

Current version: unknown
Target version: 2.0.5

This will migrate the workspace from unknown to 2.0.5
A backup will be created before migration.

Continue with migration? (y/N): y

Creating backup...
✓ Backup created: /path/.workspace_backups/my-workspace_backup_20251006_123000

Migration Strategy: Initialize metadata
Description: Add metadata tracking to existing workspace
From: unknown → To: 2.0.5

Migrating workspace to version 2.0.5...
✓ Initialize metadata completed

✓ Migration completed successfully
```plaintext

### Workspace Backups

#### List Backups

```bash
# List backups for active workspace
provisioning workspace list-backups

# List backups for specific workspace
provisioning workspace list-backups my-workspace
```plaintext

**Example Output**:

```plaintext
Workspace Backups for my-workspace

name                               created                  reason         size
my-workspace_backup_20251006_1200  2025-10-06T12:00:00Z    pre_migration  2.3 MB
my-workspace_backup_20251005_1500  2025-10-05T15:00:00Z    pre_migration  2.1 MB
```plaintext

#### Restore from Backup

```bash
# Restore workspace from backup
provisioning workspace restore-backup /path/to/backup

# Force restore without confirmation
provisioning workspace restore-backup /path/to/backup --force
```plaintext

**Restore Process**:

```plaintext
Restore Workspace from Backup

Backup: /path/.workspace_backups/my-workspace_backup_20251006_1200
Original path: /path/to/workspace
Created: 2025-10-06T12:00:00Z
Reason: pre_migration

⚠ This will replace the current workspace at:
  /path/to/workspace

Continue with restore? (y/N): y

✓ Workspace restored from backup
```plaintext

---

## Command Reference

### Workspace Version Commands

```bash
# Show workspace version information
provisioning workspace version [workspace-name] [--format table|json|yaml]

# Check compatibility
provisioning workspace check-compatibility [workspace-name]

# Migrate workspace
provisioning workspace migrate [workspace-name] [--skip-backup] [--force] [--target-version VERSION]

# List backups
provisioning workspace list-backups [workspace-name]

# Restore from backup
provisioning workspace restore-backup <backup-path> [--force]
```plaintext

### Workspace Management Commands

```bash
# List all workspaces
provisioning workspace list

# Show active workspace
provisioning workspace active

# Activate workspace
provisioning workspace activate <name>

# Create new workspace (includes metadata initialization)
provisioning workspace init <name> [path]

# Register existing workspace
provisioning workspace register <name> <path>

# Remove workspace from registry
provisioning workspace remove <name> [--force]
```plaintext

---

## Troubleshooting

### Problem: "No active workspace"

**Solution**: Activate or create a workspace

```bash
# List available workspaces
provisioning workspace list

# Activate existing workspace
provisioning workspace activate my-workspace

# Or create new workspace
provisioning workspace init new-workspace
```plaintext

### Problem: "Workspace has invalid structure"

**Symptoms**: Missing directories or configuration files

**Solution**: Run migration to fix structure

```bash
provisioning workspace migrate my-workspace
```plaintext

### Problem: "Workspace version is incompatible"

**Solution**: Run migration to upgrade workspace

```bash
provisioning workspace migrate
```plaintext

### Problem: Migration Failed

**Solution**: Restore from automatic backup

```bash
# List backups
provisioning workspace list-backups

# Restore from most recent backup
provisioning workspace restore-backup /path/to/backup
```plaintext

### Problem: Can't Activate Workspace After Migration

**Possible Causes**:

1. Migration failed partially
2. Workspace path changed
3. Metadata corrupted

**Solutions**:

```bash
# Check workspace compatibility
provisioning workspace check-compatibility my-workspace

# If corrupted, restore from backup
provisioning workspace restore-backup /path/to/backup

# If path changed, re-register
provisioning workspace remove my-workspace
provisioning workspace register my-workspace /new/path --activate
```plaintext

---

## Best Practices

### 1. Always Use Named Workspaces

Create workspaces for different environments:

```bash
provisioning workspace init dev ~/workspaces/dev --activate
provisioning workspace init staging ~/workspaces/staging
provisioning workspace init production ~/workspaces/production
```plaintext

### 2. Let System Create Backups

Never use `--skip-backup` for important workspaces. Backups are cheap, data loss is expensive.

```bash
# Good: Default with backup
provisioning workspace migrate

# Risky: No backup
provisioning workspace migrate --skip-backup  # DON'T DO THIS
```plaintext

### 3. Check Compatibility Before Operations

Before major operations, verify workspace compatibility:

```bash
provisioning workspace check-compatibility
```plaintext

### 4. Migrate After System Upgrades

After upgrading the provisioning system:

```bash
# Check if migration available
provisioning workspace version

# Migrate if needed
provisioning workspace migrate
```plaintext

### 5. Keep Backups for Safety

Don't immediately delete old backups:

```bash
# List backups
provisioning workspace list-backups

# Keep at least 2-3 recent backups
```plaintext

### 6. Use Version Control for Workspace Configs

Initialize git in workspace directory:

```bash
cd ~/workspaces/my-workspace
git init
git add config/ infra/
git commit -m "Initial workspace configuration"
```plaintext

Exclude runtime and cache directories in `.gitignore`:

```gitignore
.cache/
.runtime/
.provisioning/
.workspace_backups/
```plaintext

### 7. Document Custom Migrations

If you need custom migration steps, document them:

```bash
# Create migration notes
echo "Custom steps for v2 to v3 migration" > MIGRATION_NOTES.md
```plaintext

---

## Migration History

Each migration is recorded in workspace metadata:

```yaml
migration_history:
  - from_version: "unknown"
    to_version: "2.0.5"
    migration_type: "metadata_initialization"
    timestamp: "2025-10-06T12:00:00Z"
    success: true
    notes: "Initial metadata creation"

  - from_version: "2.0.5"
    to_version: "2.1.0"
    migration_type: "version_update"
    timestamp: "2025-10-15T10:30:00Z"
    success: true
    notes: "Updated to workspace switching support"
```plaintext

View migration history:

```bash
provisioning workspace version --format yaml | grep -A 10 "migration_history"
```plaintext

---

## Summary

The workspace enforcement and version tracking system provides:

- **Safety**: Mandatory workspace prevents accidental operations outside defined environments
- **Compatibility**: Version tracking ensures workspace works with current system
- **Upgradability**: Migration framework handles version transitions safely
- **Recoverability**: Automatic backups protect against migration failures

**Key Commands**:

```bash
# Create workspace
provisioning workspace init my-workspace --activate

# Check version
provisioning workspace version

# Migrate if needed
provisioning workspace migrate

# List backups
provisioning workspace list-backups
```plaintext

For more information, see:

- **Workspace Switching Guide**: `docs/user/WORKSPACE_SWITCHING_GUIDE.md`
- **Quick Reference**: `provisioning sc` or `provisioning guide quickstart`
- **Help System**: `provisioning help workspace`

---

**Questions or Issues?**

Check the troubleshooting section or run:

```bash
provisioning workspace check-compatibility
```plaintext

This will provide specific guidance for your situation.
