Files
Workstation-Setup/PHASE-7-EXECUTION-MODES.md
2026-09-28 17:39:45 -07:00

16 KiB

PHASE 7: EXECUTION MODES & CHECKPOINT RECOVERY

10 Operational Modes, State Persistence, and Restart-Safe Execution

Phase Start Date: 2026-09-09
Scope: Design checkpoint-based execution with resume-after-restart capability
Outcomes: Robust execution framework with 10 modes and full recovery support


7.1 EXECUTION MODES OVERVIEW

Mode Matrix

Mode Purpose Output Can Resume Modifies System
1. Audit Scan current state Report only N/A No
2. Plan Show what will change Diff report N/A No
3. Apply Install everything Status log Yes Yes
4. Repair Fix failed installs Status log Yes Yes
5. HealthCheck Verify completion Pass/fail report N/A No
6. Backup Save current state Backup archive N/A No
7. Restore Rollback to backup Restore log N/A Yes
8. Inventory List installed apps CSV/JSON N/A No
9. UpdatePortable Update portable apps Status log Yes Yes
10. CreateWorkspace Initialize project Project path N/A No

7.2 CHECKPOINT-BASED EXECUTION

Checkpoint System Architecture

Purpose: Allow script to resume after forced restart (WinGet may require reboot)

State File Location: $ProfileRoot\.workstation-setup-state.json

Checkpoint Structure

{
  "ExecutionId": "2026-09-09-142830-ABC123",
  "Profile": "DailyTech-Tuning",
  "Mode": "Apply",
  "StartTime": "2026-09-09T14:28:30Z",
  "LastCheckpoint": "2026-09-09T15:45:00Z",
  "LastCheckpointPhase": "InstallPortableApps",
  "Status": "InProgress_AwaitingRestart",
  "PendingRestart": {
    "Detected": true,
    "Reason": "WinGet installed PowerShell 7",
    "UserPrompted": true,
    "RestartAt": null,
    "AllowUserDelay": true
  },
  "CompletedPhases": [
    {
      "Phase": "ValidateConfiguration",
      "Status": "Completed",
      "Timestamp": "2026-09-09T14:28:45Z",
      "Duration": "15s",
      "ItemsProcessed": 0
    },
    {
      "Phase": "CreateFolderStructure",
      "Status": "Completed",
      "Timestamp": "2026-09-09T14:29:15Z",
      "Duration": "30s",
      "ItemsProcessed": 78
    },
    {
      "Phase": "InstallWinGetPackages",
      "Status": "Completed",
      "Timestamp": "2026-09-09T15:15:00Z",
      "Duration": "45m 45s",
      "ItemsProcessed": 16,
      "PackagesInstalled": [
        { "Name": "Git", "Status": "Success", "Version": "2.42.0" },
        { "Name": "Python 3.13", "Status": "Success", "Version": "3.13.0" }
      ]
    },
    {
      "Phase": "InstallPortableApps",
      "Status": "InProgress",
      "Timestamp": "2026-09-09T15:45:00Z",
      "Duration": "30s (elapsed)",
      "ItemsProcessed": 3,
      "ItemsRemaining": 18,
      "AppsInstalled": [
        { "Name": "HxD", "Status": "Success", "Location": "P:\\Tools\\HxD" },
        { "Name": "Sysinternals", "Status": "Success", "Location": "P:\\Tools\\Sysinternals" },
        { "Name": "PuTTY", "Status": "Success", "Location": "P:\\Tools\\PuTTY" }
      ]
    }
  ],
  "FailedPhases": [],
  "Warnings": [
    {
      "Phase": "InstallWinGetPackages",
      "Item": "VirtualBox",
      "Message": "Already installed via previous run",
      "Severity": "Info"
    }
  ],
  "NextActions": [
    "Complete InstallPortableApps phase (18 apps remaining)",
    "Proceed to SetWindowsConfiguration phase",
    "Complete VS Code Extensions installation",
    "Run HealthCheck to verify all installs"
  ],
  "ResumeInstructions": {
    "AutoResume": true,
    "AutoResumeDelay": 300,
    "ManualResumeCommand": "Automotive-Workstation-Setup.ps1 -Mode Apply -Profile DailyTech-Tuning -ResumeFromCheckpoint -ExecutionId 2026-09-09-142830-ABC123"
  }
}

