# Repository and Distribution Architecture Analysis

**Date:** 2025-10-01
**Status:** Analysis Complete - Implementation Planning
**Author:** Architecture Review

## Executive Summary

This document analyzes the current project structure and provides a comprehensive plan for optimizing the repository organization and distribution strategy. The goal is to create a professional-grade infrastructure automation system with clear separation of concerns, efficient development workflow, and user-friendly distribution.

---

## Current State Analysis

### Strengths

1. **Clean Core Separation**
   - `provisioning/` contains the core system
   - `workspace/` concept for user data
   - Clear extension points (providers, taskservs, clusters)

2. **Hybrid Architecture**
   - Rust orchestrator for performance-critical operations
   - Nushell for business logic and scripting
   - KCL for type-safe configuration

3. **Modular Design**
   - Extension system for providers and services
   - Plugin architecture for Nushell
   - Template-based code generation

4. **Advanced Features**
   - Batch workflow system (v3.1.0)
   - Hybrid orchestrator (v3.0.0)
   - Token-optimized agent architecture

### Critical Issues

1. **Confusing Root Structure**
   - Multiple workspace variants: `_workspace/`, `backup-workspace/`, `workspace-librecloud/`
   - Development artifacts at root: `wrks/`, `NO/`, `target/`
   - Unclear which workspace is active

2. **Mixed Concerns**
   - Runtime data intermixed with source code
   - Build artifacts not properly isolated
   - Presentations and demos in main repo

3. **Distribution Challenges**
   - Bash wrapper for CLI entry point (`provisioning/core/cli/provisioning`)
   - No clear installation mechanism
   - Missing package management system
   - Undefined installation paths

4. **Documentation Fragmentation**
   - Multiple `docs/` locations
   - Scattered README files
   - No unified documentation structure

5. **Configuration Complexity**
   - TOML-based system is good, but paths are unclear
   - User vs system config separation needs clarification
   - Installation paths not standardized

---

## Recommended Architecture

### 1. Monorepo Structure

```plaintext
project-provisioning/
│
├── provisioning/                    # CORE SYSTEM (distribution source)
│   ├── core/                        # Core engine
│   │   ├── cli/                     # Main CLI entry
│   │   │   └── provisioning         # Pure Nushell entry point
│   │   ├── nulib/                   # Nushell libraries
│   │   │   ├── lib_provisioning/    # Core library functions
│   │   │   ├── main_provisioning/   # CLI handlers
│   │   │   ├── servers/             # Server management
│   │   │   ├── taskservs/           # Task service management
│   │   │   ├── clusters/            # Cluster management
│   │   │   └── workflows/           # Workflow orchestration
│   │   ├── plugins/                 # System plugins
│   │   │   └── nushell-plugins/     # Nushell plugin sources
│   │   └── scripts/                 # Utility scripts
│   │
│   ├── extensions/                  # Extensible modules
│   │   ├── providers/               # Cloud providers (aws, upcloud, local)
│   │   ├── taskservs/               # Infrastructure services
│   │   │   ├── container-runtime/   # Container runtimes
│   │   │   ├── kubernetes/          # Kubernetes
│   │   │   ├── networking/          # Network services
│   │   │   ├── storage/             # Storage services
│   │   │   ├── databases/           # Database services
│   │   │   └── development/         # Dev tools
│   │   ├── clusters/                # Complete cluster configurations
│   │   └── workflows/               # Workflow templates
│   │
│   ├── platform/                    # Platform services (Rust)
│   │   ├── orchestrator/            # Rust coordination layer
│   │   ├── control-center/          # Web management UI
│   │   ├── control-center-ui/       # UI frontend
│   │   ├── mcp-server/              # Model Context Protocol server
│   │   └── api-gateway/             # REST API gateway
│   │
│   ├── kcl/                         # KCL configuration schemas
│   │   ├── main.ncl                   # Main entry point
│   │   ├── settings.ncl               # Settings schema
│   │   ├── server.ncl                 # Server definitions
│   │   ├── cluster.ncl                # Cluster definitions
│   │   ├── workflows.ncl              # Workflow definitions
│   │   └── docs/                    # KCL documentation
│   │
│   ├── templates/                   # Jinja2 templates
│   │   ├── extensions/              # Extension templates
│   │   ├── services/                # Service templates
│   │   └── workspace/               # Workspace templates
│   │
│   ├── config/                      # Default system configuration
│   │   ├── config.defaults.toml     # System defaults
│   │   └── config-examples/         # Example configs
│   │
│   ├── tools/                       # Build and packaging tools
│   │   ├── build/                   # Build scripts
│   │   ├── package/                 # Packaging tools
│   │   ├── distribution/            # Distribution tools
│   │   └── release/                 # Release automation
│   │
│   └── resources/                   # Static resources (images, assets)
│
├── workspace/                       # RUNTIME DATA (gitignored except templates)
│   ├── infra/                       # Infrastructure instances (gitignored)
│   │   └── .gitkeep
│   ├── config/                      # User configuration (gitignored)
│   │   └── .gitkeep
│   ├── extensions/                  # User extensions (gitignored)
│   │   └── .gitkeep
│   ├── runtime/                     # Runtime data (gitignored)
│   │   ├── logs/
│   │   ├── cache/
│   │   ├── state/
│   │   └── tmp/
│   └── templates/                   # Workspace templates (tracked)
│       ├── minimal/
│       ├── kubernetes/
│       └── multi-cloud/
│
├── distribution/                    # DISTRIBUTION ARTIFACTS (gitignored)
│   ├── packages/                    # Built packages
│   │   ├── provisioning-core-*.tar.gz
│   │   ├── provisioning-platform-*.tar.gz
│   │   ├── provisioning-extensions-*.tar.gz
│   │   └── checksums.txt
│   ├── installers/                  # Installation scripts
│   │   ├── install.sh               # Bash installer
│   │   └── install.nu               # Nushell installer
│   └── registry/                    # Package registry metadata
│       └── index.json
│
├── docs/                            # UNIFIED DOCUMENTATION
│   ├── README.md                    # Documentation index
│   ├── user/                        # User guides
│   │   ├── installation.md
│   │   ├── quick-start.md
│   │   ├── configuration.md
│   │   └── guides/
│   ├── api/                         # API reference
│   │   ├── rest-api.md
│   │   ├── nushell-api.md
│   │   └── kcl-schemas.md
│   ├── architecture/                # Architecture documentation
│   │   ├── overview.md
│   │   ├── decisions/               # ADRs
│   │   └── repo-dist-analysis.md    # This document
│   └── development/                 # Development guides
│       ├── contributing.md
│       ├── building.md
│       ├── testing.md
│       └── releasing.md
│
├── examples/                        # EXAMPLE CONFIGURATIONS
│   ├── minimal/                     # Minimal setup
│   ├── kubernetes-cluster/          # Full K8s cluster
│   ├── multi-cloud/                 # Multi-provider setup
│   └── README.md
│
├── tests/                           # INTEGRATION TESTS
│   ├── e2e/                         # End-to-end tests
│   ├── integration/                 # Integration tests
│   ├── fixtures/                    # Test fixtures
│   └── README.md
│
├── tools/                           # DEVELOPMENT TOOLS
│   ├── build/                       # Build scripts
│   ├── dev-env/                     # Development environment setup
│   └── scripts/                     # Utility scripts
│
├── .github/                         # GitHub configuration
│   ├── workflows/                   # CI/CD workflows
│   │   ├── build.yml
│   │   ├── test.yml
│   │   └── release.yml
│   └── ISSUE_TEMPLATE/
│
├── .coder/                          # Coder configuration (tracked)
│
├── .gitignore                       # Git ignore rules
├── .gitattributes                   # Git attributes
├── Cargo.toml                       # Rust workspace root
├── Justfile                         # Task runner (unified)
├── LICENSE                          # License file
├── README.md                        # Project README
├── CHANGELOG.md                     # Changelog
└── CLAUDE.md                        # AI assistant instructions
```plaintext

