PowerShell & Claude Code

The Agentic Heartbeat System

Architecting Self-Healing, Autonomous Systems mit Claude Code, PowerShell, MCP Integration und Heartbeat-Loops für Enterprise-Grade Automation

ULTIMATE EDITION
🔧 Production Code
⚡ Agentic Loops
❤️ Heartbeat Monitoring
📑 Struktur des Guides
1 PowerShell Fundamentals für KI-Agenten
2 Claude Code Architecture & Integration
3 Agentic Loop Design Pattern
4 Heartbeat Monitoring & Health Checks
5 MCP Server Integration
6 Production Workflows & Case Studies
7 Security & Execution Policies
8 Performance Tuning & Debugging

PowerShell Fundamentals für KI-Agenten

PowerShell ist nicht einfach nur eine Shell—es ist ein System-API für autonome Systeme. Während CMD.exe Text in Strings umwandelt und KI-Systeme diese mühsam parsen müssen, operiert PowerShell auf echten .NET-Objekten. Das ist der fundamentale Unterschied zwischen veralteter Automation und modernem Agentic Computing.

1.1 Die Objektorientiertheit als Grundpfeiler

Wenn du einen PowerShell-Befehl ausführst, gibt er nicht blindlings Text aus. Er gibt eine Sequenz von strukturierten Objektinstanzen zurück. Jedes Objekt hat Properties, Methoden und Metadaten—ideal für KI-Parsing.

BEISPIEL: Process-Objekte sind nicht nur Text# CMD (antiquiert): Gibt nur Text aus
C:\> tasklist
svchost.exe     1024  12345 KB
explorer.exe    5678  45678 KB

# PowerShell (modern): Gibt Objekt-Instanzen aus
PS> Get-Process | Select-Object Name, Id, WorkingSetMB
Name        Id   WorkingSetMB
----        --   ----
svchost     1024 12
explorer    5678 45

# KI KANN DIREKT BERECHNEN:
PS> Get-Process | Where-Object {$_.WorkingSetMB -gt 100} | Measure-Object -Property WorkingSetMB -Sum
Count : 5
Sum   : 850
Average: 170

Siehst du den Unterschied? CMD braucht Regex und String-Parsing. PowerShell gibt der KI direkt zu: Get-Process | ConvertTo-Json | ai-analyze

1.2 Pipeline-Architektur & Komposition

Die PowerShell-Pipeline ist der Schlüssel zu skalierbarer Automation. Sie erlaubt es KI-Agenten, komplexe Operationen durch einfache Verkettung aufzubauen:

PRODUCTION: Skalierbare Pipeline für System-Audits# Ein KI-Agent führt diese Kette aus und erhält strukturiertes Output
Get-ChildItem -Path "C:\Projects" -Recurse -Include "*.json" |
    Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-30) } |
    ForEach-Object {
        [PSCustomObject]@{
            Path = $_.FullName
            Size = $_.Length / 1MB
            LastModified = $_.LastWriteTime
            IsOld = $true
        }
    } |
    ConvertTo-Json -Depth 3

Die KI erhält vom ersten bis zum letzten Schritt strukturierte Objekte. Das ist nicht wie in Bash, wo du überall Delimiter, AWK und SED brauchst.

1.3 JSON als Lingua Franca zwischen Claude & PowerShell

PowerShell hat native ConvertTo-Json und ConvertFrom-Json Cmdlets. Das bedeutet: Claude kann .NET-Objekte als saubere JSON-Strukturen anfragen, verarbeiten und zurückschreiben.

Operation PowerShell Vorteil für KI
Serialisierung $obj | ConvertTo-Json -Depth 10 Direkte JSON-Übergabe an Claude API
Deserialisierung $json | ConvertFrom-Json Claude erzeugt JSON, PowerShell baut Objekte
Filterung Where-Object { $_.Property -eq $value } Typsichere Filterung, nicht Regex
Transformation ForEach-Object { [PSCustomObject]@{...} } KI-generiert neue Strukturen leicht
Deep Architectural Insight

Jeder PowerShell-Output kann als JSON serialisiert werden. Das bedeutet, dass Claude nicht "text parsing" machen muss—es arbeitet mit expliziten Datenstrukturen. Das ist der Grund, warum moderne KI-Agenten PowerShell bevorzugen.

1.4 Fehlerbehandlung & Exit Codes

KI-Agenten MÜSSEN mit Fehlern rechnen. PowerShell hat mehrere Fehlerkanäle:

KRITISCH: Error Handling für KI-Robustheit$ErrorActionPreference = "Stop"  # Stoppt bei JEDEM Fehler

try {
    $result = Get-ChildItem -Path "C:\NonExistentPath" -ErrorAction Stop
    $result | ConvertTo-Json | Write-Host
} catch {
    # Strukturierter Fehler für Claude
    [PSCustomObject]@{
        Error = $_.Exception.Message
        LineNumber = $_.InvocationInfo.ScriptLineNumber
        Command = $_.InvocationInfo.MyCommand.Name
        Timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
    } | ConvertTo-Json | Write-Error
    exit 1
}

exit 0
Kritischer Fehler: Unbehendelte Exceptions

Wenn PowerShell-Skripte stumm fehlschlagen (ohne Exit-Code), denkt Claude, alles ist okay. IMMER $ErrorActionPreference = "Stop" setzen und strukturierte JSON-Fehler zurückgeben.

Claude Code Architecture & Integration

Claude Code ist ein KI-gesteuerter Coding-Agent, der direkt auf deinem Betriebssystem läuft und PowerShell-Befehle ausführt. Die Integration funktioniert über eine einfache API: Claude generiert PowerShell-Befehle, erhält strukturierte Ausgaben, analysiert die Ergebnisse und beschließt die nächste Aktion.

2.1 Claude Code Workflow Architektur

Claude empfängt Aufgabe
Analysiert Anforderung
Plant PowerShell-Befehl
Generiert Skript
PowerShell führt aus
JSON-Output
Claude parst Ergebnis
Bewertet Erfolg
Nächste Iteration

2.2 System Prompt für Claude Code (Best Practice)

Claude Code System Prompt
"Du bist ein Expert Windows Automation Engineer mit 20+ Jahren Erfahrung in PowerShell Core (pwsh) und .NET Automation. Deine Aufgabe ist es, komplexe Systemadministrations- und DevOps-Aufgaben AUTONOM auszuführen. STRIKTE ANFORDERUNGEN: 1. ALLE Outputs müssen JSON sein (ConvertTo-Json -Depth 10) 2. IMMER $ErrorActionPreference = 'Stop' setzen 3. Nutze Try-Catch für ALLE kritischen Operationen 4. Exit-Code 0 = Erfolg, alles andere = Fehler 5. Strukturierter Error-Output mit Stacktrace 6. Keine interaktiven Prompts 7. Vollständige Pfade verwenden, keine relativen Pfade 8. Timeouts für lange-laufende Prozesse Vor JEDEM kritischen Befehl: - Validiere die Eingabe - Prüfe Voraussetzungen - Erstelle Rollback-Plan falls nötig Nach JEDEM Befehl: - Gib strukturierten JSON zurück - Enthalte Erfolgs-/Fehler-Status - Dokumentiere alle Änderungen"

2.3 Production-Ready Claude Code Integration Pattern

PATTERN: Claude Code mit vollständiger Fehlerbehandlung#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# CLAUDE CODE EXECUTION WRAPPER
# Maximale Robustheit für Agentic Loops
# ════════════════════════════════════════════════════════════════