Checkpoint Lifecycle

  1. Create at Start: Initialize with execution ID, profile, mode
  2. Update per Phase: Record progress as each phase completes
  3. Detect Restart: Monitor for pending restart
  4. Persist Before Restart: Save state to disk
  5. Resume After Restart: Load state and skip completed phases
  6. Mark Complete: Set status to "Completed" or "CompletedWithWarnings"

7.3 INDIVIDUAL EXECUTION MODES

Mode 1: Audit

Purpose: Scan current workstation state without making changes

Process:

Audit Mode
├── Verify Administrator privileges
├── Load configuration per profile
├── Scan folder structure (compare to expected)
├── Enumerate installed WinGet packages
├── List portable apps in installation paths
├── Check Windows settings (power plans, services, etc.)
├── List VS Code extensions
├── Check OEM tools installation status
└── Generate audit report (JSON/CSV/HTML)

Output: workstation-audit-{profile}-{date}.json

Example Output:

{
  "Profile": "DailyTech-Tuning",
  "AuditDate": "2026-09-09T16:00:00Z",
  "SystemInfo": {
    "OSVersion": "Windows 11 22H2",
    "Processor": "Intel Core i9-12900K",
    "RAM": 64,
    "DiskC": { "Total": 1099511627776, "Free": 549755813888 }
  },
  "FolderStructure": {
    "Total": 78,
    "Found": 75,
    "Missing": ["S:\\Backup", "S:\\Archive"],
    "Extra": ["C:\\Temp\\OldProject"]
  },
  "WinGetPackages": {
    "Expected": 16,
    "Installed": 14,
    "Missing": ["GNU Make", "CMake"],
    "Outdated": { "Git": "2.40.0 (expected 2.42.0)" }
  },
  "PortableApps": {
    "Expected": 21,
    "Found": 19,
    "Missing": ["SavvyCAN", "Binwalk"]
  },
  "WindowsSettings": {
    "Hibernation": "FAIL",
    "USBSelectiveSuspend": "PASS",
    "PowerPlan": "PASS"
  }
}

Mode 2: Plan

Purpose: Show what would change if Apply mode runs

Process:

Plan Mode
├── Load current state (via Audit)
├── Load desired state (from config)
├── Compare and diff
├── Highlight additions
├── Highlight removals
├── Highlight updates
├── Highlight Windows setting changes
├── Estimate time + disk space
└── Generate plan report (text/JSON)

Output: workstation-plan-{profile}-{date}.txt

Example Output:

WORKSTATION SETUP PLAN
Profile: DailyTech-Tuning
Estimated Time: 2 hours 30 minutes
Estimated Disk Space: 45 GB

FOLDER STRUCTURE
  Missing 3 folders - Will create:
    [+] S:\Backup
    [+] S:\Archive
    [+] C:\Projects\Analysis

WINGET PACKAGES
  Install 2 missing packages:
    [+] GNU Make (Scoop fallback or manual)
    [+] CMake (Scoop fallback or manual)
  
  Update 1 outdated package:
    [~] Git (2.40.0 → 2.42.0)
  
  Already Installed (no change):
    [✓] Python 3.13, Visual Studio Code, PowerShell 7, ...

PORTABLE APPLICATIONS
  Download + Extract 2 missing apps:
    [+] SavvyCAN (GitHub, 45 MB)
    [+] Binwalk (pip or GitHub, 30 MB)
  
  Already Installed (no change):
    [✓] HxD, Sysinternals, PuTTY, ...

WINDOWS SETTINGS
  [~] Hibernation: Enabled → Disabled (safe to change)
  [~] USB Selective Suspend: Enabled → Disabled
  [~] Power Plan: Balanced → High Performance
  [+] File Extensions: Show (currently hidden)
  
  Will need restart after applying changes

NO ROLLBACK NEEDED - All changes are reversible

Mode 3: Apply

Purpose: Install all applications, configure Windows, create folder structure

Process:

Apply Mode (with checkpoint resume)
├── Load checkpoint (if resuming)
├── Validate permissions + free space
├── CreateCheckpoint(StartExecution)
│
├── Phase 1: Validate Configuration
│   └── Verify JSON schemas, resolve paths
│
├── Phase 2: Create Folder Structure
│   ├── CreateCheckpoint(FolderStructureCreated)
│   └── Create 78 folders per profile
│
├── Phase 3: Install WinGet Packages
│   ├── Loop through each package
│   ├── Detect/Skip if already installed
│   ├── Install + verify
│   ├── Retry failed packages
│   ├── CheckpointAfterEachPackage
│   └── DetectPendingRestart → SaveStateAndPrompt
│
├── Phase 4: Download Portable Apps
│   ├── Loop through each app
│   ├── Verify HTTPS + download
│   ├── Validate integrity (7 layers)
│   ├── Extract + verify
│   ├── Add to PATH if needed
│   ├── CheckpointAfterEach
│   └── DetectPendingRestart
│
├── Phase 5: Set Windows Configuration
│   ├── Detect current state
│   ├── Apply power management settings
│   ├── Apply security settings
│   ├── Apply file system settings
│   ├── Verify each setting applied
│   └── CheckpointAfterPhase
│
├── Phase 6: Install VS Code Extensions
│   ├── Loop through each extension
│   ├── Install via 'code --install-extension'
│   ├── Verify + checkpoint
│   └── Log installation
│
├── Phase 7: Setup Shortcuts
│   ├── Create desktop shortcuts
│   ├── Create Start Menu shortcuts
│   ├── Create quick-launch links
│   └── Checkpoint
│
├── Phase 8: Create Workspace Templates
│   ├── Initialize project folders
│   ├── Create metadata templates
│   └── Checkpoint
│
├── Phase 9: Generate Final Reports
│   ├── Create setup completion report
│   ├── List all installed applications
│   ├── Generate recovery instructions
│   └── Save to logs folder
│
└── CreateCheckpoint(ExecutionComplete)

Restart Handling:

if (Detect-PendingRestart) {
    $saveState = @{
        ExecutionId = $ExecutionId
        CompletedPhases = $completedPhases
        LastCheckpoint = Get-Date
        Status = 'InProgress_AwaitingRestart'
        ResumeCommand = "Automotive-Workstation-Setup.ps1 -Mode Apply -Profile $Profile -ResumeFromCheckpoint"
    }
    $saveState | ConvertTo-Json | Set-Content -Path $StateFile
    
    # Ask user
    $response = Read-Host "Restart required. Restart now (Y/N/Minutes)?"
    if ($response -eq 'Y') {
        Restart-Computer
    } elseif ($response -match '^\d+$') {
        Start-Sleep -Seconds ($response * 60)
        Restart-Computer
    } else {
        Write-Host "Restart manually when ready. Script will resume automatically."
    }
}

Mode 4: Repair

Purpose: Fix failed installations from Apply mode

Process:

Repair Mode
├── Load last checkpoint
├── Identify failed phases/items
├── Prompt user: repair all or select items?
├── Retry each failed item
│   ├── Re-download if needed
│   ├── Re-install + verify
│   └── Update checkpoint
├── If still failing: skip with logged reason
└── Run HealthCheck on repaired items

Mode 5: HealthCheck

Purpose: Verify all installations and settings are correct

Output: Pass/fail report, actionable recommendations

Test-HealthCheck -Profile $Profile
# Returns:
# - All apps installed: [Pass/Fail]
# - Windows settings correct: [Pass/Fail]
# - Folder structure complete: [Pass/Fail]
# - Disk space OK: [Pass/Fail]
# - No corrupted files: [Pass/Fail]

Mode 6: Backup

Purpose: Save current workstation state for rollback

Output: workstation-backup-{profile}-{date}.zip (~10-20 GB for full backup)

Backs up:

  • Configuration files (JSON, registry exports)
  • Installed app list + versions
  • Windows settings (power, services, firewall rules)
  • Custom files (scripts, shortcuts)
  • NOT: Full app binaries (too large), project data

Mode 7: Restore

Purpose: Rollback to previous state

Process:

Restore Mode
├── List available backups
├── Prompt user to select
├── Restore configuration files
├── Restore Windows settings
├── Uninstall apps not in backup
├── Reinstall apps that were in backup
├── Verify restoration
└── Prompt for restart if needed

Mode 8: Inventory

Purpose: Export current installation inventory

Output: CSV or JSON with all installed apps, versions, locations


Mode 9: UpdatePortable

Purpose: Update portable applications to latest versions

Process:

UpdatePortable Mode
├── Check GitHub releases for updates
├── Compare versions
├── Backup current versions
├── Download new versions (validate integrity)
├── Extract over existing
├── Verify executable exists
├── Test basic functionality
├── Checkpoint after each update