### Key Principles

1. **Clear Separation**: Source code (`provisioning/`), runtime data (`workspace/`), build artifacts (`distribution/`)
2. **Single Source of Truth**: One location for each type of content
3. **Gitignore Strategy**: Runtime and build artifacts ignored, templates tracked
4. **Standard Paths**: Follow Unix conventions for installation

---

## Distribution Strategy

### Package Types

#### 1. **provisioning-core** (Required)

**Contents:**

- Nushell CLI and libraries
- Core providers (local, upcloud, aws)
- Essential taskservs (kubernetes, containerd, cilium)
- KCL schemas
- Configuration system
- Templates

**Size:** ~50 MB (compressed)

**Installation:**

```bash
/usr/local/
├── bin/
│   └── provisioning
├── lib/
│   └── provisioning/
│       ├── core/
│       ├── extensions/
│       └── kcl/
└── share/
    └── provisioning/
        ├── templates/
        ├── config/
        └── docs/
```plaintext

#### 2. **provisioning-platform** (Optional)

**Contents:**

- Rust orchestrator binary
- Control center web UI
- MCP server
- API gateway

**Size:** ~30 MB (compressed)

**Installation:**

```bash
/usr/local/
├── bin/
│   ├── provisioning-orchestrator
│   └── provisioning-control-center
└── share/
    └── provisioning/
        └── platform/
```plaintext

#### 3. **provisioning-extensions** (Optional)

**Contents:**

- Additional taskservs (radicle, gitea, postgres, etc.)
- Cluster templates
- Workflow templates

**Size:** ~20 MB (compressed)

**Installation:**

```bash
/usr/local/lib/provisioning/extensions/
├── taskservs/
├── clusters/
└── workflows/
```plaintext

#### 4. **provisioning-plugins** (Optional)

**Contents:**

- Pre-built Nushell plugins
- `nu_plugin_kcl`
- `nu_plugin_tera`
- Other custom plugins

**Size:** ~15 MB (compressed)

**Installation:**

```bash
~/.config/nushell/plugins/
```plaintext

### Installation Paths

#### System Installation (Root)

