# Repository and Distribution Architecture Analysis\n\n**Date:** 2025-10-01\n**Status:** Analysis Complete - Implementation Planning\n**Author:** Architecture Review\n\n## Executive Summary\n\nThis document analyzes the current project structure and provides a comprehensive plan for optimizing the repository organization and distribution\nstrategy. The goal is to create a professional-grade infrastructure automation system with clear separation of concerns, efficient development\nworkflow, and user-friendly distribution.\n\n---\n\n## Current State Analysis\n\n### Strengths\n\n1. **Clean Core Separation**\n   - `provisioning/` contains the core system\n   - `workspace/` concept for user data\n   - Clear extension points (providers, taskservs, clusters)\n\n2. **Hybrid Architecture**\n   - Rust orchestrator for performance-critical operations\n   - Nushell for business logic and scripting\n   - KCL for type-safe configuration\n\n3. **Modular Design**\n   - Extension system for providers and services\n   - Plugin architecture for Nushell\n   - Template-based code generation\n\n4. **Advanced Features**\n   - Batch workflow system (v3.1.0)\n   - Hybrid orchestrator (v3.0.0)\n   - Token-optimized agent architecture\n\n### Critical Issues\n\n1. **Confusing Root Structure**\n   - Multiple workspace variants: `_workspace/`, `backup-workspace/`, `workspace-librecloud/`\n   - Development artifacts at root: `wrks/`, `NO/`, `target/`\n   - Unclear which workspace is active\n\n2. **Mixed Concerns**\n   - Runtime data intermixed with source code\n   - Build artifacts not properly isolated\n   - Presentations and demos in main repo\n\n3. **Distribution Challenges**\n   - Bash wrapper for CLI entry point (`provisioning/core/cli/provisioning`)\n   - No clear installation mechanism\n   - Missing package management system\n   - Undefined installation paths\n\n4. **Documentation Fragmentation**\n   - Multiple `docs/` locations\n   - Scattered README files\n   - No unified documentation structure\n\n5. **Configuration Complexity**\n   - TOML-based system is good, but paths are unclear\n   - User vs system config separation needs clarification\n   - Installation paths not standardized\n\n---\n\n## Recommended Architecture\n\n### 1. Monorepo Structure\n\n```{$detected_lang}\nproject-provisioning/\n│\n├── provisioning/                    # CORE SYSTEM (distribution source)\n│   ├── core/                        # Core engine\n│   │   ├── cli/                     # Main CLI entry\n│   │   │   └── provisioning         # Pure Nushell entry point\n│   │   ├── nulib/                   # Nushell libraries\n│   │   │   ├── lib_provisioning/    # Core library functions\n│   │   │   ├── main_provisioning/   # CLI handlers\n│   │   │   ├── servers/             # Server management\n│   │   │   ├── taskservs/           # Task service management\n│   │   │   ├── clusters/            # Cluster management\n│   │   │   └── workflows/           # Workflow orchestration\n│   │   ├── plugins/                 # System plugins\n│   │   │   └── nushell-plugins/     # Nushell plugin sources\n│   │   └── scripts/                 # Utility scripts\n│   │\n│   ├── extensions/                  # Extensible modules\n│   │   ├── providers/               # Cloud providers (aws, upcloud, local)\n│   │   ├── taskservs/               # Infrastructure services\n│   │   │   ├── container-runtime/   # Container runtimes\n│   │   │   ├── kubernetes/          # Kubernetes\n│   │   │   ├── networking/          # Network services\n│   │   │   ├── storage/             # Storage services\n│   │   │   ├── databases/           # Database services\n│   │   │   └── development/         # Dev tools\n│   │   ├── clusters/                # Complete cluster configurations\n│   │   └── workflows/               # Workflow templates\n│   │\n│   ├── platform/                    # Platform services (Rust)\n│   │   ├── orchestrator/            # Rust coordination layer\n│   │   ├── control-center/          # Web management UI\n│   │   ├── control-center-ui/       # UI frontend\n│   │   ├── mcp-server/              # Model Context Protocol server\n│   │   └── api-gateway/             # REST API gateway\n│   │\n│   ├── kcl/                         # KCL configuration schemas\n│   │   ├── main.ncl                   # Main entry point\n│   │   ├── settings.ncl               # Settings schema\n│   │   ├── server.ncl                 # Server definitions\n│   │   ├── cluster.ncl                # Cluster definitions\n│   │   ├── workflows.ncl              # Workflow definitions\n│   │   └── docs/                    # KCL documentation\n│   │\n│   ├── templates/                   # Jinja2 templates\n│   │   ├── extensions/              # Extension templates\n│   │   ├── services/                # Service templates\n│   │   └── workspace/               # Workspace templates\n│   │\n│   ├── config/                      # Default system configuration\n│   │   ├── config.defaults.toml     # System defaults\n│   │   └── config-examples/         # Example configs\n│   │\n│   ├── tools/                       # Build and packaging tools\n│   │   ├── build/                   # Build scripts\n│   │   ├── package/                 # Packaging tools\n│   │   ├── distribution/            # Distribution tools\n│   │   └── release/                 # Release automation\n│   │\n│   └── resources/                   # Static resources (images, assets)\n│\n├── workspace/                       # RUNTIME DATA (gitignored except templates)\n│   ├── infra/                       # Infrastructure instances (gitignored)\n│   │   └── .gitkeep\n│   ├── config/                      # User configuration (gitignored)\n│   │   └── .gitkeep\n│   ├── extensions/                  # User extensions (gitignored)\n│   │   └── .gitkeep\n│   ├── runtime/                     # Runtime data (gitignored)\n│   │   ├── logs/\n│   │   ├── cache/\n│   │   ├── state/\n│   │   └── tmp/\n│   └── templates/                   # Workspace templates (tracked)\n│       ├── minimal/\n│       ├── kubernetes/\n│       └── multi-cloud/\n│\n├── distribution/                    # DISTRIBUTION ARTIFACTS (gitignored)\n│   ├── packages/                    # Built packages\n│   │   ├── provisioning-core-*.tar.gz\n│   │   ├── provisioning-platform-*.tar.gz\n│   │   ├── provisioning-extensions-*.tar.gz\n│   │   └── checksums.txt\n│   ├── installers/                  # Installation scripts\n│   │   ├── install.sh               # Bash installer\n│   │   └── install.nu               # Nushell installer\n│   └── registry/                    # Package registry metadata\n│       └── index.json\n│\n├── docs/                            # UNIFIED DOCUMENTATION\n│   ├── README.md                    # Documentation index\n│   ├── user/                        # User guides\n│   │   ├── installation.md\n│   │   ├── quick-start.md\n│   │   ├── configuration.md\n│   │   └── guides/\n│   ├── api/                         # API reference\n│   │   ├── rest-api.md\n│   │   ├── nushell-api.md\n│   │   └── kcl-schemas.md\n│   ├── architecture/                # Architecture documentation\n│   │   ├── overview.md\n│   │   ├── decisions/               # ADRs\n│   │   └── repo-dist-analysis.md    # This document\n│   └── development/                 # Development guides\n│       ├── contributing.md\n│       ├── building.md\n│       ├── testing.md\n│       └── releasing.md\n│\n├── examples/                        # EXAMPLE CONFIGURATIONS\n│   ├── minimal/                     # Minimal setup\n│   ├── kubernetes-cluster/          # Full K8s cluster\n│   ├── multi-cloud/                 # Multi-provider setup\n│   └── README.md\n│\n├── tests/                           # INTEGRATION TESTS\n│   ├── e2e/                         # End-to-end tests\n│   ├── integration/                 # Integration tests\n│   ├── fixtures/                    # Test fixtures\n│   └── README.md\n│\n├── tools/                           # DEVELOPMENT TOOLS\n│   ├── build/                       # Build scripts\n│   ├── dev-env/                     # Development environment setup\n│   └── scripts/                     # Utility scripts\n│\n├── .github/                         # GitHub configuration\n│   ├── workflows/                   # CI/CD workflows\n│   │   ├── build.yml\n│   │   ├── test.yml\n│   │   └── release.yml\n│   └── ISSUE_TEMPLATE/\n│\n├── .coder/                          # Coder configuration (tracked)\n│\n├── .gitignore                       # Git ignore rules\n├── .gitattributes                   # Git attributes\n├── Cargo.toml                       # Rust workspace root\n├── Justfile                         # Task runner (unified)\n├── LICENSE                          # License file\n├── README.md                        # Project README\n├── CHANGELOG.md                     # Changelog\n└── CLAUDE.md                        # AI assistant instructions\n```\n\n### Key Principles\n\n1. **Clear Separation**: Source code (`provisioning/`), runtime data (`workspace/`), build artifacts (`distribution/`)\n2. **Single Source of Truth**: One location for each type of content\n3. **Gitignore Strategy**: Runtime and build artifacts ignored, templates tracked\n4. **Standard Paths**: Follow Unix conventions for installation\n\n---\n\n## Distribution Strategy\n\n### Package Types\n\n#### 1. **provisioning-core** (Required)\n\n**Contents:**\n\n- Nushell CLI and libraries\n- Core providers (local, upcloud, aws)\n- Essential taskservs (kubernetes, containerd, cilium)\n- KCL schemas\n- Configuration system\n- Templates\n\n**Size:** ~50 MB (compressed)\n\n**Installation:**\n\n```{$detected_lang}\n/usr/local/\n├── bin/\n│   └── provisioning\n├── lib/\n│   └── provisioning/\n│       ├── core/\n│       ├── extensions/\n│       └── kcl/\n└── share/\n    └── provisioning/\n        ├── templates/\n        ├── config/\n        └── docs/\n```\n\n#### 2. **provisioning-platform** (Optional)\n\n**Contents:**\n\n- Rust orchestrator binary\n- Control center web UI\n- MCP server\n- API gateway\n\n**Size:** ~30 MB (compressed)\n\n**Installation:**\n\n```{$detected_lang}\n/usr/local/\n├── bin/\n│   ├── provisioning-orchestrator\n│   └── provisioning-control-center\n└── share/\n    └── provisioning/\n        └── platform/\n```\n\n#### 3. **provisioning-extensions** (Optional)\n\n**Contents:**\n\n- Additional taskservs (radicle, gitea, postgres, etc.)\n- Cluster templates\n- Workflow templates\n\n**Size:** ~20 MB (compressed)\n\n**Installation:**\n\n```{$detected_lang}\n/usr/local/lib/provisioning/extensions/\n├── taskservs/\n├── clusters/\n└── workflows/\n```\n\n#### 4. **provisioning-plugins** (Optional)\n\n**Contents:**\n\n- Pre-built Nushell plugins\n- `nu_plugin_kcl`\n- `nu_plugin_tera`\n- Other custom plugins\n\n**Size:** ~15 MB (compressed)\n\n**Installation:**\n\n```{$detected_lang}\n~/.config/nushell/plugins/\n```\n\n### Installation Paths\n\n#### System Installation (Root)\n\n```{$detected_lang}\n/usr/local/\n├── bin/\n│   ├── provisioning                      # Main CLI\n│   ├── provisioning-orchestrator         # Orchestrator binary\n│   └── provisioning-control-center       # Control center binary\n├── lib/\n│   └── provisioning/\n│       ├── core/                         # Core Nushell libraries\n│       │   ├── nulib/\n│       │   └── plugins/\n│       ├── extensions/                   # Extensions\n│       │   ├── providers/\n│       │   ├── taskservs/\n│       │   └── clusters/\n│       └── kcl/                          # KCL schemas\n└── share/\n    └── provisioning/\n        ├── templates/                    # System templates\n        ├── config/                       # Default configs\n        │   └── config.defaults.toml\n        └── docs/                         # Documentation\n```\n\n#### User Configuration\n\n```{$detected_lang}\n~/.provisioning/\n├── config/\n│   └── config.user.toml                  # User overrides\n├── extensions/                           # User extensions\n│   ├── providers/\n│   ├── taskservs/\n│   └── clusters/\n├── cache/                                # Cache directory\n└── plugins/                              # User plugins\n```\n\n#### Project Workspace\n\n```{$detected_lang}\n./workspace/\n├── infra/                                # Infrastructure definitions\n│   ├── my-cluster/\n│   │   ├── config.toml\n│   │   ├── servers.yaml\n│   │   └── taskservs.yaml\n│   └── production/\n├── config/                               # Project configuration\n│   └── config.toml\n├── runtime/                              # Runtime data\n│   ├── logs/\n│   ├── state/\n│   └── cache/\n└── extensions/                           # Project-specific extensions\n```\n\n### Configuration Hierarchy\n\n```{$detected_lang}\nPriority (highest to lowest):\n1. CLI flags                              --debug, --infra=my-cluster\n2. Runtime overrides                      PROVISIONING_DEBUG=true\n3. Project config                         ./workspace/config/config.toml\n4. User config                            ~/.provisioning/config/config.user.toml\n5. System config                          /usr/local/share/provisioning/config/config.defaults.toml\n```\n\n---\n\n## Build System\n\n### Build Tools Structure\n\n**`provisioning/tools/build/`:**\n\n```{$detected_lang}\nbuild/\n├── build-system.nu                       # Main build orchestrator\n├── package-core.nu                       # Core packaging\n├── package-platform.nu                   # Platform packaging\n├── package-extensions.nu                 # Extensions packaging\n├── package-plugins.nu                    # Plugins packaging\n├── create-installers.nu                  # Installer generation\n├── validate-package.nu                   # Package validation\n└── publish-registry.nu                   # Registry publishing\n```\n\n### Build System Implementation\n\n**`provisioning/tools/build/build-system.nu`:**\n\n```{$detected_lang}\n#!/usr/bin/env nu\n# Build system for provisioning project\n\nuse ../core/nulib/lib_provisioning/config/accessor.nu *\n\n# Build all packages\nexport def "main build-all" [\n    --version: string = "dev"             # Version to build\n    --output: string = "distribution/packages"  # Output directory\n] {\n    print $"Building all packages version: ($version)"\n\n    let results = {\n        core: (build-core $version $output)\n        platform: (build-platform $version $output)\n        extensions: (build-extensions $version $output)\n        plugins: (build-plugins $version $output)\n    }\n\n    # Generate checksums\n    create-checksums $output\n\n    print "✅ All packages built successfully"\n    $results\n}\n\n# Build core package\nexport def "build-core" [\n    version: string\n    output: string\n] -> record {\n    print "📦 Building provisioning-core..."\n\n    nu package-core.nu build --version $version --output $output\n}\n\n# Build platform package (Rust binaries)\nexport def "build-platform" [\n    version: string\n    output: string\n] -> record {\n    print "📦 Building provisioning-platform..."\n\n    nu package-platform.nu build --version $version --output $output\n}\n\n# Build extensions package\nexport def "build-extensions" [\n    version: string\n    output: string\n] -> record {\n    print "📦 Building provisioning-extensions..."\n\n    nu package-extensions.nu build --version $version --output $output\n}\n\n# Build plugins package\nexport def "build-plugins" [\n    version: string\n    output: string\n] -> record {\n    print "📦 Building provisioning-plugins..."\n\n    nu package-plugins.nu build --version $version --output $output\n}\n\n# Create release artifacts\nexport def "main release" [\n    version: string                       # Release version\n    --upload                              # Upload to release server\n] {\n    print $"🚀 Creating release ($version)"\n\n    # Build all packages\n    let packages = (build-all --version $version)\n\n    # Create installers\n    create-installers $version\n\n    # Generate release notes\n    generate-release-notes $version\n\n    # Upload if requested\n    if $upload {\n        upload-release $version\n    }\n\n    print $"✅ Release ($version) ready"\n}\n\n# Create installers\ndef create-installers [version: string] {\n    print "📝 Creating installers..."\n\n    nu create-installers.nu --version $version\n}\n\n# Generate release notes\ndef generate-release-notes [version: string] {\n    print "📝 Generating release notes..."\n\n    let changelog = (open CHANGELOG.md)\n    let notes = ($changelog | parse-version-section $version)\n\n    $notes | save $"distribution/packages/RELEASE_NOTES_($version).md"\n}\n\n# Upload release\ndef upload-release [version: string] {\n    print "⬆️  Uploading release..."\n\n    # Implementation depends on your release infrastructure\n    # Could use: GitHub releases, S3, custom server, etc.\n}\n\n# Create checksums for all packages\ndef create-checksums [output: string] {\n    print "🔐 Creating checksums..."\n\n    ls ($output | path join "*.tar.gz")\n    | each { |file|\n        let hash = (sha256sum $file.name | split row ' ' | get 0)\n        $"($hash)  (($file.name | path basename))"\n    }\n    | str join "\n"\n    | save ($output | path join "checksums.txt")\n}\n\n# Clean build artifacts\nexport def "main clean" [\n    --all                                 # Clean all build artifacts\n] {\n    print "🧹 Cleaning build artifacts..."\n\n    if ($all) {\n        rm -rf distribution/packages\n        rm -rf target/\n        rm -rf provisioning/platform/target/\n    } else {\n        rm -rf distribution/packages\n    }\n\n    print "✅ Clean complete"\n}\n\n# Validate built packages\nexport def "main validate" [\n    package_path: string                  # Package to validate\n] {\n    print $"🔍 Validating package: ($package_path)"\n\n    nu validate-package.nu $package_path\n}\n\n# Show build status\nexport def "main status" [] {\n    print "📊 Build Status"\n    print "─" * 60\n\n    let core_exists = ("distribution/packages" | path join "provisioning-core-*.tar.gz" | glob | is-not-empty)\n    let platform_exists = ("distribution/packages" | path join "provisioning-platform-*.tar.gz" | glob | is-not-empty)\n\n    print $"Core package:       (if $core_exists { '✅ Built' } else { '❌ Not built' })"\n    print $"Platform package:   (if $platform_exists { '✅ Built' } else { '❌ Not built' })"\n\n    if ("distribution/packages" | path exists) {\n        let packages = (ls distribution/packages | where name =~ ".tar.gz")\n        print $"\nTotal packages: (($packages | length))"\n        $packages | select name size\n    }\n}\n```\n\n### Justfile Integration\n\n**`Justfile`:**\n\n```{$detected_lang}\n# Provisioning Build System\n# Use 'just --list' to see all available commands\n\n# Default recipe\ndefault:\n    @just --list\n\n# Development tasks\nalias d := dev-check\nalias t := test\nalias b := build\n\n# Build all packages\nbuild VERSION="dev":\n    nu provisioning/tools/build/build-system.nu build-all --version {{VERSION}}\n\n# Build core package only\nbuild-core VERSION="dev":\n    nu provisioning/tools/build/build-system.nu build-core {{VERSION}}\n\n# Build platform binaries\nbuild-platform VERSION="dev":\n    cargo build --release --workspace --manifest-path provisioning/platform/Cargo.toml\n    nu provisioning/tools/build/build-system.nu build-platform {{VERSION}}\n\n# Run development checks\ndev-check:\n    @echo "🔍 Running development checks..."\n    cargo check --workspace --manifest-path provisioning/platform/Cargo.toml\n    cargo clippy --workspace --manifest-path provisioning/platform/Cargo.toml\n    nu provisioning/tools/build/validate-nushell.nu\n\n# Run tests\ntest:\n    @echo "🧪 Running tests..."\n    cargo test --workspace --manifest-path provisioning/platform/Cargo.toml\n    nu tests/run-all-tests.nu\n\n# Run integration tests\ntest-e2e:\n    @echo "🔬 Running E2E tests..."\n    nu tests/e2e/run-e2e.nu\n\n# Format code\nfmt:\n    cargo fmt --all --manifest-path provisioning/platform/Cargo.toml\n    nu provisioning/tools/build/format-nushell.nu\n\n# Clean build artifacts\nclean:\n    nu provisioning/tools/build/build-system.nu clean\n\n# Clean all (including Rust target/)\nclean-all:\n    nu provisioning/tools/build/build-system.nu clean --all\n    cargo clean --manifest-path provisioning/platform/Cargo.toml\n\n# Create release\nrelease VERSION:\n    @echo "🚀 Creating release {{VERSION}}..."\n    nu provisioning/tools/build/build-system.nu release {{VERSION}}\n\n# Install from source\ninstall:\n    @echo "📦 Installing from source..."\n    just build\n    sudo nu distribution/installers/install.nu --from-source\n\n# Install development version (symlink)\ninstall-dev:\n    @echo "🔗 Installing development version..."\n    sudo ln -sf $(pwd)/provisioning/core/cli/provisioning /usr/local/bin/provisioning\n    @echo "✅ Development installation complete"\n\n# Uninstall\nuninstall:\n    @echo "🗑️  Uninstalling..."\n    sudo rm -f /usr/local/bin/provisioning\n    sudo rm -rf /usr/local/lib/provisioning\n    sudo rm -rf /usr/local/share/provisioning\n\n# Show build status\nstatus:\n    nu provisioning/tools/build/build-system.nu status\n\n# Validate package\nvalidate PACKAGE:\n    nu provisioning/tools/build/build-system.nu validate {{PACKAGE}}\n\n# Start development environment\ndev-start:\n    @echo "🚀 Starting development environment..."\n    cd provisioning/platform/orchestrator && cargo run\n\n# Watch and rebuild on changes\nwatch:\n    @echo "👀 Watching for changes..."\n    cargo watch -x 'check --workspace --manifest-path provisioning/platform/Cargo.toml'\n\n# Update dependencies\nupdate-deps:\n    cargo update --manifest-path provisioning/platform/Cargo.toml\n    nu provisioning/tools/build/update-nushell-deps.nu\n\n# Generate documentation\ndocs:\n    @echo "📚 Generating documentation..."\n    cargo doc --workspace --no-deps --manifest-path provisioning/platform/Cargo.toml\n    nu provisioning/tools/build/generate-docs.nu\n\n# Benchmark\nbench:\n    cargo bench --workspace --manifest-path provisioning/platform/Cargo.toml\n\n# Check licenses\ncheck-licenses:\n    cargo deny check licenses --manifest-path provisioning/platform/Cargo.toml\n\n# Security audit\naudit:\n    cargo audit --file provisioning/platform/Cargo.lock\n```\n\n---\n\n## Installation System\n\n### Installer Script\n\n**`distribution/installers/install.nu`:**\n\n```{$detected_lang}\n#!/usr/bin/env nu\n# Provisioning installation script\n\nconst DEFAULT_PREFIX = "/usr/local"\nconst REPO_URL = "https://releases.provisioning.io"\n\n# Main installation command\ndef main [\n    --prefix: string = $DEFAULT_PREFIX    # Installation prefix\n    --version: string = "latest"          # Version to install\n    --from-source                         # Install from source (development)\n    --packages: list<string> = ["core"]   # Packages to install\n] {\n    print "📦 Provisioning Installation"\n    print "─" * 60\n\n    # Check prerequisites\n    check-prerequisites\n\n    # Install packages\n    if $from_source {\n        install-from-source $prefix\n    } else {\n        install-from-release $prefix $version $packages\n    }\n\n    # Post-installation\n    post-install $prefix\n\n    print ""\n    print "✅ Installation complete!"\n    print $"Run 'provisioning --help' to get started"\n}\n\n# Check prerequisites\ndef check-prerequisites [] {\n    print "🔍 Checking prerequisites..."\n\n    # Check for Nushell\n    if (which nu | is-empty) {\n        error make {\n            msg: "Nushell not found. Please install Nushell first: https://nushell.sh"\n        }\n    }\n\n    let nu_version = (nu --version | parse "{name} {version}" | get 0.version)\n    print $"  ✓ Nushell ($nu_version)"\n\n    # Check for required tools\n    if (which tar | is-empty) {\n        error make { msg: "tar not found" }\n    }\n\n    if (which curl | is-empty) and (which wget | is-empty) {\n        error make { msg: "curl or wget required" }\n    }\n\n    print "  ✓ All prerequisites met"\n}\n\n# Install from source\ndef install-from-source [prefix: string] {\n    print "📦 Installing from source..."\n\n    # Check if we're in the source directory\n    if not ("provisioning" | path exists) {\n        error make { msg: "Must run from project root" }\n    }\n\n    # Create installation directories\n    create-install-dirs $prefix\n\n    # Copy files\n    print "  Copying core files..."\n    cp -r provisioning/core/nulib $"($prefix)/lib/provisioning/core/"\n    cp -r provisioning/extensions $"($prefix)/lib/provisioning/"\n    cp -r provisioning/kcl $"($prefix)/lib/provisioning/"\n    cp -r provisioning/templates $"($prefix)/share/provisioning/"\n    cp -r provisioning/config $"($prefix)/share/provisioning/"\n\n    # Create CLI wrapper\n    create-cli-wrapper $prefix\n\n    print "  ✓ Source installation complete"\n}\n\n# Install from release\ndef install-from-release [\n    prefix: string\n    version: string\n    packages: list<string>\n] {\n    print $"📦 Installing version ($version)..."\n\n    # Download packages\n    for package in $packages {\n        download-package $package $version\n        extract-package $package $version $prefix\n    }\n}\n\n# Download package\ndef download-package [package: string, version: string] {\n    let filename = $"provisioning-($package)-($version).tar.gz"\n    let url = $"($REPO_URL)/($version)/($filename)"\n\n    print $"  Downloading ($package)..."\n\n    if (which curl | is-not-empty) {\n        curl -fsSL -o $"/tmp/($filename)" $url\n    } else {\n        wget -q -O $"/tmp/($filename)" $url\n    }\n}\n\n# Extract package\ndef extract-package [package: string, version: string, prefix: string] {\n    let filename = $"provisioning-($package)-($version).tar.gz"\n\n    print $"  Installing ($package)..."\n\n    tar xzf $"/tmp/($filename)" -C $prefix\n    rm $"/tmp/($filename)"\n}\n\n# Create installation directories\ndef create-install-dirs [prefix: string] {\n    mkdir ($prefix | path join "bin")\n    mkdir ($prefix | path join "lib" "provisioning" "core")\n    mkdir ($prefix | path join "lib" "provisioning" "extensions")\n    mkdir ($prefix | path join "share" "provisioning" "templates")\n    mkdir ($prefix | path join "share" "provisioning" "config")\n    mkdir ($prefix | path join "share" "provisioning" "docs")\n}\n\n# Create CLI wrapper\ndef create-cli-wrapper [prefix: string] {\n    let wrapper = $"#!/usr/bin/env nu\n# Provisioning CLI wrapper\n\n# Load provisioning library\nconst PROVISIONING_LIB = \"($prefix)/lib/provisioning\"\nconst PROVISIONING_SHARE = \"($prefix)/share/provisioning\"\n\n$env.PROVISIONING_ROOT = $PROVISIONING_LIB\n$env.PROVISIONING_SHARE = $PROVISIONING_SHARE\n\n# Add to Nushell path\n$env.NU_LIB_DIRS = ($env.NU_LIB_DIRS | append $\"($PROVISIONING_LIB)/core/nulib\")\n\n# Load main provisioning module\nuse ($PROVISIONING_LIB)/core/nulib/main_provisioning/dispatcher.nu *\n\n# Main entry point\ndef main [...args] {\n    dispatch-command $args\n}\n\nmain ...$args\n"\n\n    $wrapper | save ($prefix | path join "bin" "provisioning")\n    chmod +x ($prefix | path join "bin" "provisioning")\n}\n\n# Post-installation tasks\ndef post-install [prefix: string] {\n    print "🔧 Post-installation setup..."\n\n    # Create user config directory\n    let user_config = ($env.HOME | path join ".provisioning")\n    if not ($user_config | path exists) {\n        mkdir ($user_config | path join "config")\n        mkdir ($user_config | path join "extensions")\n        mkdir ($user_config | path join "cache")\n\n        # Copy example config\n        let example = ($prefix | path join "share" "provisioning" "config" "config-examples" "config.user.toml")\n        if ($example | path exists) {\n            cp $example ($user_config | path join "config" "config.user.toml")\n        }\n\n        print $"  ✓ Created user config directory: ($user_config)"\n    }\n\n    # Check if prefix is in PATH\n    if not ($env.PATH | any { |p| $p == ($prefix | path join "bin") }) {\n        print ""\n        print "⚠️  Note: ($prefix)/bin is not in your PATH"\n        print "   Add this to your shell configuration:"\n        print $"   export PATH=\"($prefix)/bin:$PATH\""\n    }\n}\n\n# Uninstall provisioning\nexport def "main uninstall" [\n    --prefix: string = $DEFAULT_PREFIX    # Installation prefix\n    --keep-config                         # Keep user configuration\n] {\n    print "🗑️  Uninstalling provisioning..."\n\n    # Remove installed files\n    rm -rf ($prefix | path join "bin" "provisioning")\n    rm -rf ($prefix | path join "lib" "provisioning")\n    rm -rf ($prefix | path join "share" "provisioning")\n\n    # Remove user config if requested\n    if not $keep_config {\n        let user_config = ($env.HOME | path join ".provisioning")\n        if ($user_config | path exists) {\n            rm -rf $user_config\n            print "  ✓ Removed user configuration"\n        }\n    }\n\n    print "✅ Uninstallation complete"\n}\n\n# Upgrade provisioning\nexport def "main upgrade" [\n    --version: string = "latest"          # Version to upgrade to\n    --prefix: string = $DEFAULT_PREFIX    # Installation prefix\n] {\n    print $"⬆️  Upgrading to version ($version)..."\n\n    # Check current version\n    let current = (^provisioning version | parse "{version}" | get 0.version)\n    print $"  Current version: ($current)"\n\n    if $current == $version {\n        print "  Already at latest version"\n        return\n    }\n\n    # Backup current installation\n    print "  Backing up current installation..."\n    let backup = ($prefix | path join "lib" "provisioning.backup")\n    mv ($prefix | path join "lib" "provisioning") $backup\n\n    # Install new version\n    try {\n        install-from-release $prefix $version ["core"]\n        print $"  ✅ Upgraded to version ($version)"\n        rm -rf $backup\n    } catch {\n        print "  ❌ Upgrade failed, restoring backup..."\n        mv $backup ($prefix | path join "lib" "provisioning")\n        error make { msg: "Upgrade failed" }\n    }\n}\n```\n\n### Bash Installer (For Systems Without Nushell)\n\n**`distribution/installers/install.sh`:**\n\n```{$detected_lang}\n#!/usr/bin/env bash\n# Provisioning installation script (Bash version)\n# This script installs Nushell first, then runs the Nushell installer\n\nset -euo pipefail\n\nDEFAULT_PREFIX="/usr/local"\nREPO_URL="https://releases.provisioning.io"\n\n# Colors\nRED='\033[0;31m'\nGREEN='\033[0;32m'\nYELLOW='\033[1;33m'\nNC='\033[0m' # No Color\n\ninfo() {\n    echo -e "${GREEN}✓${NC} $*"\n}\n\nwarn() {\n    echo -e "${YELLOW}⚠${NC} $*"\n}\n\nerror() {\n    echo -e "${RED}✗${NC} $*" >&2\n    exit 1\n}\n\n# Check if Nushell is installed\ncheck_nushell() {\n    if command -v nu >/dev/null 2>&1; then\n        info "Nushell is already installed"\n        return 0\n    else\n        warn "Nushell not found"\n        return 1\n    fi\n}\n\n# Install Nushell\ninstall_nushell() {\n    echo "📦 Installing Nushell..."\n\n    # Detect OS and architecture\n    OS="$(uname -s)"\n    ARCH="$(uname -m)"\n\n    case "$OS" in\n        Linux*)\n            if command -v apt-get >/dev/null 2>&1; then\n                sudo apt-get update && sudo apt-get install -y nushell\n            elif command -v dnf >/dev/null 2>&1; then\n                sudo dnf install -y nushell\n            elif command -v brew >/dev/null 2>&1; then\n                brew install nushell\n            else\n                error "Cannot automatically install Nushell. Please install manually: https://nushell.sh"\n            fi\n            ;;\n        Darwin*)\n            if command -v brew >/dev/null 2>&1; then\n                brew install nushell\n            else\n                error "Homebrew not found. Install from: https://brew.sh"\n            fi\n            ;;\n        *)\n            error "Unsupported operating system: $OS"\n            ;;\n    esac\n\n    info "Nushell installed successfully"\n}\n\n# Main installation\nmain() {\n    echo "📦 Provisioning Installation"\n    echo "────────────────────────────────────────────────────────────"\n\n    # Check for Nushell\n    if ! check_nushell; then\n        read -p "Install Nushell? (y/N) " -n 1 -r\n        echo\n        if [[ $REPLY =~ ^[Yy]$ ]]; then\n            install_nushell\n        else\n            error "Nushell is required. Install from: https://nushell.sh"\n        fi\n    fi\n\n    # Download Nushell installer\n    echo "📥 Downloading installer..."\n    INSTALLER_URL="$REPO_URL/latest/install.nu"\n    curl -fsSL "$INSTALLER_URL" -o /tmp/install.nu\n\n    # Run Nushell installer\n    echo "🚀 Running installer..."\n    nu /tmp/install.nu "$@"\n\n    # Cleanup\n    rm -f /tmp/install.nu\n\n    info "Installation complete!"\n}\n\n# Run main\nmain "$@"\n```\n\n---\n\n## Implementation Plan\n\n### Phase 1: Repository Restructuring (3-4 days)\n\n#### Day 1: Cleanup and Preparation\n\n**Tasks:**\n\n1. Create backup of current state\n2. Analyze and document all workspace directories\n3. Identify active workspace vs backups\n4. Map all file dependencies\n\n**Commands:**\n\n```{$detected_lang}\n# Backup current state\ncp -r /Users/Akasha/project-provisioning /Users/Akasha/project-provisioning.backup\n\n# Analyze workspaces\nfd workspace -t d > workspace-dirs.txt\n```\n\n**Deliverables:**\n\n- Complete backup\n- Workspace analysis document\n- Dependency map\n\n#### Day 2: Directory Restructuring\n\n**Tasks:**\n\n1. Consolidate workspace directories\n2. Move build artifacts to `distribution/`\n3. Remove obsolete directories (`NO/`, `wrks/`, presentation artifacts)\n4. Create proper `.gitignore`\n\n**Commands:**\n\n```{$detected_lang}\n# Create distribution directory\nmkdir -p distribution/{packages,installers,registry}\n\n# Move build artifacts\nmv target distribution/\nmv provisioning/tools/dist distribution/packages/\n\n# Remove obsolete\nrm -rf NO/ wrks/ presentations/\n```\n\n**Deliverables:**\n\n- Clean directory structure\n- Updated `.gitignore`\n- Migration log\n\n#### Day 3: Update Path References\n\n**Tasks:**\n\n1. Update all hardcoded paths in Nushell scripts\n2. Update CLAUDE.md with new paths\n3. Update documentation references\n4. Test all path changes\n\n**Files to Update:**\n\n- `provisioning/core/nulib/**/*.nu` (~65 files)\n- `CLAUDE.md`\n- `docs/**/*.md`\n\n**Deliverables:**\n\n- Updated scripts\n- Updated documentation\n- Test results\n\n#### Day 4: Validation and Documentation\n\n**Tasks:**\n\n1. Run full test suite\n2. Verify all commands work\n3. Update README.md\n4. Create migration guide\n\n**Deliverables:**\n\n- Passing tests\n- Updated README\n- Migration guide for users\n\n### Phase 2: Build System Implementation (3-4 days)\n\n#### Day 5: Build System Core\n\n**Tasks:**\n\n1. Create `provisioning/tools/build/` structure\n2. Implement `build-system.nu`\n3. Implement `package-core.nu`\n4. Create Justfile\n\n**Files to Create:**\n\n- `provisioning/tools/build/build-system.nu`\n- `provisioning/tools/build/package-core.nu`\n- `provisioning/tools/build/validate-package.nu`\n- `Justfile`\n\n**Deliverables:**\n\n- Working build system\n- Core packaging capability\n- Justfile with basic recipes\n\n#### Day 6: Platform and Extension Packaging\n\n**Tasks:**\n\n1. Implement `package-platform.nu`\n2. Implement `package-extensions.nu`\n3. Implement `package-plugins.nu`\n4. Add checksum generation\n\n**Deliverables:**\n\n- Platform packaging\n- Extension packaging\n- Plugin packaging\n- Checksum generation\n\n#### Day 7: Package Validation\n\n**Tasks:**\n\n1. Create package validation system\n2. Implement integrity checks\n3. Create test suite for packages\n4. Document package format\n\n**Deliverables:**\n\n- Package validation\n- Test suite\n- Package format documentation\n\n#### Day 8: Build System Testing\n\n**Tasks:**\n\n1. Test full build pipeline\n2. Test all package types\n3. Optimize build performance\n4. Document build system\n\n**Deliverables:**\n\n- Tested build system\n- Performance optimizations\n- Build system documentation\n\n### Phase 3: Installation System (2-3 days)\n\n#### Day 9: Nushell Installer\n\n**Tasks:**\n\n1. Create `install.nu`\n2. Implement installation logic\n3. Implement upgrade logic\n4. Implement uninstallation\n\n**Files to Create:**\n\n- `distribution/installers/install.nu`\n\n**Deliverables:**\n\n- Working Nushell installer\n- Upgrade mechanism\n- Uninstall mechanism\n\n#### Day 10: Bash Installer and CLI\n\n**Tasks:**\n\n1. Create `install.sh`\n2. Replace bash CLI wrapper with pure Nushell\n3. Update PATH handling\n4. Test installation on clean system\n\n**Files to Create:**\n\n- `distribution/installers/install.sh`\n- Updated `provisioning/core/cli/provisioning`\n\n**Deliverables:**\n\n- Bash installer\n- Pure Nushell CLI\n- Installation tests\n\n#### Day 11: Installation Testing\n\n**Tasks:**\n\n1. Test installation on multiple OSes\n2. Test upgrade scenarios\n3. Test uninstallation\n4. Create installation documentation\n\n**Deliverables:**\n\n- Multi-OS installation tests\n- Installation guide\n- Troubleshooting guide\n\n### Phase 4: Package Registry (Optional, 2-3 days)\n\n#### Day 12: Registry System\n\n**Tasks:**\n\n1. Design registry format\n2. Implement registry indexing\n3. Create package metadata\n4. Implement search functionality\n\n**Files to Create:**\n\n- `provisioning/tools/build/publish-registry.nu`\n- `distribution/registry/index.json`\n\n**Deliverables:**\n\n- Registry system\n- Package metadata\n- Search functionality\n\n#### Day 13: Registry Commands\n\n**Tasks:**\n\n1. Implement `provisioning registry list`\n2. Implement `provisioning registry search`\n3. Implement `provisioning registry install`\n4. Implement `provisioning registry update`\n\n**Deliverables:**\n\n- Registry commands\n- Package installation from registry\n- Update mechanism\n\n#### Day 14: Registry Hosting\n\n**Tasks:**\n\n1. Set up registry hosting (S3, GitHub releases, etc.)\n2. Implement upload mechanism\n3. Create CI/CD for automatic publishing\n4. Document registry system\n\n**Deliverables:**\n\n- Hosted registry\n- CI/CD pipeline\n- Registry documentation\n\n### Phase 5: Documentation and Release (2 days)\n\n#### Day 15: Documentation\n\n**Tasks:**\n\n1. Update all documentation for new structure\n2. Create user guides\n3. Create development guides\n4. Create API documentation\n\n**Deliverables:**\n\n- Updated documentation\n- User guides\n- Developer guides\n- API docs\n\n#### Day 16: Release Preparation\n\n**Tasks:**\n\n1. Create CHANGELOG.md\n2. Build release packages\n3. Test installation from packages\n4. Create release announcement\n\n**Deliverables:**\n\n- CHANGELOG\n- Release packages\n- Installation verification\n- Release announcement\n\n---\n\n## Migration Strategy\n\n### For Existing Users\n\n#### Option 1: Clean Migration\n\n```{$detected_lang}\n# Backup current workspace\ncp -r workspace workspace.backup\n\n# Upgrade to new version\nprovisioning upgrade --version 3.2.0\n\n# Migrate workspace\nprovisioning workspace migrate --from workspace.backup --to workspace/\n```\n\n#### Option 2: In-Place Migration\n\n```{$detected_lang}\n# Run migration script\nprovisioning migrate --check  # Dry run\nprovisioning migrate          # Execute migration\n```\n\n### For Developers\n\n```{$detected_lang}\n# Pull latest changes\ngit pull origin main\n\n# Rebuild\njust clean-all\njust build\n\n# Reinstall development version\njust install-dev\n\n# Verify\nprovisioning --version\n```\n\n---\n\n## Success Criteria\n\n### Repository Structure\n\n- ✅ Single `workspace/` directory for all runtime data\n- ✅ Clear separation: source (`provisioning/`), runtime (`workspace/`), artifacts (`distribution/`)\n- ✅ All build artifacts in `distribution/` and gitignored\n- ✅ Clean root directory (no `wrks/`, `NO/`, etc.)\n- ✅ Unified documentation in `docs/`\n\n### Build System\n\n- ✅ Single command builds all packages: `just build`\n- ✅ Packages can be built independently\n- ✅ Checksums generated automatically\n- ✅ Validation before packaging\n- ✅ Build time < 5 minutes for full build\n\n### Installation\n\n- ✅ One-line installation: `curl -fsSL https://get.provisioning.io | sh`\n- ✅ Works on Linux and macOS\n- ✅ Standard installation paths (`/usr/local/`)\n- ✅ User configuration in `~/.provisioning/`\n- ✅ Clean uninstallation\n\n### Distribution\n\n- ✅ Packages available at stable URL\n- ✅ Automated releases via CI/CD\n- ✅ Package registry for extensions\n- ✅ Upgrade mechanism works reliably\n\n### Documentation\n\n- ✅ Complete installation guide\n- ✅ Quick start guide\n- ✅ Developer contributing guide\n- ✅ API documentation\n- ✅ Architecture documentation\n\n---\n\n## Risks and Mitigations\n\n### Risk 1: Breaking Changes for Existing Users\n\n**Impact:** High\n**Probability:** High\n**Mitigation:**\n\n- Provide migration script\n- Support both old and new paths during transition (v3.2.x)\n- Clear migration guide\n- Automated backup before migration\n\n### Risk 2: Build System Complexity\n\n**Impact:** Medium\n**Probability:** Medium\n**Mitigation:**\n\n- Start with simple packaging\n- Iterate and improve\n- Document thoroughly\n- Provide examples\n\n### Risk 3: Installation Path Conflicts\n\n**Impact:** Medium\n**Probability:** Low\n**Mitigation:**\n\n- Check for existing installations\n- Support custom prefix\n- Clear uninstallation\n- Non-conflicting binary names\n\n### Risk 4: Cross-Platform Issues\n\n**Impact:** High\n**Probability:** Medium\n**Mitigation:**\n\n- Test on multiple OSes (Linux, macOS)\n- Use portable commands\n- Provide fallbacks\n- Clear error messages\n\n### Risk 5: Dependency Management\n\n**Impact:** Medium\n**Probability:** Medium\n**Mitigation:**\n\n- Document all dependencies\n- Check prerequisites during installation\n- Provide installation instructions for dependencies\n- Consider bundling critical dependencies\n\n---\n\n## Timeline Summary\n\n| Phase | Duration | Key Deliverables |\n| ------- | ---------- | ------------------ |\n| Phase 1: Restructuring | 3-4 days | Clean directory structure, updated paths |\n| Phase 2: Build System | 3-4 days | Working build system, all package types |\n| Phase 3: Installation | 2-3 days | Installers, pure Nushell CLI |\n| Phase 4: Registry (Optional) | 2-3 days | Package registry, extension management |\n| Phase 5: Documentation | 2 days | Complete documentation, release |\n| **Total** | **12-16 days** | Production-ready distribution system |\n\n---\n\n## Next Steps\n\n1. **Review and Approval** (Day 0)\n   - Review this analysis\n   - Approve implementation plan\n   - Assign resources\n\n2. **Kickoff** (Day 1)\n   - Create implementation branch\n   - Set up project tracking\n   - Begin Phase 1\n\n3. **Weekly Reviews**\n   - End of Phase 1: Structure review\n   - End of Phase 2: Build system review\n   - End of Phase 3: Installation review\n   - Final review before release\n\n---\n\n## Conclusion\n\nThis comprehensive plan transforms the provisioning system into a professional-grade infrastructure automation platform with:\n\n- **Clean Architecture**: Clear separation of concerns\n- **Professional Distribution**: Standard installation paths and packaging\n- **Easy Installation**: One-command installation for users\n- **Developer Friendly**: Simple build system and clear development workflow\n- **Extensible**: Package registry for community extensions\n- **Well Documented**: Complete guides for users and developers\n\nThe implementation will take approximately **2-3 weeks** and will result in a production-ready system suitable for both individual developers and\nenterprise deployments.\n\n---\n\n## References\n\n- Current codebase structure\n- Unix FHS (Filesystem Hierarchy Standard)\n- Rust cargo packaging conventions\n- npm/yarn package management patterns\n- Homebrew formula best practices\n- KCL package management design