param(
    [Parameter(Mandatory = $true)]
    [string]$TaskDescription,
    
    [Parameter(Mandatory = $false)]
    [hashtable]$Context = @{}
)

$ErrorActionPreference = "Stop"
$ProgressPreference = "SilentlyContinue"

# ════════════════════════════════════════════════════════════════
# INITIALIZATION
# ════════════════════════════════════════════════════════════════

$ExecutionStartTime = Get-Date
$ScriptResult = @{
    Status = "INITIALIZING"
    TaskDescription = $TaskDescription
    Context = $Context
    ExecutionLog = @()
    Errors = @()
    Output = $null
    ExecutionTime = $null
    Timestamp = $ExecutionStartTime.ToString("yyyy-MM-dd HH:mm:ss")
}

function Log-Execution {
    param([string]$Message, [string]$Level = "INFO")
    $LogEntry = [PSCustomObject]@{
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
        Level = $Level
        Message = $Message
    }
    $ScriptResult.ExecutionLog += $LogEntry
    Write-Host "[$Level] $Message"
}

function Invoke-TaskWithTimeout {
    param(
        [scriptblock]$ScriptBlock,
        [int]$TimeoutSeconds = 300
    )
    
    $job = Start-Job -ScriptBlock $ScriptBlock
    $result = Wait-Job -Job $job -Timeout $TimeoutSeconds
    
    if ($null -eq $result) {
        Stop-Job -Job $job
        throw "Timeout after $TimeoutSeconds seconds"
    }
    
    $output = Receive-Job -Job $job
    Remove-Job -Job $job
    return $output
}

# ════════════════════════════════════════════════════════════════
# MAIN EXECUTION
# ════════════════════════════════════════════════════════════════

try {
    Log-Execution "Task started: $TaskDescription" "INFO"
    
    # Validate Environment
    if (-not (Get-Command pwsh -ErrorAction SilentlyContinue)) {
        throw "PowerShell Core (pwsh) nicht verfügbar"
    }
    
    Log-Execution "Umgebung validiert" "INFO"
    
    # Execute Main Task (Example: System Health Check)
    $mainTask = {
        $ErrorActionPreference = "Stop"
        
        $systemHealth = [PSCustomObject]@{
            ComputerName = $env:COMPUTERNAME
            OSVersion = [System.Environment]::OSVersion.ToString()
            AvailableMemoryMB = [System.GC]::GetTotalMemory($false) / 1MB
            ProcessCount = @(Get-Process).Count
            Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        }
        
        return $systemHealth
    }
    
    $ScriptResult.Output = Invoke-TaskWithTimeout -ScriptBlock $mainTask -TimeoutSeconds 60
    Log-Execution "Hauptaufgabe abgeschlossen" "INFO"
    
    $ScriptResult.Status = "SUCCESS"
    
} catch {
    $ScriptResult.Status = "FAILED"
    $ScriptResult.Errors += [PSCustomObject]@{
        Message = $_.Exception.Message
        LineNumber = $_.InvocationInfo.ScriptLineNumber
        Command = $_.InvocationInfo.MyCommand.Name
        StackTrace = $_.ScriptStackTrace
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    }
    Log-Execution "Error: $($_.Exception.Message)" "ERROR"
}

# ════════════════════════════════════════════════════════════════
# FINALIZE & OUTPUT
# ════════════════════════════════════════════════════════════════

$ScriptResult.ExecutionTime = ((Get-Date) - $ExecutionStartTime).TotalSeconds

# JSON Output for Claude
$ScriptResult | ConvertTo-Json -Depth 10 | Write-Host

# Exit Code für Claude
if ($ScriptResult.Status -eq "SUCCESS") {
    exit 0
} else {
    exit 1
}
Best Practice: Structured Return Values

Dieser Wrapper gibt Claude ALLES, was es braucht: Erfolgs-Status, Timestamps, Execution Logs, Fehlerdetails und das eigentliche Output. Claude kann damit sofort die nächste Aktion planen.

2.4 Claude Code MCP Integration

Claude Code kann über MCP (Model Context Protocol) direkt mit externen Tools kommunizieren. Für PowerShell bedeutet das: Claude kann nicht nur Befehle ausführen, sondern auch mit APIs, Datenbanken und anderen Services kommunizieren.

PATTERN: Claude Code mit MCP Server Calls# Claude kann via MCP PowerShell-Befehle UND externe APIs aufrufen

# Beispiel: Claude orchestriert PowerShell + Gmail MCP
$task = @{
    Task = "System-Error-Report per Email versenden"
    Steps = @(
        "PowerShell: Get-SystemErrors (letzten 1 Stunde)",
        "MCP Gmail: systemerrors@company.de versenden",
        "PowerShell: Log update in Database",
        "Return Status"
    )
}

# Claude führt aus:
# 1. PowerShell-Befehl für lokale System-Daten
$errors = Get-EventLog -LogName System -After (Get-Date).AddHours(-1) |
    Where-Object { $_.EntryType -eq "Error" } |
    ConvertTo-Json

# 2. MCP Gmail zur Kommunikation
# (Claude nutzt MCP-Server um Email zu versenden)

# 3. PowerShell-Befehl für lokale Logs
# Update-SystemAuditLog -Entries $errors

# 4. Strukturiertes Return für nächste Loop
[PSCustomObject]@{
    ErrorsCollected = @($errors).Count
    EmailSent = $true
    LogsUpdated = $true
    NextCheck = (Get-Date).AddHours(1)
} | ConvertTo-Json

Agentic Loop Design Pattern

Das Herz aller autonomen Systeme ist die Agentic Loop—ein kontinuierliches Zyklus von Wahrnehmung, Entscheidung und Aktion. Claude + PowerShell müssen zusammen einen stabilen, fehlerresistenten Loop bilden.

3.1 Die Klassische Agentic Loop Architektur

Der 5-Phasen Loop

1️⃣ OBSERVE
2️⃣ ANALYZE
3️⃣ DECIDE


5️⃣ HANDLE ERROR
4️⃣ EXECUTE

3.2 Production Agentic Loop Implementierung

PRODUCTION: Vollständige Agentic Loop mit Heartbeat#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# AUTONOMOUS AGENTIC LOOP FOR SYSTEM MANAGEMENT
# Claude + PowerShell Synergy mit Heartbeat & State Management
# ════════════════════════════════════════════════════════════════

param(
    [Parameter(Mandatory = $true)]
    [string]$SystemName,
    
    [Parameter(Mandatory = $false)]
    [int]$LoopIntervalSeconds = 60
)

$ErrorActionPreference = "Stop"

# ════════════════════════════════════════════════════════════════
# GLOBAL STATE
# ════════════════════════════════════════════════════════════════

$AgentState = @{
    SystemName = $SystemName
    Status = "INITIALIZING"
    LoopCount = 0
    LastHeartbeat = $null
    HealthCheck = $null
    Decisions = @()
    ExecutionLog = @()
    Errors = @()
    Timestamp = Get-Date
}

$HeartbeatConfig = @{
    CheckInterval = 30  # Sekunden
    HealthThreshold = @{
        CPUUsage = 85
        MemoryUsage = 90
        DiskUsage = 85
    }
    MaxRetries = 3
    RetryDelay = 5
}

# ════════════════════════════════════════════════════════════════
# PHASE 1: OBSERVE (Datensammlung)
# ════════════════════════════════════════════════════════════════