```bash
/usr/local/
├── bin/
│   ├── provisioning                      # Main CLI
│   ├── provisioning-orchestrator         # Orchestrator binary
│   └── provisioning-control-center       # Control center binary
├── lib/
│   └── provisioning/
│       ├── core/                         # Core Nushell libraries
│       │   ├── nulib/
│       │   └── plugins/
│       ├── extensions/                   # Extensions
│       │   ├── providers/
│       │   ├── taskservs/
│       │   └── clusters/
│       └── kcl/                          # KCL schemas
└── share/
    └── provisioning/
        ├── templates/                    # System templates
        ├── config/                       # Default configs
        │   └── config.defaults.toml
        └── docs/                         # Documentation
```plaintext

#### User Configuration

```bash
~/.provisioning/
├── config/
│   └── config.user.toml                  # User overrides
├── extensions/                           # User extensions
│   ├── providers/
│   ├── taskservs/
│   └── clusters/
├── cache/                                # Cache directory
└── plugins/                              # User plugins
```plaintext

#### Project Workspace

```bash
./workspace/
├── infra/                                # Infrastructure definitions
│   ├── my-cluster/
│   │   ├── config.toml
│   │   ├── servers.yaml
│   │   └── taskservs.yaml
│   └── production/
├── config/                               # Project configuration
│   └── config.toml
├── runtime/                              # Runtime data
│   ├── logs/
│   ├── state/
│   └── cache/
└── extensions/                           # Project-specific extensions
```plaintext

### Configuration Hierarchy

```plaintext
Priority (highest to lowest):
1. CLI flags                              --debug, --infra=my-cluster
2. Runtime overrides                      PROVISIONING_DEBUG=true
3. Project config                         ./workspace/config/config.toml
4. User config                            ~/.provisioning/config/config.user.toml
5. System config                          /usr/local/share/provisioning/config/config.defaults.toml
```plaintext

---

## Build System

### Build Tools Structure

**`provisioning/tools/build/`:**

```plaintext
build/
├── build-system.nu                       # Main build orchestrator
├── package-core.nu                       # Core packaging
├── package-platform.nu                   # Platform packaging
├── package-extensions.nu                 # Extensions packaging
├── package-plugins.nu                    # Plugins packaging
├── create-installers.nu                  # Installer generation
├── validate-package.nu                   # Package validation
└── publish-registry.nu                   # Registry publishing
```plaintext

### Build System Implementation

**`provisioning/tools/build/build-system.nu`:**

```nushell
#!/usr/bin/env nu
# Build system for provisioning project

use ../core/nulib/lib_provisioning/config/accessor.nu *

# Build all packages
export def "main build-all" [
    --version: string = "dev"             # Version to build
    --output: string = "distribution/packages"  # Output directory
] {
    print $"Building all packages version: ($version)"

    let results = {
        core: (build-core $version $output)
        platform: (build-platform $version $output)
        extensions: (build-extensions $version $output)
        plugins: (build-plugins $version $output)
    }

    # Generate checksums
    create-checksums $output

    print "✅ All packages built successfully"
    $results
}

# Build core package
export def "build-core" [
    version: string
    output: string
] -> record {
    print "📦 Building provisioning-core..."

    nu package-core.nu build --version $version --output $output
}

# Build platform package (Rust binaries)
export def "build-platform" [
    version: string
    output: string
] -> record {
    print "📦 Building provisioning-platform..."

    nu package-platform.nu build --version $version --output $output
}

# Build extensions package
export def "build-extensions" [
    version: string
    output: string
] -> record {
    print "📦 Building provisioning-extensions..."

    nu package-extensions.nu build --version $version --output $output
}

# Build plugins package
export def "build-plugins" [
    version: string
    output: string
] -> record {
    print "📦 Building provisioning-plugins..."

    nu package-plugins.nu build --version $version --output $output
}

# Create release artifacts
export def "main release" [
    version: string                       # Release version
    --upload                              # Upload to release server
] {
    print $"🚀 Creating release ($version)"

    # Build all packages
    let packages = (build-all --version $version)

    # Create installers
    create-installers $version

    # Generate release notes
    generate-release-notes $version

    # Upload if requested
    if $upload {
        upload-release $version
    }

    print $"✅ Release ($version) ready"
}

# Create installers
def create-installers [version: string] {
    print "📝 Creating installers..."

    nu create-installers.nu --version $version
}

# Generate release notes
def generate-release-notes [version: string] {
    print "📝 Generating release notes..."

    let changelog = (open CHANGELOG.md)
    let notes = ($changelog | parse-version-section $version)

    $notes | save $"distribution/packages/RELEASE_NOTES_($version).md"
}

# Upload release
def upload-release [version: string] {
    print "⬆️  Uploading release..."

    # Implementation depends on your release infrastructure
    # Could use: GitHub releases, S3, custom server, etc.
}

# Create checksums for all packages
def create-checksums [output: string] {
    print "🔐 Creating checksums..."

    ls ($output | path join "*.tar.gz")
    | each { |file|
        let hash = (sha256sum $file.name | split row ' ' | get 0)
        $"($hash)  (($file.name | path basename))"
    }
    | str join "\n"
    | save ($output | path join "checksums.txt")
}

# Clean build artifacts
export def "main clean" [
    --all                                 # Clean all build artifacts
] {
    print "🧹 Cleaning build artifacts..."

    if ($all) {
        rm -rf distribution/packages
        rm -rf target/
        rm -rf provisioning/platform/target/
    } else {
        rm -rf distribution/packages
    }

    print "✅ Clean complete"
}

# Validate built packages
export def "main validate" [
    package_path: string                  # Package to validate
] {
    print $"🔍 Validating package: ($package_path)"

    nu validate-package.nu $package_path
}

# Show build status
export def "main status" [] {
    print "📊 Build Status"
    print "─" * 60

    let core_exists = ("distribution/packages" | path join "provisioning-core-*.tar.gz" | glob | is-not-empty)
    let platform_exists = ("distribution/packages" | path join "provisioning-platform-*.tar.gz" | glob | is-not-empty)

    print $"Core package:       (if $core_exists { '✅ Built' } else { '❌ Not built' })"
    print $"Platform package:   (if $platform_exists { '✅ Built' } else { '❌ Not built' })"

    if ("distribution/packages" | path exists) {
        let packages = (ls distribution/packages | where name =~ ".tar.gz")
        print $"\nTotal packages: (($packages | length))"
        $packages | select name size
    }
}
```plaintext

