# Operations: migrations, health check, backup and restore. function Update-FoundryDatabase { <# .SYNOPSIS Apply pending SQL migrations from infrastructure/postgres/migrations (idempotent). #> [CmdletBinding()] param([string]$Database) $dir = Join-Path $script:FoundryRoot 'infrastructure/postgres/migrations' $null = Invoke-FkeSql -Database $Database -Text -Sql 'CREATE EXTENSION IF NOT EXISTS vector; CREATE SCHEMA IF NOT EXISTS knowledge; CREATE TABLE IF NOT EXISTS knowledge.schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW());' $applied = @((Invoke-FkeSql -Database $Database -Sql "SELECT COALESCE(jsonb_agg(version), '[]'::jsonb) FROM knowledge.schema_migrations;")) foreach ($f in Get-ChildItem -LiteralPath $dir -Filter '*.sql' | Sort-Object Name) { if ($f.BaseName -in $applied) { Write-Verbose "already applied: $($f.Name)"; continue } $sql = Get-Content -LiteralPath $f.FullName -Raw $null = Invoke-FkeSql -Database $Database -Text -Sql ("BEGIN;`n$sql`nINSERT INTO knowledge.schema_migrations (version) VALUES ('$($f.BaseName)');`nCOMMIT;") Write-Host "applied migration $($f.Name)" } } function Test-FoundryKnowledge { <# .SYNOPSIS Check that the knowledge system is usable. Never throws. .DESCRIPTION Ready = database and schema work. EmbeddingsReady = Ollama and the model also work. Without EmbeddingsReady, storing still works but search is keyword-only. #> [CmdletBinding()] param([switch]$AsJson) $cfg = Get-FkeConfig $checks = [System.Collections.Generic.List[object]]::new() $add = { param($n, $ok, $d) $checks.Add([pscustomobject]@{ check = $n; ok = [bool]$ok; detail = $d }) } $docker = Get-Command docker -ErrorAction SilentlyContinue & $add 'docker CLI' $docker $(if ($docker) { 'found' } else { 'docker not found on PATH' }) $health = $null if ($docker) { $health = (& docker inspect -f '{{.State.Status}}/{{.State.Health.Status}}' $cfg.Container 2>&1 | Select-Object -First 1) } $running = $health -like 'running/*' & $add "container $($cfg.Container)" $running $(if ($running) { $health } else { "not running. Run: pwsh -File scripts/Start-Foundry.ps1 ($health)" }) $dbOk = $false; $schemaOk = $false if ($running) { try { $r = Invoke-FkeSql -Sql "SELECT to_jsonb(r) FROM (SELECT (SELECT extversion FROM pg_extension WHERE extname='vector') AS vector, (SELECT count(*) FROM information_schema.tables WHERE table_schema='knowledge' AND table_name IN ('entries','relationships','sessions')) AS tables, (SELECT COALESCE(max(version),'none') FROM knowledge.schema_migrations) AS migration) r;" $dbOk = $true & $add "database $($cfg.Database)" $true 'reachable' $schemaOk = ($r.tables -eq 3 -and $r.vector) & $add 'schema' $schemaOk $(if ($schemaOk) { "3 tables, pgvector $($r.vector), migration $($r.migration)" } else { 'missing. Run: pwsh -File scripts/Initialize-Foundry.ps1' }) } catch { if (-not $dbOk) { & $add "database $($cfg.Database)" $false $_.Exception.Message } else { & $add 'schema' $false 'missing. Run: pwsh -File scripts/Initialize-Foundry.ps1' } } } $embOk = $false try { $tags = Invoke-RestMethod -Uri "$($cfg.OllamaUrl)/api/tags" -TimeoutSec 5 & $add "ollama $($cfg.OllamaUrl)" $true 'reachable' $hasModel = @($tags.models | Where-Object { $_.name -eq $cfg.EmbeddingModel -or $_.name -eq "$($cfg.EmbeddingModel):latest" }).Count -gt 0 & $add "model $($cfg.EmbeddingModel)" $hasModel $(if ($hasModel) { 'present' } else { "missing. Run: ollama pull $($cfg.EmbeddingModel)" }) if ($hasModel) { $v = Get-FkeEmbedding -Text 'health check' $embOk = $true & $add 'embedding dimensions' $true "$($v.Count) (schema expects $($cfg.EmbeddingDimension))" } } catch { & $add "ollama $($cfg.OllamaUrl)" $false $_.Exception.Message } $result = [pscustomobject]@{ Ready = ($dbOk -and $schemaOk); EmbeddingsReady = $embOk; Checks = @($checks) } Out-FkeResult $result -AsJson:$AsJson } function Backup-FoundryKnowledge { <# .SYNOPSIS pg_dump (custom format) of the knowledge schema to backups/ or -Path. Returns the file path. #> [CmdletBinding()] param([string]$Path) $cfg = Get-FkeConfig if (-not $Path) { $dir = Join-Path $script:FoundryRoot 'backups' New-Item -ItemType Directory -Force -Path $dir | Out-Null $Path = Join-Path $dir ("foundry-knowledge-{0}.dump" -f (Get-Date -Format 'yyyyMMdd-HHmmss')) } $Path = [IO.Path]::GetFullPath($Path) New-Item -ItemType Directory -Force -Path (Split-Path $Path -Parent) | Out-Null $tmp = "/tmp/fke-backup-$([Guid]::NewGuid().ToString('N')).dump" & docker exec $cfg.Container pg_dump -U $cfg.User -d $cfg.Database -n knowledge -Fc -f $tmp if ($LASTEXITCODE -ne 0) { throw 'pg_dump failed.' } try { & docker cp "$($cfg.Container):$tmp" $Path if ($LASTEXITCODE -ne 0) { throw 'docker cp failed.' } } finally { & docker exec $cfg.Container rm -f $tmp | Out-Null } $Path } function Restore-FoundryKnowledge { <# .SYNOPSIS Replace the knowledge schema with the contents of a dump. Destructive: requires -Force. #> [CmdletBinding()] param([Parameter(Mandatory)][string]$Path, [switch]$Force) if (-not $Force) { throw 'Restore replaces everything in the knowledge schema. Re-run with -Force to confirm (consider Backup-FoundryKnowledge first).' } if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "Backup file not found: $Path" } $cfg = Get-FkeConfig $tmp = "/tmp/fke-restore-$([Guid]::NewGuid().ToString('N')).dump" & docker cp (Resolve-Path -LiteralPath $Path).ProviderPath "$($cfg.Container):$tmp" if ($LASTEXITCODE -ne 0) { throw 'docker cp failed.' } try { & docker exec $cfg.Container pg_restore -U $cfg.User -d $cfg.Database --clean --if-exists --no-owner -n knowledge $tmp if ($LASTEXITCODE -ne 0) { throw 'pg_restore reported errors.' } } finally { & docker exec $cfg.Container rm -f $tmp | Out-Null } Write-Host "Restored knowledge schema from $Path" }