function Invoke-ObservationPhase {
    Write-Host "[OBSERVE] Sammle System-Status..."
    
    try {
        $observation = [PSCustomObject]@{
            Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
            System = [PSCustomObject]@{
                ComputerName = $env:COMPUTERNAME
                OSVersion = [System.Environment]::OSVersion.VersionString
                Architecture = [System.Environment]::Is64BitOperatingSystem ? "64-bit" : "32-bit"
            }
            Performance = [PSCustomObject]@{
                CPUUsagePercent = (Get-Counter '\Processor(_Total)\% Processor Time' -SampleInterval 1 -MaxSamples 1 | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue)
                MemoryUsageMB = ([System.GC]::GetTotalMemory($false) / 1MB)
                AvailableMemoryMB = (Get-Counter '\Memory\Available MBytes' -SampleInterval 1 -MaxSamples 1 | Select-Object -ExpandProperty CounterSamples | Select-Object -ExpandProperty CookedValue)
            }
            Processes = [PSCustomObject]@{
                TotalCount = (Get-Process | Measure-Object).Count
                TopMemory = (Get-Process | Sort-Object WorkingSetMB -Descending | Select-Object -First 3 | ConvertTo-Json)
            }
            Services = [PSCustomObject]@{
                CriticalServices = @(Get-Service | Where-Object { $_.StartType -eq "Automatic" -and $_.Status -ne "Running" } | ConvertTo-Json)
            }
        }
        
        return $observation
    } catch {
        Write-Error "Observation Phase Failed: $_"
        return $null
    }
}

# ════════════════════════════════════════════════════════════════
# PHASE 2: ANALYZE (Intelligente Bewertung)
# ════════════════════════════════════════════════════════════════

function Invoke-AnalysisPhase {
    param([PSCustomObject]$Observation)
    
    Write-Host "[ANALYZE] Bewerte Systemstatus..."
    
    $analysis = [PSCustomObject]@{
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
        HealthStatus = "UNKNOWN"
        Alerts = @()
        Recommendations = @()
    }
    
    # CPU Analysis
    if ($Observation.Performance.CPUUsagePercent -gt $HeartbeatConfig.HealthThreshold.CPUUsage) {
        $analysis.HealthStatus = "WARNING"
        $analysis.Alerts += "CPU-Auslastung über Threshold: $($Observation.Performance.CPUUsagePercent)%"
        $analysis.Recommendations += "Prüfe Top-Prozesse und stelle Ressourcen frei"
    }
    
    # Memory Analysis
    $MemoryPercent = (($Observation.Performance.MemoryUsageMB / ($Observation.Performance.MemoryUsageMB + $Observation.Performance.AvailableMemoryMB)) * 100)
    if ($MemoryPercent -gt $HeartbeatConfig.HealthThreshold.MemoryUsage) {
        $analysis.HealthStatus = "WARNING"
        $analysis.Alerts += "Memory-Auslastung über Threshold: $MemoryPercent%"
        $analysis.Recommendations += "Führe Speicherfreigabe durch und prüfe Speicherlecks"
    }
    
    # Service Analysis
    if ($Observation.Services.CriticalServices -ne $null) {
        $analysis.HealthStatus = if ($analysis.HealthStatus -eq "UNKNOWN") { "CRITICAL" } else { "CRITICAL" }
        $analysis.Alerts += "Kritische Services nicht laufend"
        $analysis.Recommendations += "Starte kritische Services neu"
    }
    
    return $analysis
}

# ════════════════════════════════════════════════════════════════
# PHASE 3: DECIDE (Entscheidungsfindung basierend auf Analyse)
# ════════════════════════════════════════════════════════════════

function Invoke-DecisionPhase {
    param([PSCustomObject]$Analysis, [PSCustomObject]$Observation)
    
    Write-Host "[DECIDE] Treffe Entscheidungen basierend auf Analyse..."
    
    $decisions = @()
    
    if ($Analysis.HealthStatus -eq "CRITICAL") {
        $decisions += [PSCustomObject]@{
            Action = "RESTART_CRITICAL_SERVICES"
            Priority = "HIGH"
            Reason = "Kritische Services nicht verfügbar"
        }
    }
    
    if ($Analysis.HealthStatus -eq "WARNING") {
        if ($Observation.Performance.CPUUsagePercent -gt 90) {
            $decisions += [PSCustomObject]@{
                Action = "TERMINATE_HIGH_MEMORY_PROCESSES"
                Priority = "MEDIUM"
                Reason = "Extremale Ressourcenauslastung"
            }
        }
    }
    
    if ($Analysis.Alerts.Count -eq 0) {
        $decisions += [PSCustomObject]@{
            Action = "CONTINUE_NORMAL_OPERATION"
            Priority = "LOW"
            Reason = "System ist healthy"
        }
    }
    
    return $decisions
}

# ════════════════════════════════════════════════════════════════
# PHASE 4: EXECUTE (Aktionen durchführen)
# ════════════════════════════════════════════════════════════════

function Invoke-ExecutionPhase {
    param([PSCustomObject[]]$Decisions)
    
    Write-Host "[EXECUTE] Führe Aktionen aus..."
    
    $executionResults = @()
    
    foreach ($decision in $Decisions) {
        $result = [PSCustomObject]@{
            Action = $decision.Action
            Status = "PENDING"
            Result = $null
            Error = $null
            ExecutionTime = 0
        }
        
        try {
            $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
            
            switch ($decision.Action) {
                "RESTART_CRITICAL_SERVICES" {
                    $stoppedServices = Get-Service | Where-Object { $_.StartType -eq "Automatic" -and $_.Status -ne "Running" }
                    foreach ($service in $stoppedServices) {
                        Start-Service -Name $service.Name -ErrorAction SilentlyContinue
                    }
                    $result.Result = "Services restarted"
                    $result.Status = "SUCCESS"
                }
                
                "TERMINATE_HIGH_MEMORY_PROCESSES" {
                    $topProcess = Get-Process | Sort-Object WorkingSetMB -Descending | Select-Object -First 1
                    if ($topProcess.WorkingSetMB -gt 500) {
                        Stop-Process -Id $topProcess.Id -Force -Confirm:$false
                        $result.Result = "Process $($topProcess.Name) terminated"
                        $result.Status = "SUCCESS"
                    }
                }
                
                "CONTINUE_NORMAL_OPERATION" {
                    $result.Result = "System operating normally"
                    $result.Status = "SUCCESS"
                }
            }
            
            $stopwatch.Stop()
            $result.ExecutionTime = $stopwatch.ElapsedMilliseconds
            
        } catch {
            $result.Status = "FAILED"
            $result.Error = $_.Exception.Message
        }
        
        $executionResults += $result
    }
    
    return $executionResults
}

# ════════════════════════════════════════════════════════════════
# PHASE 5: ERROR HANDLING & RECOVERY
# ════════════════════════════════════════════════════════════════

function Invoke-ErrorHandling {
    param([string]$ErrorMessage, [int]$AttemptCount)
    
    Write-Host "[ERROR] Fehler erkannt: $ErrorMessage (Versuch $AttemptCount)"
    
    if ($AttemptCount -lt $HeartbeatConfig.MaxRetries) {
        Write-Host "Warte $($HeartbeatConfig.RetryDelay) Sekunden vor Wiederholung..."
        Start-Sleep -Seconds $HeartbeatConfig.RetryDelay
        return $true  # Retry
    } else {
        Write-Host "Maximale Wiederholungsversuche erreicht. Fallback aktiviert."
        return $false  # Gib auf
    }
}

# ════════════════════════════════════════════════════════════════
# HEARTBEAT LOOP
# ════════════════════════════════════════════════════════════════