### Justfile Integration

**`Justfile`:**

```makefile
# Provisioning Build System
# Use 'just --list' to see all available commands

# Default recipe
default:
    @just --list

# Development tasks
alias d := dev-check
alias t := test
alias b := build

# Build all packages
build VERSION="dev":
    nu provisioning/tools/build/build-system.nu build-all --version {{VERSION}}

# Build core package only
build-core VERSION="dev":
    nu provisioning/tools/build/build-system.nu build-core {{VERSION}}

# Build platform binaries
build-platform VERSION="dev":
    cargo build --release --workspace --manifest-path provisioning/platform/Cargo.toml
    nu provisioning/tools/build/build-system.nu build-platform {{VERSION}}

# Run development checks
dev-check:
    @echo "🔍 Running development checks..."
    cargo check --workspace --manifest-path provisioning/platform/Cargo.toml
    cargo clippy --workspace --manifest-path provisioning/platform/Cargo.toml
    nu provisioning/tools/build/validate-nushell.nu

# Run tests
test:
    @echo "🧪 Running tests..."
    cargo test --workspace --manifest-path provisioning/platform/Cargo.toml
    nu tests/run-all-tests.nu

# Run integration tests
test-e2e:
    @echo "🔬 Running E2E tests..."
    nu tests/e2e/run-e2e.nu

# Format code
fmt:
    cargo fmt --all --manifest-path provisioning/platform/Cargo.toml
    nu provisioning/tools/build/format-nushell.nu

# Clean build artifacts
clean:
    nu provisioning/tools/build/build-system.nu clean

# Clean all (including Rust target/)
clean-all:
    nu provisioning/tools/build/build-system.nu clean --all
    cargo clean --manifest-path provisioning/platform/Cargo.toml

# Create release
release VERSION:
    @echo "🚀 Creating release {{VERSION}}..."
    nu provisioning/tools/build/build-system.nu release {{VERSION}}

# Install from source
install:
    @echo "📦 Installing from source..."
    just build
    sudo nu distribution/installers/install.nu --from-source

# Install development version (symlink)
install-dev:
    @echo "🔗 Installing development version..."
    sudo ln -sf $(pwd)/provisioning/core/cli/provisioning /usr/local/bin/provisioning
    @echo "✅ Development installation complete"

# Uninstall
uninstall:
    @echo "🗑️  Uninstalling..."
    sudo rm -f /usr/local/bin/provisioning
    sudo rm -rf /usr/local/lib/provisioning
    sudo rm -rf /usr/local/share/provisioning

# Show build status
status:
    nu provisioning/tools/build/build-system.nu status

# Validate package
validate PACKAGE:
    nu provisioning/tools/build/build-system.nu validate {{PACKAGE}}

# Start development environment
dev-start:
    @echo "🚀 Starting development environment..."
    cd provisioning/platform/orchestrator && cargo run

# Watch and rebuild on changes
watch:
    @echo "👀 Watching for changes..."
    cargo watch -x 'check --workspace --manifest-path provisioning/platform/Cargo.toml'

# Update dependencies
update-deps:
    cargo update --manifest-path provisioning/platform/Cargo.toml
    nu provisioning/tools/build/update-nushell-deps.nu

# Generate documentation
docs:
    @echo "📚 Generating documentation..."
    cargo doc --workspace --no-deps --manifest-path provisioning/platform/Cargo.toml
    nu provisioning/tools/build/generate-docs.nu

# Benchmark
bench:
    cargo bench --workspace --manifest-path provisioning/platform/Cargo.toml

# Check licenses
check-licenses:
    cargo deny check licenses --manifest-path provisioning/platform/Cargo.toml

# Security audit
audit:
    cargo audit --file provisioning/platform/Cargo.lock
```plaintext

---

## Installation System

### Installer Script

