# Workspace Management

**Workspaces** are the default organizational unit for all infrastructure work in Provisioning.
Every infrastructure project, deployment environment, or isolated configuration lives within a
workspace. This workspace-first approach provides clean separation between projects,
environments, and teams while enabling rapid context switching.

## Overview

A workspace is an isolated environment that groups together:

- **Infrastructure definitions** - Nickel schemas, server configs, cluster definitions
- **Configuration settings** - Environment-specific settings, provider credentials, user preferences
- **Runtime data** - State files, checkpoints, logs, generated configurations
- **Extensions** - Custom providers, task services, workflow templates

The workspace system enforces that all infrastructure operations (server creation, task service
installation, cluster deployment) require an active workspace. This prevents accidental
cross-project modifications and ensures configuration isolation.

## Why Workspace-First

Traditional infrastructure tools often mix configurations across projects, leading to:

- Accidental deployments to wrong environments
- Configuration drift between dev/staging/production
- Credential leakage across projects
- Difficulty tracking infrastructure boundaries

Provisioning's workspace-first approach solves these problems by making workspace boundaries explicit and enforced at the CLI level.

## Workspace Structure

Every workspace follows a consistent directory structure:

```bash
workspace_my_project/
├── infra/                    # Infrastructure definitions (Nickel schemas)
│   ├── my-cluster.ncl        # Cluster definition
│   ├── servers.ncl           # Server configurations
│   └── batch-workflows.ncl   # Batch workflow definitions
│
├── config/                   # Workspace configuration
│   ├── local-overrides.toml  # User-specific overrides (gitignored)
│   ├── dev-defaults.toml     # Development environment defaults
│   ├── test-defaults.toml    # Testing environment defaults
│   ├── prod-defaults.toml    # Production environment defaults
│   └── provisioning.yaml     # Workspace metadata and settings
│
├── extensions/               # Workspace-specific extensions
│   ├── providers/            # Custom cloud providers
│   ├── taskservs/            # Custom task services
│   ├── clusters/             # Custom cluster templates
│   └── workflows/            # Custom workflow definitions
│
└── runtime/                  # Runtime data (gitignored)
    ├── state/                # Infrastructure state files
    ├── checkpoints/          # Workflow checkpoints
    ├── logs/                 # Operation logs
    └── generated/            # Generated configuration files
```

## Configuration Hierarchy

Workspace configurations follow a 5-layer hierarchy:

```text
1. System Defaults       (provisioning/config/config.defaults.toml)
   ↓ overridden by
2. User Config           (~/.config/provisioning/user_config.yaml)
   ↓ overridden by
3. Workspace Config      (workspace/config/provisioning.yaml)
   ↓ overridden by
4. Environment Config    (workspace/config/{dev,test,prod}-defaults.toml)
   ↓ overridden by
5. Runtime Flags         (--flag value)
```

This hierarchy ensures sensible defaults while allowing granular control at every level.

## Core Commands

### Creating Workspaces

```bash
# Create new workspace
provisioning workspace init my-project

# Create workspace with specific location
provisioning workspace init my-project --path /custom/location

# Create from template
provisioning workspace init my-project --template kubernetes-ha
```

### Listing Workspaces

```bash
# List all workspaces
provisioning workspace list

# Show active workspace
provisioning workspace status

# List with details
provisioning workspace list --verbose
```

Example output:

```text
NAME              PATH                                 LAST_USED           STATUS
my-project        /workspaces/workspace_my_project     2026-01-15 10:30    Active
dev-env           /workspaces/workspace_dev_env        2026-01-14 15:45
production        /workspaces/workspace_production     2026-01-10 09:00
```

### Switching Workspaces

```bash
# Switch to different workspace (single command)
provisioning workspace switch my-project

# Switch with validation
provisioning workspace switch production --validate

# Quick switch using shortcut
provisioning ws switch dev-env
```

Workspace switching updates:

- Active workspace marker in user configuration
- Environment variables for current session
- CLI prompt indicator (if configured)
- Last-used timestamp

### Deleting Workspaces

```bash
# Delete workspace (requires confirmation)
provisioning workspace delete old-project

# Force delete without confirmation
provisioning workspace delete old-project --force

# Delete but keep backups
provisioning workspace delete old-project --backup
```

Deletion safety:

- Requires explicit confirmation unless `--force` is used
- Optionally creates backup before deletion
- Validates no active operations are running
- Updates workspace registry

## Workspace Registry

The workspace registry is stored in user configuration and tracks all workspaces:

```yaml
# ~/.config/provisioning/user_config.yaml
workspaces:
  active: my-project
  registry:
    my-project:
      path: /workspaces/workspace_my_project
      created: 2026-01-15T10:30:00Z
      last_used: 2026-01-15T14:20:00Z
      template: default
    dev-env:
      path: /workspaces/workspace_dev_env
      created: 2026-01-10T08:00:00Z
      last_used: 2026-01-14T15:45:00Z
      template: development
```

This centralized registry enables:

- Fast workspace discovery
- Usage tracking and statistics
- Workspace templates
- Path resolution

## Workspace Enforcement

The CLI enforces workspace requirements for all infrastructure operations:

**Workspace-exempt commands** (work without active workspace):

- `provisioning help`
- `provisioning version`
- `provisioning workspace *`
- `provisioning guide *`
- `provisioning setup *`
- `provisioning providers` (list only)

**Workspace-required commands** (require active workspace):

- `provisioning server create`
- `provisioning taskserv install`
- `provisioning cluster deploy`
- `provisioning batch submit`
- All infrastructure modification operations

If no workspace is active, workspace-required commands fail with:

```text
Error: No active workspace
Please activate or create a workspace:
  provisioning workspace init <name>
  provisioning workspace switch <name>
```