function Start-AgentHeartbeat {
    Write-Host "════════════════════════════════════════════════════════════════"
    Write-Host "🫀 Agentic Heartbeat Loop started for [$SystemName]"
    Write-Host "════════════════════════════════════════════════════════════════"
    
    $attemptCount = 0
    
    while ($true) {
        try {
            $AgentState.LoopCount++
            Write-Host "`n[LOOP #$($AgentState.LoopCount)] $(Get-Date -Format 'HH:mm:ss')"
            
            # PHASE 1: OBSERVE
            $observation = Invoke-ObservationPhase
            if ($null -eq $observation) { throw "Observation phase failed" }
            
            # PHASE 2: ANALYZE
            $analysis = Invoke-AnalysisPhase -Observation $observation
            
            # PHASE 3: DECIDE
            $decisions = Invoke-DecisionPhase -Analysis $analysis -Observation $observation
            
            # PHASE 4: EXECUTE
            $results = Invoke-ExecutionPhase -Decisions $decisions
            
            # PHASE 5: HEARTBEAT HEALTH CHECK
            $AgentState.LastHeartbeat = [PSCustomObject]@{
                LoopNumber = $AgentState.LoopCount
                Observation = $observation
                Analysis = $analysis
                Decisions = $decisions
                ExecutionResults = $results
                Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
            }
            
            # Reset attempt counter on success
            $attemptCount = 0
            $AgentState.Status = "RUNNING"
            
            Write-Host "✓ Loop completed successfully. Status: RUNNING"
            
        } catch {
            $attemptCount++
            Write-Host "✗ Error in loop: $_"
            $AgentState.Errors += [PSCustomObject]@{
                Timestamp = Get-Date
                LoopNumber = $AgentState.LoopCount
                Error = $_.Exception.Message
                AttemptCount = $attemptCount
            }
            
            if (-not (Invoke-ErrorHandling -ErrorMessage $_.Exception.Message -AttemptCount $attemptCount)) {
                $AgentState.Status = "CRITICAL_FAILURE"
                Write-Host "⚠️ CRITICAL: Agent heartbeat failed. Exiting."
                break
            }
        }
        
        Start-Sleep -Seconds $LoopIntervalSeconds
    }
    
    # Final Report
    Write-Host "`n════════════════════════════════════════════════════════════════"
    Write-Host "🫀 Agentic Heartbeat Loop ended"
    Write-Host "Total loops: $($AgentState.LoopCount)"
    Write-Host "Errors: $($AgentState.Errors.Count)"
    Write-Host "════════════════════════════════════════════════════════════════"
    
    $AgentState | ConvertTo-Json -Depth 10 | Write-Host
}

# ════════════════════════════════════════════════════════════════
# START THE HEARTBEAT
# ════════════════════════════════════════════════════════════════

Start-AgentHeartbeat
Production-Ready Loop

Dieser Loop hat: ✅ Heartbeat-Monitoring (alle 60 Sekunden) ✅ 5-Phasen-Struktur (OBSERVE → ANALYZE → DECIDE → EXECUTE → ERROR) ✅ Retry-Mechanismen ✅ Strukturierte Fehlerbehandlung ✅ State Management für Tracking ✅ JSON-Output für Claude-Parsing

Heartbeat Monitoring & Health Checks

Das "Heartbeat" ist das kontinuierliche Pulsen des Agentic Systems. Es überwacht nicht nur die Systemgesundheit, sondern auch die Gesundheit des Agenten selbst. Ein guter Heartbeat verrät der KI sofort, wenn etwas falsch läuft.

4.1 Health Check Metrics

Metrik Kritischer Wert Warnung Aktion bei Fehler
Agent Response Time > 30 Sekunden > 10 Sekunden Timeout, Retry, Fallback
CPU Usage > 95% > 85% Throttle, Priorität anpassen
Memory Usage > 95% > 85% GC, Prozesse beenden
Disk Space (System) < 5% < 15% Cleaner starten, Alert versenden
Loop Execution Time > 2x Avg > 1.5x Avg Analyze Bottleneck, Log
Error Rate > 50% Errors > 20% Errors Escalate, Notify Admin

4.2 Health Check Implementation

PRODUCTION: Heartbeat Health Check System#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# HEARTBEAT HEALTH CHECK ENGINE
# Kontinuierliche Überwachung mit Alerting
# ════════════════════════════════════════════════════════════════

$HealthCheckConfig = @{
    Interval = 30  # Sekunden
    Metrics = @{
        ResponseTimeThreshold_Critical = 30000  # ms
        ResponseTimeThreshold_Warning = 10000
        CPUThreshold_Critical = 95
        CPUThreshold_Warning = 85
        MemoryThreshold_Critical = 95
        MemoryThreshold_Warning = 85
        DiskThreshold_Critical = 5
        DiskThreshold_Warning = 15
    }
    AlertChannels = @("Email", "Log", "MCP-Webhook")
}

class HealthMetrics {
    [string]$Timestamp
    [int]$LoopNumber
    [double]$CPUUsagePercent
    [double]$MemoryUsagePercent
    [double]$DiskFreePercent
    [int]$ResponseTimeMs
    [int]$ErrorCountLastLoop
    [double]$ErrorRatePercent
    [hashtable]$Status = @{}
    
    [PSCustomObject] ToJSON() {
        return [PSCustomObject]@{
            Timestamp = $this.Timestamp
            LoopNumber = $this.LoopNumber
            CPU = [PSCustomObject]@{
                UsagePercent = $this.CPUUsagePercent
                Status = $this.Status.CPU
            }
            Memory = [PSCustomObject]@{
                UsagePercent = $this.MemoryUsagePercent
                Status = $this.Status.Memory
            }
            Disk = [PSCustomObject]@{
                FreePercent = $this.DiskFreePercent
                Status = $this.Status.Disk
            }
            ResponseTime = [PSCustomObject]@{
                Milliseconds = $this.ResponseTimeMs
                Status = $this.Status.ResponseTime
            }
            ErrorRate = [PSCustomObject]@{
                Percent = $this.ErrorRatePercent
                Status = $this.Status.ErrorRate
            }
            OverallHealth = $this.GetOverallHealth()
        }
    }
    
    [string] GetOverallHealth() {
        $criticalCount = @($this.Status.Values | Where-Object { $_ -eq "CRITICAL" }).Count
        $warningCount = @($this.Status.Values | Where-Object { $_ -eq "WARNING" }).Count
        
        if ($criticalCount -gt 0) { return "CRITICAL" }
        if ($warningCount -gt 2) { return "WARNING" }
        return "HEALTHY"
    }
}