**`distribution/installers/install.nu`:**

```nushell
#!/usr/bin/env nu
# Provisioning installation script

const DEFAULT_PREFIX = "/usr/local"
const REPO_URL = "https://releases.provisioning.io"

# Main installation command
def main [
    --prefix: string = $DEFAULT_PREFIX    # Installation prefix
    --version: string = "latest"          # Version to install
    --from-source                         # Install from source (development)
    --packages: list<string> = ["core"]   # Packages to install
] {
    print "📦 Provisioning Installation"
    print "─" * 60

    # Check prerequisites
    check-prerequisites

    # Install packages
    if $from_source {
        install-from-source $prefix
    } else {
        install-from-release $prefix $version $packages
    }

    # Post-installation
    post-install $prefix

    print ""
    print "✅ Installation complete!"
    print $"Run 'provisioning --help' to get started"
}

# Check prerequisites
def check-prerequisites [] {
    print "🔍 Checking prerequisites..."

    # Check for Nushell
    if (which nu | is-empty) {
        error make {
            msg: "Nushell not found. Please install Nushell first: https://nushell.sh"
        }
    }

    let nu_version = (nu --version | parse "{name} {version}" | get 0.version)
    print $"  ✓ Nushell ($nu_version)"

    # Check for required tools
    if (which tar | is-empty) {
        error make { msg: "tar not found" }
    }

    if (which curl | is-empty) and (which wget | is-empty) {
        error make { msg: "curl or wget required" }
    }

    print "  ✓ All prerequisites met"
}

# Install from source
def install-from-source [prefix: string] {
    print "📦 Installing from source..."

    # Check if we're in the source directory
    if not ("provisioning" | path exists) {
        error make { msg: "Must run from project root" }
    }

    # Create installation directories
    create-install-dirs $prefix

    # Copy files
    print "  Copying core files..."
    cp -r provisioning/core/nulib $"($prefix)/lib/provisioning/core/"
    cp -r provisioning/extensions $"($prefix)/lib/provisioning/"
    cp -r provisioning/kcl $"($prefix)/lib/provisioning/"
    cp -r provisioning/templates $"($prefix)/share/provisioning/"
    cp -r provisioning/config $"($prefix)/share/provisioning/"

    # Create CLI wrapper
    create-cli-wrapper $prefix

    print "  ✓ Source installation complete"
}

# Install from release
def install-from-release [
    prefix: string
    version: string
    packages: list<string>
] {
    print $"📦 Installing version ($version)..."

    # Download packages
    for package in $packages {
        download-package $package $version
        extract-package $package $version $prefix
    }
}

# Download package
def download-package [package: string, version: string] {
    let filename = $"provisioning-($package)-($version).tar.gz"
    let url = $"($REPO_URL)/($version)/($filename)"

    print $"  Downloading ($package)..."

    if (which curl | is-not-empty) {
        curl -fsSL -o $"/tmp/($filename)" $url
    } else {
        wget -q -O $"/tmp/($filename)" $url
    }
}

# Extract package
def extract-package [package: string, version: string, prefix: string] {
    let filename = $"provisioning-($package)-($version).tar.gz"

    print $"  Installing ($package)..."

    tar xzf $"/tmp/($filename)" -C $prefix
    rm $"/tmp/($filename)"
}

# Create installation directories
def create-install-dirs [prefix: string] {
    mkdir ($prefix | path join "bin")
    mkdir ($prefix | path join "lib" "provisioning" "core")
    mkdir ($prefix | path join "lib" "provisioning" "extensions")
    mkdir ($prefix | path join "share" "provisioning" "templates")
    mkdir ($prefix | path join "share" "provisioning" "config")
    mkdir ($prefix | path join "share" "provisioning" "docs")
}

# Create CLI wrapper
def create-cli-wrapper [prefix: string] {
    let wrapper = $"#!/usr/bin/env nu
# Provisioning CLI wrapper

# Load provisioning library
const PROVISIONING_LIB = \"($prefix)/lib/provisioning\"
const PROVISIONING_SHARE = \"($prefix)/share/provisioning\"

$env.PROVISIONING_ROOT = $PROVISIONING_LIB
$env.PROVISIONING_SHARE = $PROVISIONING_SHARE

# Add to Nushell path
$env.NU_LIB_DIRS = ($env.NU_LIB_DIRS | append $\"($PROVISIONING_LIB)/core/nulib\")

# Load main provisioning module
use ($PROVISIONING_LIB)/core/nulib/main_provisioning/dispatcher.nu *

# Main entry point
def main [...args] {
    dispatch-command $args
}

main ...$args
"

    $wrapper | save ($prefix | path join "bin" "provisioning")
    chmod +x ($prefix | path join "bin" "provisioning")
}

# Post-installation tasks
def post-install [prefix: string] {
    print "🔧 Post-installation setup..."

    # Create user config directory
    let user_config = ($env.HOME | path join ".provisioning")
    if not ($user_config | path exists) {
        mkdir ($user_config | path join "config")
        mkdir ($user_config | path join "extensions")
        mkdir ($user_config | path join "cache")

        # Copy example config
        let example = ($prefix | path join "share" "provisioning" "config" "config-examples" "config.user.toml")
        if ($example | path exists) {
            cp $example ($user_config | path join "config" "config.user.toml")
        }

        print $"  ✓ Created user config directory: ($user_config)"
    }

    # Check if prefix is in PATH
    if not ($env.PATH | any { |p| $p == ($prefix | path join "bin") }) {
        print ""
        print "⚠️  Note: ($prefix)/bin is not in your PATH"
        print "   Add this to your shell configuration:"
        print $"   export PATH=\"($prefix)/bin:$PATH\""
    }
}

# Uninstall provisioning
export def "main uninstall" [
    --prefix: string = $DEFAULT_PREFIX    # Installation prefix
    --keep-config                         # Keep user configuration
] {
    print "🗑️  Uninstalling provisioning..."

    # Remove installed files
    rm -rf ($prefix | path join "bin" "provisioning")
    rm -rf ($prefix | path join "lib" "provisioning")
    rm -rf ($prefix | path join "share" "provisioning")

    # Remove user config if requested
    if not $keep_config {
        let user_config = ($env.HOME | path join ".provisioning")
        if ($user_config | path exists) {
            rm -rf $user_config
            print "  ✓ Removed user configuration"
        }
    }

    print "✅ Uninstallation complete"
}

# Upgrade provisioning
export def "main upgrade" [
    --version: string = "latest"          # Version to upgrade to
    --prefix: string = $DEFAULT_PREFIX    # Installation prefix
] {
    print $"⬆️  Upgrading to version ($version)..."

    # Check current version
    let current = (^provisioning version | parse "{version}" | get 0.version)
    print $"  Current version: ($current)"

    if $current == $version {
        print "  Already at latest version"
        return
    }

    # Backup current installation
    print "  Backing up current installation..."
    let backup = ($prefix | path join "lib" "provisioning.backup")
    mv ($prefix | path join "lib" "provisioning") $backup

    # Install new version
    try {
        install-from-release $prefix $version ["core"]
        print $"  ✅ Upgraded to version ($version)"
        rm -rf $backup
    } catch {
        print "  ❌ Upgrade failed, restoring backup..."
        mv $backup ($prefix | path join "lib" "provisioning")
        error make { msg: "Upgrade failed" }
    }
}
```plaintext