This enforcement prevents accidental infrastructure modifications outside workspace boundaries.

## Workspace Templates

Templates provide pre-configured workspace structures for common use cases:

### Available Templates

| Template | Description | Use Case |
| -------- | ----------- | -------- |
| `default` | Minimal workspace structure | General purpose infrastructure |
| `kubernetes-ha` | HA Kubernetes setup with 3 control planes | Production Kubernetes deployments |
| `development` | Dev-optimized with Docker Compose | Local testing and development |
| `multi-cloud` | Multiple provider configurations | Multi-cloud deployments |
| `database-cluster` | Database-focused with backup configs | Database infrastructure |
| `cicd` | CI/CD pipeline configurations | Automated deployment pipelines |

### Using Templates

```bash
# Create from template
provisioning workspace init my-k8s --template kubernetes-ha

# List available templates
provisioning workspace templates

# Show template details
provisioning workspace template show kubernetes-ha
```

Templates pre-populate:

- Infrastructure Nickel schemas
- Provider configurations
- Environment-specific defaults
- Example workflow definitions
- README with usage instructions

## Multi-Environment Workflows

Workspaces excel at managing multiple environments:

### Strategy 1: Separate Workspaces Per Environment

```bash
# Create dedicated workspaces
provisioning workspace init myapp-dev
provisioning workspace init myapp-staging
provisioning workspace init myapp-prod

# Switch between environments
provisioning ws switch myapp-dev
provisioning server create      # Creates in dev

provisioning ws switch myapp-prod
provisioning server create      # Creates in prod (isolated)
```

**Pros**: Complete isolation, different credentials, independent state
**Cons**: More workspace management, duplicate configuration

### Strategy 2: Single Workspace, Multiple Environments

```bash
# Single workspace with environment configs
provisioning workspace init myapp

# Deploy to different environments using flags
PROVISIONING_ENV=dev provisioning server create
PROVISIONING_ENV=staging provisioning server create
PROVISIONING_ENV=prod provisioning server create
```

**Pros**: Shared configuration, easier to maintain
**Cons**: Shared credentials, risk of cross-environment mistakes

### Strategy 3: Hybrid Approach

```bash
# Dev workspace for experimentation
provisioning workspace init myapp-dev

# Prod workspace for production only
provisioning workspace init myapp-prod

# Use environment flags within workspaces
provisioning ws switch myapp-prod
PROVISIONING_ENV=prod provisioning cluster deploy
```

**Pros**: Balances isolation and convenience
**Cons**: More complex to explain to teams

## Best Practices

### Naming Conventions

```bash
# Good names (descriptive, unique)
workspace_librecloud_production
workspace_myapp_dev
workspace_k8s_staging

# Avoid (ambiguous, generic)
workspace_test
workspace_1
workspace_temp
```

### Configuration Management

```toml
# Version control: Commit these files
infra/**/*.ncl                    # Infrastructure definitions
config/*-defaults.toml             # Environment defaults
config/provisioning.yaml           # Workspace metadata
extensions/**/*                    # Custom extensions

# Gitignore: Never commit these
config/local-overrides.toml        # User-specific overrides
runtime/**/*                       # Runtime data and state
**/*.secret                        # Credential files
```

### Environment Separation

```bash
# Use dedicated workspaces for production
provisioning workspace init myapp-prod --template production

# Enable extra validation for production
provisioning ws switch myapp-prod
provisioning config set validation.strict true
provisioning config set confirmation.required true
```

### Team Collaboration

```bash
# Share workspace structure via git
git clone repo/myapp-infrastructure
cd myapp-infrastructure
provisioning workspace init . --import

# Each team member creates local-overrides.toml
cat > config/local-overrides.toml <<EOF
[user]
default_region = "us-east-1"
confirmation_required = true
EOF
```

## Troubleshooting

### No Active Workspace Error

```text
Error: No active workspace
```

**Solution:**

```bash
# List workspaces
provisioning workspace list

# Switch to workspace
provisioning workspace switch <name>

# Or create new workspace
provisioning workspace init <name>
```

### Workspace Not Found

```text
Error: Workspace 'my-project' not found in registry
```

**Solution:**

```bash
# Re-register workspace
provisioning workspace register /path/to/workspace_my_project

# Or recreate workspace
provisioning workspace init my-project
```

### Workspace Path Doesn't Exist

```text
Error: Workspace path '/workspaces/workspace_my_project' does not exist
```

**Solution:**

```bash
# Remove invalid entry
provisioning workspace unregister my-project

# Re-create workspace
provisioning workspace init my-project
```

## Integration with Other Features

### Batch Workflows

Workspaces provide the context for batch workflow execution:

```bash
provisioning ws switch production
provisioning batch submit infra/batch-workflows.ncl
```

Batch workflows access workspace-specific:

- Infrastructure definitions
- Provider credentials
- Configuration settings
- State management

### Test Environments

Test environments inherit workspace configuration:

```bash
provisioning ws switch dev
provisioning test quick kubernetes
# Uses dev workspace's configuration and providers
```

### Version Management

Workspace configurations can specify tool versions:

```nickel
# workspace/infra/versions.ncl
{
  tools = {
    nushell = "0.109.1"
    nickel = "1.15.1"
    kubernetes = "1.29.0"
  }
}
```

Provisioning validates versions match workspace requirements.

## See Also

- [Configuration System](configuration-system.md) - Hierarchical configuration details
- [Nickel Guide](../infrastructure/nickel-guide.md) - Infrastructure definitions in Nickel
- [Batch Workflows](batch-workflows.md) - Multi-cloud workflow orchestration
- [Test Environment](test-environment.md) - Container-based testing within workspaces