function Get-SystemMetrics {
    param([int]$LoopNumber)
    
    $metrics = [HealthMetrics]@{
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
        LoopNumber = $LoopNumber
    }
    
    # CPU
    try {
        $cpuCounter = (Get-Counter '\Processor(_Total)\% Processor Time' -SampleInterval 1 -MaxSamples 1).CounterSamples[0].CookedValue
        $metrics.CPUUsagePercent = [Math]::Round($cpuCounter, 2)
    } catch {
        $metrics.CPUUsagePercent = 0
    }
    
    # Memory
    try {
        $totalMemory = (Get-WmiObject Win32_ComputerSystem).TotalPhysicalMemory / 1MB
        $usedMemory = ($totalMemory - ((Get-Counter '\Memory\Available MBytes').CounterSamples[0].CookedValue))
        $metrics.MemoryUsagePercent = [Math]::Round(($usedMemory / $totalMemory) * 100, 2)
    } catch {
        $metrics.MemoryUsagePercent = 0
    }
    
    # Disk
    try {
        $diskInfo = Get-PSDrive -Name C
        $metrics.DiskFreePercent = [Math]::Round(($diskInfo.Free / $diskInfo.Used) * 100, 2)
    } catch {
        $metrics.DiskFreePercent = 0
    }
    
    # Status Evaluation
    $metrics.Status.CPU = if ($metrics.CPUUsagePercent -ge $HealthCheckConfig.Metrics.CPUThreshold_Critical) {
        "CRITICAL"
    } elseif ($metrics.CPUUsagePercent -ge $HealthCheckConfig.Metrics.CPUThreshold_Warning) {
        "WARNING"
    } else {
        "HEALTHY"
    }
    
    $metrics.Status.Memory = if ($metrics.MemoryUsagePercent -ge $HealthCheckConfig.Metrics.MemoryThreshold_Critical) {
        "CRITICAL"
    } elseif ($metrics.MemoryUsagePercent -ge $HealthCheckConfig.Metrics.MemoryThreshold_Warning) {
        "WARNING"
    } else {
        "HEALTHY"
    }
    
    $metrics.Status.Disk = if ($metrics.DiskFreePercent -le $HealthCheckConfig.Metrics.DiskThreshold_Critical) {
        "CRITICAL"
    } elseif ($metrics.DiskFreePercent -le $HealthCheckConfig.Metrics.DiskThreshold_Warning) {
        "WARNING"
    } else {
        "HEALTHY"
    }
    
    return $metrics
}

function Send-HealthAlert {
    param(
        [HealthMetrics]$Metrics,
        [string]$AlertLevel
    )
    
    Write-Host "🚨 [$AlertLevel] Health Alert: $($Metrics.GetOverallHealth())"
    
    # Log Alert
    $alertLog = @{
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
        Level = $AlertLevel
        Metrics = $Metrics.ToJSON()
    }
    
    $alertLog | ConvertTo-Json -Depth 10 | Out-File -FilePath "health_alerts.jsonl" -Append -Encoding UTF8
    
    # Optional: Send via MCP or Email
    # (Integration mit Email/Webhook)
}

# ════════════════════════════════════════════════════════════════
# HEARTBEAT MONITOR (Continuous Background Task)
# ════════════════════════════════════════════════════════════════

$loopNumber = 0
while ($true) {
    $loopNumber++
    $metrics = Get-SystemMetrics -LoopNumber $loopNumber
    
    # Evaluate Health
    $overallHealth = $metrics.GetOverallHealth()
    
    if ($overallHealth -eq "CRITICAL") {
        Send-HealthAlert -Metrics $metrics -AlertLevel "CRITICAL"
    } elseif ($overallHealth -eq "WARNING") {
        Send-HealthAlert -Metrics $metrics -AlertLevel "WARNING"
    }
    
    # JSON Output (für Claude)
    $metrics.ToJSON() | ConvertTo-Json | Write-Host
    
    Start-Sleep -Seconds $HealthCheckConfig.Interval
}

MCP Server Integration & Computer Use Context

MCP (Model Context Protocol) ermöglicht es Claude, über PowerShell hinaus mit externen Services zu kommunizieren. Damit wird der Agent noch mächtiger: Er kann nicht nur lokale Befehle ausführen, sondern auch mit APIs, Datenbanken, Cloud-Services kommunizieren.

5.1 MCP Architektur mit PowerShell

PATTERN: Claude orchestriert PowerShell + MCP Services# MCP Server Konfiguration für Claude Code
# config.json
{
  "mcpServers": {
    "gmail": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-gmail"],
      "disabled": false
    },
    "google_drive": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-google-drive"],
      "disabled": false
    },
    "websearch": {
      "command": "npx",
      "args": ["@modelcontextprotocol/server-websearch"],
      "disabled": false
    }
  }
}

# PowerShell kann nun in Skripten MCP-Integrationen aufrufen
# Claude orchestriert:
# 1. PowerShell: Get-SystemErrors
# 2. MCP Gmail: Versende Fehler-Report per Email
# 3. MCP Google Drive: Speichere Audit-Logs
# 4. PowerShell: Update lokale Datenbank

# Beispiel PowerShell Script
$systemErrors = Get-EventLog -LogName System -After (Get-Date).AddHours(-1) |
    Where-Object { $_.EntryType -eq "Error" } |
    ConvertTo-Json

# Claude kann nun entscheiden:
# "Sende diese Fehler via Gmail (MCP) an systemadmin@company.com"
# "Speichere Report in Google Drive unter /audits/"
# "Update Lokal-DB mit Fehler-Count"

5.2 Computer Use Context for Claude

Claude Code hat "Computer Use"—die Fähigkeit, den Desktop wie ein Mensch zu sehen und zu kontrollieren. Mit PowerShell kombiniert ist das extrem mächtig:

Computer Use Context PowerShell Integration Use Case
Screenshot Capture $screen = screenshot.png | Analyze-UI-State Claude sieht GUI-Fehler und dirigiert PowerShell-Korrektionen
Mouse/Keyboard Control Öffne PowerShell Terminal, führe Befehle aus Claude navigiert GUI und nutzt PowerShell für Automation
OCR Text Reading PowerShell liest OCR-Output und parst Daten Claude liest Fehler von Legacy-Tools und dirigiert Fixes
Real-time Monitoring PowerShell lädt Logs, Claude analysiert via Computer Use Visual Monitoring + Structured Data

5.3 Production MCP Integration Pattern

PRODUCTION: MCP + PowerShell Orchestration#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# MCP INTEGRATION BRIDGE: Claude ↔ PowerShell ↔ External APIs
# ════════════════════════════════════════════════════════════════

$MCPConfig = @{
    EnabledServers = @("gmail", "google_drive", "slack")
    TimeoutSeconds = 60
    RetryAttempts = 3
}

class MCPBridge {
    [string]$ServerName
    [string]$Status = "DISCONNECTED"
    [hashtable]$Context = @{}
    
    [PSCustomObject] InvokeRemote([string]$Function, [hashtable]$Parameters) {
        $request = @{
            ServerName = $this.ServerName
            Function = $Function
            Parameters = $Parameters
            Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
        }
        
        # Claude führt MCP Call aus (z.B. via Anthropic API)
        # Dies ist konzeptionell—Claude würde das über MCP SDK aufrufen
        
        return [PSCustomObject]@{
            Status = "SUCCESS"
            Response = $null
            ExecutionTime = 0
        }
    }
}

# Beispiel: Gmail Integration
$gmailBridge = [MCPBridge]@{
    ServerName = "gmail"
}

# PowerShell sammelt Daten
$systemReport = @{
    Subject = "Daily System Health Report"
    Body = Get-Content "system_report.txt" -Raw
    Recipients = @("admin@company.com", "devops@company.com")
    Date = Get-Date -Format "yyyy-MM-dd"
}

# Claude orchestriert via MCP
$emailResult = $gmailBridge.InvokeRemote(
    "SendEmail",
    @{
        To = $systemReport.Recipients -join ","
        Subject = $systemReport.Subject
        Body = $systemReport.Body
        Attachments = @("system_report.txt", "metrics.csv")
    }
)

if ($emailResult.Status -eq "SUCCESS") {
    Write-Host "✓ Email sent via MCP Gmail"
} else {
    Write-Host "✗ Email sending failed, fallback to local log"
}

Production Workflows & Case Studies aus Genitus

Hier zeige ich echte Use Cases aus Genitus Inc. und deinen Fintech-Projekten, wie PowerShell + Claude Code zusammen arbeiten.