### Bash Installer (For Systems Without Nushell)

**`distribution/installers/install.sh`:**

```bash
#!/usr/bin/env bash
# Provisioning installation script (Bash version)
# This script installs Nushell first, then runs the Nushell installer

set -euo pipefail

DEFAULT_PREFIX="/usr/local"
REPO_URL="https://releases.provisioning.io"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

info() {
    echo -e "${GREEN}✓${NC} $*"
}

warn() {
    echo -e "${YELLOW}⚠${NC} $*"
}

error() {
    echo -e "${RED}✗${NC} $*" >&2
    exit 1
}

# Check if Nushell is installed
check_nushell() {
    if command -v nu >/dev/null 2>&1; then
        info "Nushell is already installed"
        return 0
    else
        warn "Nushell not found"
        return 1
    fi
}

# Install Nushell
install_nushell() {
    echo "📦 Installing Nushell..."

    # Detect OS and architecture
    OS="$(uname -s)"
    ARCH="$(uname -m)"

    case "$OS" in
        Linux*)
            if command -v apt-get >/dev/null 2>&1; then
                sudo apt-get update && sudo apt-get install -y nushell
            elif command -v dnf >/dev/null 2>&1; then
                sudo dnf install -y nushell
            elif command -v brew >/dev/null 2>&1; then
                brew install nushell
            else
                error "Cannot automatically install Nushell. Please install manually: https://nushell.sh"
            fi
            ;;
        Darwin*)
            if command -v brew >/dev/null 2>&1; then
                brew install nushell
            else
                error "Homebrew not found. Install from: https://brew.sh"
            fi
            ;;
        *)
            error "Unsupported operating system: $OS"
            ;;
    esac

    info "Nushell installed successfully"
}

# Main installation
main() {
    echo "📦 Provisioning Installation"
    echo "────────────────────────────────────────────────────────────"

    # Check for Nushell
    if ! check_nushell; then
        read -p "Install Nushell? (y/N) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            install_nushell
        else
            error "Nushell is required. Install from: https://nushell.sh"
        fi
    fi

    # Download Nushell installer
    echo "📥 Downloading installer..."
    INSTALLER_URL="$REPO_URL/latest/install.nu"
    curl -fsSL "$INSTALLER_URL" -o /tmp/install.nu

    # Run Nushell installer
    echo "🚀 Running installer..."
    nu /tmp/install.nu "$@"

    # Cleanup
    rm -f /tmp/install.nu

    info "Installation complete!"
}

# Run main
main "$@"
```plaintext

---

## Implementation Plan

### Phase 1: Repository Restructuring (3-4 days)

#### Day 1: Cleanup and Preparation

**Tasks:**

1. Create backup of current state
2. Analyze and document all workspace directories
3. Identify active workspace vs backups
4. Map all file dependencies

**Commands:**