Mode 10: CreateWorkspace

Purpose: Initialize new project folder structure

Process:

CreateWorkspace Mode
├── Load workspace templates for profile
├── Prompt for project details (VIN, module, etc.)
├── Create folder structure
├── Generate ProjectMetadata.json
├── Create job log template
├── Initialize checksum tracker
└── Output project path

7.4 PENDING RESTART DETECTION

Check Methods

function Detect-PendingRestart {
    [OutputType([bool])]
    
    # Method 1: Component-Based Servicing
    $cbs = Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Component Based Servicing\RebootPending"
    
    # Method 2: Windows Update
    $wu = Test-Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\WindowsUpdate\Auto Update\RebootRequired"
    
    # Method 3: System Properties
    $sp = $null -ne (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue)
    
    # Method 4: PendingFileRenameOperations
    $pfro = $null -ne (Get-ItemProperty "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager" -Name PendingFileRenameOperations -ErrorAction SilentlyContinue)
    
    return ($cbs -or $wu -or $sp -or $pfro)
}

7.5 STATE PERSISTENCE & RECOVERY

Checkpoint File Operations

function Save-ExecutionCheckpoint {
    param(
        [string]$Phase,
        [string]$Status,
        [object[]]$CompletedItems = @()
    )
    
    $checkpoint = @{
        ExecutionId = $script:ExecutionId
        Profile = $script:Profile
        Mode = $script:Mode
        LastCheckpoint = Get-Date -Format 'O'
        LastCheckpointPhase = $Phase
        Status = $Status
        CompletedPhases += @{
            Phase = $Phase
            Status = $Status
            Timestamp = Get-Date -Format 'O'
            ItemsProcessed = $CompletedItems.Count
            Items = $CompletedItems
        }
    }
    
    $checkpoint | ConvertTo-Json | Set-Content -LiteralPath $StateFile
    Write-Host "✓ Checkpoint saved: $Phase ($Status)"
}

function Resume-FromCheckpoint {
    param(
        [guid]$ExecutionId
    )
    
    $checkpoint = Get-Content $StateFile | ConvertFrom-Json
    
    if ($checkpoint.ExecutionId -ne $ExecutionId) {
        throw "Checkpoint ExecutionId mismatch"
    }
    
    # Skip already-completed phases
    $completedPhases = @($checkpoint.CompletedPhases | Select-Object -ExpandProperty Phase)
    $skipped = 0
    
    foreach ($phase in @('ValidateConfiguration', 'CreateFolders', 'InstallWinGet', ...)) {
        if ($phase -in $completedPhases) {
            Write-Host "⊗ Skipping completed phase: $phase"
            $skipped++
        } else {
            Write-Host "▶ Resuming from phase: $phase"
            & "Invoke-$phase"
        }
    }
    
    Write-Host "Resumed from checkpoint: skipped $skipped completed phases"
}

7.6 EXECUTION MODE INVOCATION

Command Examples

# Audit current state
Automotive-Workstation-Setup.ps1 -Mode Audit -Profile DailyTech-Tuning

# Plan changes
Automotive-Workstation-Setup.ps1 -Mode Plan -Profile ODIS-XENTRY

# Apply with automatic restart
Automotive-Workstation-Setup.ps1 -Mode Apply -Profile DailyTech-Tuning -AllowAutomaticRestart

# Apply with manual restart timing
Automotive-Workstation-Setup.ps1 -Mode Apply -Profile PIWIS-ISTA -PromptForRestart

# Resume after restart
Automotive-Workstation-Setup.ps1 -Mode Apply -Profile DailyTech-Tuning -ResumeFromCheckpoint

# Repair failed installs
Automotive-Workstation-Setup.ps1 -Mode Repair -Profile DailyTech-Tuning -ExecutionId "2026-09-09-142830-ABC123"

# HealthCheck
Automotive-Workstation-Setup.ps1 -Mode HealthCheck -Profile DailyTech-Tuning

# Backup before major change
Automotive-Workstation-Setup.ps1 -Mode Backup -Profile DailyTech-Tuning -BackupName "BeforeMajorUpdate"

# Create workspace
Automotive-Workstation-Setup.ps1 -Mode CreateWorkspace -Profile DailyTech-Tuning -JobId "VW001"

NEXT STEPS

Phase 8 will create Pester Unit Tests to validate the execution modes and checkpoint system.