6.1 Use Case 1: Autonomous GOLDSHIELD Newsletter Generation

Szenario: Der GOLDSHIELD Newsletter muss täglich 100+ Fintech-Ticker analysieren, Risiken bewerten und einen Report generieren. Manuell ist das unmöglich.

Lösung: Agentic Loop mit Claude Code + PowerShell:

Claude: Ticker-Liste laden
PowerShell: API-Call (EOD Historical Data)
Claude: Daten analysieren
Claude: Generiere HTML Newsletter
PowerShell: Speichere HTML
MCP Gmail: Versende Newsletter
PRODUCTION: Autonomous Newsletter Generation Loop#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# GOLDSHIELD AUTONOMOUS NEWSLETTER ENGINE
# Daily Fintech Analysis via Claude + PowerShell
# ════════════════════════════════════════════════════════════════

param(
    [Parameter(Mandatory = $false)]
    [string]$TickerFile = "./tickers.json",
    
    [Parameter(Mandatory = $false)]
    [string]$OutputPath = "./newsletters",
    
    [Parameter(Mandatory = $false)]
    [bool]$SendEmail = $true
)

$ErrorActionPreference = "Stop"

# ════════════════════════════════════════════════════════════════
# STEP 1: Load Tickers & API Configuration
# ════════════════════════════════════════════════════════════════

function Load-TickerConfiguration {
    try {
        $config = Get-Content $TickerFile | ConvertFrom-Json
        Write-Host "✓ Loaded $(($config.Tickers | Measure-Object).Count) tickers"
        return $config
    } catch {
        Write-Error "Failed to load ticker configuration: $_"
        exit 1
    }
}

# ════════════════════════════════════════════════════════════════
# STEP 2: Fetch Market Data
# ════════════════════════════════════════════════════════════════

function Get-FinancialData {
    param([string[]]$Tickers)
    
    Write-Host "📊 Fetching financial data for $($Tickers.Count) tickers..."
    
    $apiBaseUrl = "https://theserver-open-ai.replit.app/eod"  # Proxy Server
    
    $marketData = @()
    
    foreach ($ticker in $Tickers) {
        try {
            $response = Invoke-RestMethod -Uri "$apiBaseUrl/$ticker" -Method Get -TimeoutSec 10
            
            $marketData += [PSCustomObject]@{
                Ticker = $ticker
                Price = $response.close
                Change = $response.change
                ChangePercent = $response.change_percent
                Volume = $response.volume
                Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
            }
            
        } catch {
            Write-Warning "Failed to fetch data for $ticker: $_"
        }
    }
    
    return $marketData
}

# ════════════════════════════════════════════════════════════════
# STEP 3: Invoke Claude Analysis
# ════════════════════════════════════════════════════════════════