```bash
# Backup current state
cp -r /Users/Akasha/project-provisioning /Users/Akasha/project-provisioning.backup

# Analyze workspaces
fd workspace -t d > workspace-dirs.txt
```plaintext

**Deliverables:**

- Complete backup
- Workspace analysis document
- Dependency map

#### Day 2: Directory Restructuring

**Tasks:**

1. Consolidate workspace directories
2. Move build artifacts to `distribution/`
3. Remove obsolete directories (`NO/`, `wrks/`, presentation artifacts)
4. Create proper `.gitignore`

**Commands:**

```bash
# Create distribution directory
mkdir -p distribution/{packages,installers,registry}

# Move build artifacts
mv target distribution/
mv provisioning/tools/dist distribution/packages/

# Remove obsolete
rm -rf NO/ wrks/ presentations/
```plaintext

**Deliverables:**

- Clean directory structure
- Updated `.gitignore`
- Migration log

#### Day 3: Update Path References

**Tasks:**

1. Update all hardcoded paths in Nushell scripts
2. Update CLAUDE.md with new paths
3. Update documentation references
4. Test all path changes

**Files to Update:**

- `provisioning/core/nulib/**/*.nu` (~65 files)
- `CLAUDE.md`
- `docs/**/*.md`

**Deliverables:**

- Updated scripts
- Updated documentation
- Test results

#### Day 4: Validation and Documentation

**Tasks:**

1. Run full test suite
2. Verify all commands work
3. Update README.md
4. Create migration guide

**Deliverables:**

- Passing tests
- Updated README
- Migration guide for users

### Phase 2: Build System Implementation (3-4 days)

#### Day 5: Build System Core

**Tasks:**

1. Create `provisioning/tools/build/` structure
2. Implement `build-system.nu`
3. Implement `package-core.nu`
4. Create Justfile

**Files to Create:**

- `provisioning/tools/build/build-system.nu`
- `provisioning/tools/build/package-core.nu`
- `provisioning/tools/build/validate-package.nu`
- `Justfile`

**Deliverables:**

- Working build system
- Core packaging capability
- Justfile with basic recipes

#### Day 6: Platform and Extension Packaging

**Tasks:**

1. Implement `package-platform.nu`
2. Implement `package-extensions.nu`
3. Implement `package-plugins.nu`
4. Add checksum generation

**Deliverables:**

- Platform packaging
- Extension packaging
- Plugin packaging
- Checksum generation

#### Day 7: Package Validation

**Tasks:**

1. Create package validation system
2. Implement integrity checks
3. Create test suite for packages
4. Document package format

**Deliverables:**

- Package validation
- Test suite
- Package format documentation

#### Day 8: Build System Testing

**Tasks:**

1. Test full build pipeline
2. Test all package types
3. Optimize build performance
4. Document build system

**Deliverables:**

- Tested build system
- Performance optimizations
- Build system documentation

### Phase 3: Installation System (2-3 days)

#### Day 9: Nushell Installer

**Tasks:**

1. Create `install.nu`
2. Implement installation logic
3. Implement upgrade logic
4. Implement uninstallation

**Files to Create:**

- `distribution/installers/install.nu`

**Deliverables:**

- Working Nushell installer
- Upgrade mechanism
- Uninstall mechanism

#### Day 10: Bash Installer and CLI

**Tasks:**

1. Create `install.sh`
2. Replace bash CLI wrapper with pure Nushell
3. Update PATH handling
4. Test installation on clean system

**Files to Create:**

- `distribution/installers/install.sh`
- Updated `provisioning/core/cli/provisioning`

**Deliverables:**

- Bash installer
- Pure Nushell CLI
- Installation tests

#### Day 11: Installation Testing

**Tasks:**

1. Test installation on multiple OSes
2. Test upgrade scenarios
3. Test uninstallation
4. Create installation documentation

**Deliverables:**

- Multi-OS installation tests
- Installation guide
- Troubleshooting guide

### Phase 4: Package Registry (Optional, 2-3 days)

#### Day 12: Registry System

**Tasks:**

1. Design registry format
2. Implement registry indexing
3. Create package metadata
4. Implement search functionality

**Files to Create:**

- `provisioning/tools/build/publish-registry.nu`
- `distribution/registry/index.json`

**Deliverables:**

- Registry system
- Package metadata
- Search functionality

#### Day 13: Registry Commands

**Tasks:**

1. Implement `provisioning registry list`
2. Implement `provisioning registry search`
3. Implement `provisioning registry install`
4. Implement `provisioning registry update`

**Deliverables:**

- Registry commands
- Package installation from registry
- Update mechanism

#### Day 14: Registry Hosting

**Tasks:**

1. Set up registry hosting (S3, GitHub releases, etc.)
2. Implement upload mechanism
3. Create CI/CD for automatic publishing
4. Document registry system

**Deliverables:**

- Hosted registry
- CI/CD pipeline
- Registry documentation

### Phase 5: Documentation and Release (2 days)

#### Day 15: Documentation

**Tasks:**

1. Update all documentation for new structure
2. Create user guides
3. Create development guides
4. Create API documentation

**Deliverables:**

- Updated documentation
- User guides
- Developer guides
- API docs

#### Day 16: Release Preparation

**Tasks:**

1. Create CHANGELOG.md
2. Build release packages
3. Test installation from packages
4. Create release announcement

**Deliverables:**

- CHANGELOG
- Release packages
- Installation verification
- Release announcement

---

## Migration Strategy

### For Existing Users

#### Option 1: Clean Migration

```bash
# Backup current workspace
cp -r workspace workspace.backup

# Upgrade to new version
provisioning upgrade --version 3.2.0

# Migrate workspace
provisioning workspace migrate --from workspace.backup --to workspace/
```plaintext

#### Option 2: In-Place Migration

```bash
# Run migration script
provisioning migrate --check  # Dry run
provisioning migrate          # Execute migration
```plaintext

### For Developers

```bash
# Pull latest changes
git pull origin main

# Rebuild
just clean-all
just build

# Reinstall development version
just install-dev

# Verify
provisioning --version
```plaintext

---

## Success Criteria

### Repository Structure

- ✅ Single `workspace/` directory for all runtime data
- ✅ Clear separation: source (`provisioning/`), runtime (`workspace/`), artifacts (`distribution/`)
- ✅ All build artifacts in `distribution/` and gitignored
- ✅ Clean root directory (no `wrks/`, `NO/`, etc.)
- ✅ Unified documentation in `docs/`

### Build System

- ✅ Single command builds all packages: `just build`
- ✅ Packages can be built independently
- ✅ Checksums generated automatically
- ✅ Validation before packaging
- ✅ Build time < 5 minutes for full build

### Installation

- ✅ One-line installation: `curl -fsSL https://get.provisioning.io | sh`
- ✅ Works on Linux and macOS
- ✅ Standard installation paths (`/usr/local/`)
- ✅ User configuration in `~/.provisioning/`
- ✅ Clean uninstallation

### Distribution

- ✅ Packages available at stable URL
- ✅ Automated releases via CI/CD
- ✅ Package registry for extensions
- ✅ Upgrade mechanism works reliably

### Documentation

- ✅ Complete installation guide
- ✅ Quick start guide
- ✅ Developer contributing guide
- ✅ API documentation
- ✅ Architecture documentation

---

## Risks and Mitigations

### Risk 1: Breaking Changes for Existing Users

**Impact:** High
**Probability:** High
**Mitigation:**

- Provide migration script
- Support both old and new paths during transition (v3.2.x)
- Clear migration guide
- Automated backup before migration

### Risk 2: Build System Complexity

**Impact:** Medium
**Probability:** Medium
**Mitigation:**

- Start with simple packaging
- Iterate and improve
- Document thoroughly
- Provide examples

### Risk 3: Installation Path Conflicts

**Impact:** Medium
**Probability:** Low
**Mitigation:**

- Check for existing installations
- Support custom prefix
- Clear uninstallation
- Non-conflicting binary names

### Risk 4: Cross-Platform Issues

**Impact:** High
**Probability:** Medium
**Mitigation:**

- Test on multiple OSes (Linux, macOS)
- Use portable commands
- Provide fallbacks
- Clear error messages

### Risk 5: Dependency Management

**Impact:** Medium
**Probability:** Medium
**Mitigation:**

- Document all dependencies
- Check prerequisites during installation
- Provide installation instructions for dependencies
- Consider bundling critical dependencies

---

## Timeline Summary

| Phase | Duration | Key Deliverables |
|-------|----------|------------------|
| Phase 1: Restructuring | 3-4 days | Clean directory structure, updated paths |
| Phase 2: Build System | 3-4 days | Working build system, all package types |
| Phase 3: Installation | 2-3 days | Installers, pure Nushell CLI |
| Phase 4: Registry (Optional) | 2-3 days | Package registry, extension management |
| Phase 5: Documentation | 2 days | Complete documentation, release |
| **Total** | **12-16 days** | Production-ready distribution system |

---

## Next Steps

1. **Review and Approval** (Day 0)
   - Review this analysis
   - Approve implementation plan
   - Assign resources

2. **Kickoff** (Day 1)
   - Create implementation branch
   - Set up project tracking
   - Begin Phase 1

3. **Weekly Reviews**
   - End of Phase 1: Structure review
   - End of Phase 2: Build system review
   - End of Phase 3: Installation review
   - Final review before release

---

## Conclusion

This comprehensive plan transforms the provisioning system into a professional-grade infrastructure automation platform with:

- **Clean Architecture**: Clear separation of concerns
- **Professional Distribution**: Standard installation paths and packaging
- **Easy Installation**: One-command installation for users
- **Developer Friendly**: Simple build system and clear development workflow
- **Extensible**: Package registry for community extensions
- **Well Documented**: Complete guides for users and developers

The implementation will take approximately **2-3 weeks** and will result in a production-ready system suitable for both individual developers and enterprise deployments.

---

## References

- Current codebase structure
- Unix FHS (Filesystem Hierarchy Standard)
- Rust cargo packaging conventions
- npm/yarn package management patterns
- Homebrew formula best practices
- KCL package management design