function Invoke-ClaudeAnalysis {
    param([PSCustomObject[]]$MarketData)
    
    Write-Host "🧠 Invoking Claude AI for analysis..."
    
    # Prepare data for Claude
    $analysisRequest = @{
        data = $MarketData
        instructions = @"
Du bist ein Senior Fintech Analyst. Analysiere diese Market Data und erstelle einen umfassenden Newsletter Report mit:

1. **Market Overview**: Top 5 Gainers und Loser
2. **Risk Assessment**: Volatility Index, unusual volume spikes
3. **Recommendations**: Buy/Hold/Sell Signale basierend auf technischen Indikatoren
4. **Key Insights**: Relevante News und Markttrends

Output: HTML-Template ready zum Versenden
"@
    } | ConvertTo-Json -Depth 10
    
    # Call Claude (via Anthropic API)
    $claudeResponse = Invoke-RestMethod `
        -Uri "https://api.anthropic.com/v1/messages" `
        -Method Post `
        -Headers @{
            "Content-Type" = "application/json"
            "x-api-key" = $env:ANTHROPIC_API_KEY
        } `
        -Body $analysisRequest `
        -TimeoutSec 60
    
    return $claudeResponse.content[0].text
}

# ════════════════════════════════════════════════════════════════
# STEP 4: Generate Newsletter HTML
# ════════════════════════════════════════════════════════════════

function New-NewsletterHTML {
    param(
        [string]$ClaudeAnalysis,
        [PSCustomObject[]]$MarketData
    )
    
    $date = Get-Date -Format "yyyy-MM-dd"
    
    $html = @"



    


    

GOLDSHIELD Financial Newsletter

Daily Market Analysis | $date

$ClaudeAnalysis "@ foreach ($data in $MarketData | Sort-Object ChangePercent -Descending | Select-Object -First 10) { $changeColor = if ($data.ChangePercent -gt 0) { "#10b981" } else { "#ef4444" } $html += "`n" } $html += @"
TickerPriceChange %Volume
$($data.Ticker)\$$($data.Price)$($data.ChangePercent)%$($data.Volume)
"@ return $html } # ════════════════════════════════════════════════════════════════ # STEP 5: Send Newsletter via Email # ════════════════════════════════════════════════════════════════ function Send-Newsletter { param([string]$HTML, [string]$Date) if (-not $SendEmail) { Write-Host "Email sending disabled. Skipping..." return } Write-Host "📧 Sending newsletter via MCP Gmail..." # Would call MCP Gmail service # This is conceptual—Claude orchestrates the actual send Write-Host "✓ Newsletter sent successfully" } # ════════════════════════════════════════════════════════════════ # MAIN EXECUTION # ════════════════════════════════════════════════════════════════ try { Write-Host "════════════════════════════════════════════════════════════════" Write-Host "🚀 GOLDSHIELD Newsletter Engine started" Write-Host "════════════════════════════════════════════════════════════════" # Step 1: Load Configuration $config = Load-TickerConfiguration # Step 2: Fetch Market Data $marketData = Get-FinancialData -Tickers $config.Tickers # Step 3: Invoke Claude $analysis = Invoke-ClaudeAnalysis -MarketData $marketData # Step 4: Generate HTML $newsletter = New-NewsletterHTML -ClaudeAnalysis $analysis -MarketData $marketData # Step 5: Save & Send $date = Get-Date -Format "yyyy-MM-dd_HHmmss" $outputFile = "$OutputPath/newsletter_$date.html" $newsletter | Out-File $outputFile -Encoding UTF8 Send-Newsletter -HTML $newsletter -Date $date Write-Host "✓ Newsletter generation completed" Write-Host "📂 Output: $outputFile" } catch { Write-Error "Newsletter generation failed: $_" exit 1 }

6.2 Use Case 2: Self-Healing Neural Depot Terminal

Szenario: Der Neural Depot Terminal verbindet sich täglich zu 50+ APIs (XETRA, Yahoo Finance, etc.). Wenn eine API antwortet nicht, bricht der ganze Terminal zusammen.

Lösung: Autonomer Self-Healing Agent, der automatisch Fehlerbehandlung und Fallback-Systeme aktiviert.

PRODUCTION: Self-Healing Terminal with Fallback#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# NEURAL DEPOT TERMINAL - Self-Healing Agent
# ════════════════════════════════════════════════════════════════

$APIConfigs = @(
    @{ Name = "XETRA"; URL = "https://api.xetra.de/quotes"; Timeout = 10; Critical = $true }
    @{ Name = "Yahoo Finance"; URL = "https://yahoo-finance-api.com"; Timeout = 15; Critical = $false }
    @{ Name = "AlphaVantage"; URL = "https://alpha-vantage.com"; Timeout = 20; Critical = $false }
)

$APIHealth = @{}
$FailoverMode = $false

function Test-APIHealth {
    param([hashtable]$APIConfig)
    
    try {
        $response = Invoke-WebRequest -Uri "$($APIConfig.URL)/health" `
            -Method Get `
            -TimeoutSec $APIConfig.Timeout `
            -ErrorAction Stop
        
        return [PSCustomObject]@{
            Name = $APIConfig.Name
            Status = "HEALTHY"
            ResponseTime = $response.ResponseTime
            Timestamp = Get-Date
        }
    } catch {
        return [PSCustomObject]@{
            Name = $APIConfig.Name
            Status = "UNHEALTHY"
            Error = $_.Exception.Message
            Timestamp = Get-Date
        }
    }
}

function Invoke-HealthCheckLoop {
    while ($true) {
        foreach ($api in $APIConfigs) {
            $health = Test-APIHealth -APIConfig $api
            $APIHealth[$api.Name] = $health
            
            if ($health.Status -eq "UNHEALTHY" -and $api.Critical) {
                Write-Host "⚠️ CRITICAL API FAILURE: $($api.Name)"
                Invoke-Healing -APIName $api.Name
            }
        }
        
        Start-Sleep -Seconds 60
    }
}

function Invoke-Healing {
    param([string]$APIName)
    
    Write-Host "🔧 Activating Self-Healing for $APIName..."
    
    $healingActions = @(
        "Restart-Service",
        "Clear-DNSCache",
        "Test-Alternate-Endpoint",
        "Use-LocalCache",
        "Notify-Claude"
    )
    
    foreach ($action in $healingActions) {
        try {
            switch ($action) {
                "Restart-Service" {
                    # Restart API service (if local)
                    Write-Host "  └─ Restarting $APIName service..."
                }
                "Clear-DNSCache" {
                    ipconfig /flushdns | Out-Null
                    Write-Host "  └─ DNS cache cleared"
                }
                "Test-Alternate-Endpoint" {
                    # Switch to backup API endpoint
                    Write-Host "  └─ Switching to alternate endpoint..."
                }
                "Use-LocalCache" {
                    # Use cached data
                    Write-Host "  └─ Using cached data for continuity..."
                    $FailoverMode = $true
                }
                "Notify-Claude" {
                    # Alert Claude to the issue
                    Write-Host "  └─ Notifying Claude AI for analysis..."
                }
            }
        } catch {
            Write-Warning "Action $action failed: $_"
        }
    }
    
    Write-Host "✓ Self-healing completed"
}

# Start Monitoring
Invoke-HealthCheckLoop
Real-World Power

Diese beiden Case Studies zeigen, wie PowerShell + Claude zusammen: ✅ Newsletter vollautomatisch generieren ✅ APIs überwachen und selbst heilen ✅ 24/7 ohne manuales Eingreifen arbeiten ✅ Intelligent Fehler beheben statt zu crashen

Security & Execution Policies

PowerShell ist ein sehr mächtiges Tool—und deswegen auch ein Sicherheitsrisiko. Wenn Claude Code unbeschränkt PowerShell ausführen kann, kann es das ganze System compromitten. Hier sind die kritischen Security-Policies.

7.1 Execution Policy Strategy

NIEMALS Global-Execution-Policy ändern für KI-Agenten!

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned Das ist ein kritischer Fehler. Stattdessen: Per-Process-Policies mit whitelist.

SECURITY: Execution Policy für KI-Agenten# ════════════════════════════════════════════════════════════════
# SECURE POWERSHELL EXECUTION FOR CLAUDE CODE
# ════════════════════════════════════════════════════════════════

# FALSCH: Global RemoteSigned (zu unsicher)
# Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

# RICHTIG: Per-Process mit Whitelist
$AllowedCommands = @(
    "Get-Process",
    "Get-Service",
    "Get-ChildItem",
    "Get-Content",
    "Get-EventLog",
    "Invoke-RestMethod",
    "Get-Counter",
    "ConvertTo-Json",
    "ConvertFrom-Json",
    "Measure-Object",
    "Where-Object",
    "ForEach-Object",
    "Select-Object"
)

# START CLAUDE CODE PROCESS MIT RESTRICTIONS
$processParams = @{
    FilePath = "pwsh.exe"
    ArgumentList = "-NoProfile", "-ExecutionPolicy", "Restricted"
    WorkingDirectory = "C:\Secure\Claude\Scripts"
    NoNewWindow = $false
    PassThru = $true
    Environment = @{
        "CLAUDE_MODE" = "RESTRICTED"
        "ALLOWED_COMMANDS" = $AllowedCommands -join ";"
    }
}

$claudeProcess = Start-Process @processParams

# FIREWALL RULES für Claude Process
New-NetFirewallRule -DisplayName "Claude Code - Outbound HTTPS Only" `
    -Direction Outbound `
    -Action Allow `
    -Program "$claudeProcess.Path" `
    -Protocol TCP `
    -RemotePort 443 `
    -Enabled $true

New-NetFirewallRule -DisplayName "Claude Code - Block Local Network" `
    -Direction Outbound `
    -Action Block `
    -Program "$claudeProcess.Path" `
    -Protocol TCP `
    -RemoteAddress "192.168.0.0/16","10.0.0.0/8" `
    -Enabled $true

7.2 Command Whitelisting & Sandboxing

SECURITY: Restricted Command Execution#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# COMMAND WHITELIST ENGINE FOR CLAUDE
# ════════════════════════════════════════════════════════════════

class CommandWhitelist {
    [string[]]$AllowedCommands
    [string[]]$BlockedPatterns
    [hashtable]$CommandLimits
    
    CommandWhitelist() {
        $this.AllowedCommands = @(
            "Get-*",
            "ConvertTo-Json",
            "ConvertFrom-Json",
            "Measure-Object",
            "Where-Object",
            "ForEach-Object",
            "Select-Object",
            "Sort-Object",
            "Group-Object",
            "Write-Host",  # Output only
            "Write-Output"
        )
        
        $this.BlockedPatterns = @(
            "Remove-Item",
            "Set-*",
            "New-*",
            "Invoke-Command",  # Remote execution
            "Start-Process",   # Arbitrary process start
            "Add-Type",        # Code injection
            "Out-GridView",    # GUI (hang risk)
            "Write-Host *Red*" # Security logging bypass
        )
        
        $this.CommandLimits = @{
            "Get-ChildItem" = 100  # Max items returned
            "Get-Process" = 50
            "Get-EventLog" = 1000  # Log entries
        }
    }
    
    [bool] IsCommandAllowed([string]$Command) {
        # Check blacklist first
        foreach ($pattern in $this.BlockedPatterns) {
            if ($Command -like $pattern) {
                return $false
            }
        }
        
        # Check whitelist
        foreach ($allowedCmd in $this.AllowedCommands) {
            if ($Command -like $allowedCmd) {
                return $true
            }
        }
        
        return $false
    }
    
    [int] GetCommandLimit([string]$Command) {
        return $this.CommandLimits[$Command] ?? 1000
    }
}

# ════════════════════════════════════════════════════════════════
# EXECUTION WRAPPER
# ════════════════════════════════════════════════════════════════

$whitelist = [CommandWhitelist]::new()

function Invoke-WhitelistedCommand {
    param(
        [string]$Command,
        [hashtable]$Parameters
    )
    
    # Check whitelist
    if (-not $whitelist.IsCommandAllowed($Command)) {
        throw "Command '$Command' is not whitelisted for Claude execution"
    }
    
    # Check parameter restrictions
    foreach ($param in $Parameters.Keys) {
        if ($param -like "*Path*" -or $param -like "*File*") {
            # Restrict to specific directories
            $path = $Parameters[$param]
            if (-not $path.StartsWith("C:\Safe\Claude\")) {
                throw "Path access denied: $path"
            }
        }
    }
    
    # Execute with timeout
    $job = Start-Job -ScriptBlock {
        param($Cmd, $Params)
        & $Cmd @Params
    } -ArgumentList $Command, $Parameters
    
    $result = Wait-Job -Job $job -Timeout 30
    
    if ($null -eq $result) {
        Stop-Job -Job $job
        throw "Command execution timeout: $Command"
    }
    
    return Receive-Job -Job $job | ConvertTo-Json
}

# ════════════════════════════════════════════════════════════════
# AUDIT LOGGING
# ════════════════════════════════════════════════════════════════

function Log-CommandExecution {
    param(
        [string]$Command,
        [string]$Status,
        [string]$Result
    )
    
    [PSCustomObject]@{
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
        Command = $Command
        Status = $Status
        Result = $Result
        User = $env:USERNAME
        ProcessID = $PID
    } | ConvertTo-Json | Out-File -FilePath "claude_audit.jsonl" -Append
}

Performance Tuning & Debugging

Wenn das Agentic Loop langsam wird oder Fehler auftreten, braucht der Agent selbst gute Debugging-Tools. Hier sind Production-Grade Tools dafür.

8.1 Performance Profiling

PRODUCTION: Performance Profiling für Loops#!/usr/bin/env pwsh

# ════════════════════════════════════════════════════════════════
# PERFORMANCE PROFILER FOR AGENTIC LOOPS
# ════════════════════════════════════════════════════════════════

class PerformanceProfile {
    [string]$LoopName
    [int]$LoopNumber
    [double]$TotalExecutionTime
    [hashtable]$PhaseTimings
    [int]$MemoryUsedMB
    [int]$CPUPercent
    
    [PSCustomObject] ToJSON() {
        return [PSCustomObject]@{
            LoopName = $this.LoopName
            LoopNumber = $this.LoopNumber
            ExecutionTime = [PSCustomObject]@{
                Total = $this.TotalExecutionTime
                Phases = $this.PhaseTimings
            }
            Resources = [PSCustomObject]@{
                MemoryMB = $this.MemoryUsedMB
                CPUPercent = $this.CPUPercent
            }
        }
    }
}

function Measure-LoopPerformance {
    param(
        [string]$LoopName,
        [scriptblock]$LoopLogic,
        [int]$Iterations = 5
    )
    
    Write-Host "📊 Profiling $LoopName for $Iterations iterations..."
    
    $profiles = @()
    
    for ($i = 1; $i -le $Iterations; $i++) {
        $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
        $memBefore = (Get-Process -Id $PID).WorkingSetMB
        
        # Execute loop iteration
        & $LoopLogic
        
        $stopwatch.Stop()
        $memAfter = (Get-Process -Id $PID).WorkingSetMB
        
        $profile = [PerformanceProfile]@{
            LoopName = $LoopName
            LoopNumber = $i
            TotalExecutionTime = $stopwatch.ElapsedMilliseconds
            MemoryUsedMB = $memAfter - $memBefore
            CPUPercent = 0  # Would be calculated from counter
        }
        
        $profiles += $profile
        
        Write-Host "  ✓ Iteration $i completed in $($stopwatch.ElapsedMilliseconds)ms"
    }
    
    # Analysis
    $avgTime = ($profiles | Measure-Object -Property TotalExecutionTime -Average).Average
    $maxTime = ($profiles | Measure-Object -Property TotalExecutionTime -Maximum).Maximum
    $minTime = ($profiles | Measure-Object -Property TotalExecutionTime -Minimum).Minimum
    
    Write-Host "`n📈 Performance Summary:"
    Write-Host "  Average: ${avgTime}ms"
    Write-Host "  Max: ${maxTime}ms"
    Write-Host "  Min: ${minTime}ms"
    Write-Host "  Variance: $(($maxTime - $minTime)ms)"
    
    return $profiles
}

# ════════════════════════════════════════════════════════════════
# BOTTLENECK DETECTION
# ════════════════════════════════════════════════════════════════

function Find-PerformanceBottleneck {
    param([PerformanceProfile[]]$Profiles)
    
    $avgTime = ($Profiles | Measure-Object -Property TotalExecutionTime -Average).Average
    
    foreach ($profile in $Profiles) {
        if ($profile.TotalExecutionTime -gt ($avgTime * 1.5)) {
            Write-Warning "⚠️ Loop #$($profile.LoopNumber) is $($profile.TotalExecutionTime - $avgTime)ms slower than average"
        }
    }
}

# ════════════════════════════════════════════════════════════════
# LOGGING & DEBUGGING
# ════════════════════════════════════════════════════════════════

$DebugConfig = @{
    LogLevel = "INFO"  # INFO, DEBUG, ERROR
    LogFile = "./debug.jsonl"
    KeepHistoryDays = 7
}

function Write-DebugLog {
    param(
        [string]$Message,
        [string]$Level = "INFO",
        [hashtable]$Context = @{}
    )
    
    if ($DebugConfig.LogLevel -eq "INFO" -and $Level -eq "DEBUG") {
        return
    }
    
    $logEntry = [PSCustomObject]@{
        Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss.fff"
        Level = $Level
        Message = $Message
        Context = $Context
        ProcessID = $PID
    }
    
    $logEntry | ConvertTo-Json | Out-File -FilePath $DebugConfig.LogFile -Append
}

# Example usage
Write-DebugLog -Message "Loop iteration started" -Level DEBUG -Context @{
    LoopNumber = 1
    PhaseCount = 5
}
Optimization Strategy

Nach dieser Profiling, optimierst du: 1. **Bottleneck-Analyse**: Welche Phase dauert am längsten? 2. **API-Calls Cachen**: Häufige Calls cachen 3. **Parallelisierung**: Unabhängige Operationen parallel ausführen 4. **JSON-Depth Begrenzen**: Tiefer JSON = langsamer Parsing

Fazit: Die Zukunft ist Agentic

PowerShell + Claude Code ist nicht nur eine technische Integration—es ist eine neue Paradigma für Automation. Während traditionelle Automation starr und fragil ist, sind Agentic Systeme adaptiv, selbstheilend und intelligent.

Mit den Patterns aus diesem Guide kannst du:

Nächste Schritte für deine Genitus Projekte

🚀 Immediate (Diese Woche)

  • Agentic Loop Wrapper implementieren
  • Health Check Monitoring starten
  • Logging & Debugging-Infrastructure setup

📈 Short-term (Diese Monat)

  • MCP Integration für Gmail + Google Drive
  • GOLDSHIELD mit autonomem Loop erweitern
  • Neural Depot Terminal Self-Healing aktivieren

🎯 Medium-term (Nächste 3 Monate)

  • Alle Genitus Services mit Agentic Loops
  • Cross-Service Orchestration (Newsletter → Monitoring → Email)
  • Advanced Performance Optimization

🔮 Vision (6+ Monate)

  • Fully Autonomous Fintech Platform
  • Global Real-Time Trading Orchestration
  • Multi-Agent Swarm Computing
Das Fundament ist gelegt

Du hast jetzt nicht nur ein Handbuch, sondern ein operatives System für Agentic Computing. PowerShell + Claude Code + Heartbeat Monitoring = die Zukunft deiner Genitus-Infrastruktur.

Bre, jetzt wird es ernst. 🚀