Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

104 lines
6.2KB

  1. # Operations: migrations, health check, backup and restore.
  2. function Update-FoundryDatabase {
  3. <# .SYNOPSIS Apply pending SQL migrations from infrastructure/postgres/migrations (idempotent). #>
  4. [CmdletBinding()]
  5. param([string]$Database)
  6. $dir = Join-Path $script:FoundryRoot 'infrastructure/postgres/migrations'
  7. $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());'
  8. $applied = @((Invoke-FkeSql -Database $Database -Sql "SELECT COALESCE(jsonb_agg(version), '[]'::jsonb) FROM knowledge.schema_migrations;"))
  9. foreach ($f in Get-ChildItem -LiteralPath $dir -Filter '*.sql' | Sort-Object Name) {
  10. if ($f.BaseName -in $applied) { Write-Verbose "already applied: $($f.Name)"; continue }
  11. $sql = Get-Content -LiteralPath $f.FullName -Raw
  12. $null = Invoke-FkeSql -Database $Database -Text -Sql ("BEGIN;`n$sql`nINSERT INTO knowledge.schema_migrations (version) VALUES ('$($f.BaseName)');`nCOMMIT;")
  13. Write-Host "applied migration $($f.Name)"
  14. }
  15. }
  16. function Test-FoundryKnowledge {
  17. <#
  18. .SYNOPSIS Check that the knowledge system is usable. Never throws.
  19. .DESCRIPTION Ready = database and schema work. EmbeddingsReady = Ollama and the model also work.
  20. Without EmbeddingsReady, storing still works but search is keyword-only.
  21. #>
  22. [CmdletBinding()]
  23. param([switch]$AsJson)
  24. $cfg = Get-FkeConfig
  25. $checks = [System.Collections.Generic.List[object]]::new()
  26. $add = { param($n, $ok, $d) $checks.Add([pscustomobject]@{ check = $n; ok = [bool]$ok; detail = $d }) }
  27. $docker = Get-Command docker -ErrorAction SilentlyContinue
  28. & $add 'docker CLI' $docker $(if ($docker) { 'found' } else { 'docker not found on PATH' })
  29. $health = $null
  30. if ($docker) { $health = (& docker inspect -f '{{.State.Status}}/{{.State.Health.Status}}' $cfg.Container 2>&1 | Select-Object -First 1) }
  31. $running = $health -like 'running/*'
  32. & $add "container $($cfg.Container)" $running $(if ($running) { $health } else { "not running. Run: pwsh -File scripts/Start-Foundry.ps1 ($health)" })
  33. $dbOk = $false; $schemaOk = $false
  34. if ($running) {
  35. try {
  36. $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;"
  37. $dbOk = $true
  38. & $add "database $($cfg.Database)" $true 'reachable'
  39. $schemaOk = ($r.tables -eq 3 -and $r.vector)
  40. & $add 'schema' $schemaOk $(if ($schemaOk) { "3 tables, pgvector $($r.vector), migration $($r.migration)" } else { 'missing. Run: pwsh -File scripts/Initialize-Foundry.ps1' })
  41. } catch {
  42. if (-not $dbOk) { & $add "database $($cfg.Database)" $false $_.Exception.Message } else { & $add 'schema' $false 'missing. Run: pwsh -File scripts/Initialize-Foundry.ps1' }
  43. }
  44. }
  45. $embOk = $false
  46. try {
  47. $tags = Invoke-RestMethod -Uri "$($cfg.OllamaUrl)/api/tags" -TimeoutSec 5
  48. & $add "ollama $($cfg.OllamaUrl)" $true 'reachable'
  49. $hasModel = @($tags.models | Where-Object { $_.name -eq $cfg.EmbeddingModel -or $_.name -eq "$($cfg.EmbeddingModel):latest" }).Count -gt 0
  50. & $add "model $($cfg.EmbeddingModel)" $hasModel $(if ($hasModel) { 'present' } else { "missing. Run: ollama pull $($cfg.EmbeddingModel)" })
  51. if ($hasModel) {
  52. $v = Get-FkeEmbedding -Text 'health check'
  53. $embOk = $true
  54. & $add 'embedding dimensions' $true "$($v.Count) (schema expects $($cfg.EmbeddingDimension))"
  55. }
  56. } catch {
  57. & $add "ollama $($cfg.OllamaUrl)" $false $_.Exception.Message
  58. }
  59. $result = [pscustomobject]@{ Ready = ($dbOk -and $schemaOk); EmbeddingsReady = $embOk; Checks = @($checks) }
  60. Out-FkeResult $result -AsJson:$AsJson
  61. }
  62. function Backup-FoundryKnowledge {
  63. <# .SYNOPSIS pg_dump (custom format) of the knowledge schema to backups/ or -Path. Returns the file path. #>
  64. [CmdletBinding()]
  65. param([string]$Path)
  66. $cfg = Get-FkeConfig
  67. if (-not $Path) {
  68. $dir = Join-Path $script:FoundryRoot 'backups'
  69. New-Item -ItemType Directory -Force -Path $dir | Out-Null
  70. $Path = Join-Path $dir ("foundry-knowledge-{0}.dump" -f (Get-Date -Format 'yyyyMMdd-HHmmss'))
  71. }
  72. $Path = [IO.Path]::GetFullPath($Path)
  73. New-Item -ItemType Directory -Force -Path (Split-Path $Path -Parent) | Out-Null
  74. $tmp = "/tmp/fke-backup-$([Guid]::NewGuid().ToString('N')).dump"
  75. & docker exec $cfg.Container pg_dump -U $cfg.User -d $cfg.Database -n knowledge -Fc -f $tmp
  76. if ($LASTEXITCODE -ne 0) { throw 'pg_dump failed.' }
  77. try {
  78. & docker cp "$($cfg.Container):$tmp" $Path
  79. if ($LASTEXITCODE -ne 0) { throw 'docker cp failed.' }
  80. } finally { & docker exec $cfg.Container rm -f $tmp | Out-Null }
  81. $Path
  82. }
  83. function Restore-FoundryKnowledge {
  84. <# .SYNOPSIS Replace the knowledge schema with the contents of a dump. Destructive: requires -Force. #>
  85. [CmdletBinding()]
  86. param([Parameter(Mandatory)][string]$Path, [switch]$Force)
  87. if (-not $Force) { throw 'Restore replaces everything in the knowledge schema. Re-run with -Force to confirm (consider Backup-FoundryKnowledge first).' }
  88. if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "Backup file not found: $Path" }
  89. $cfg = Get-FkeConfig
  90. $tmp = "/tmp/fke-restore-$([Guid]::NewGuid().ToString('N')).dump"
  91. & docker cp (Resolve-Path -LiteralPath $Path).ProviderPath "$($cfg.Container):$tmp"
  92. if ($LASTEXITCODE -ne 0) { throw 'docker cp failed.' }
  93. try {
  94. & docker exec $cfg.Container pg_restore -U $cfg.User -d $cfg.Database --clean --if-exists --no-owner -n knowledge $tmp
  95. if ($LASTEXITCODE -ne 0) { throw 'pg_restore reported errors.' }
  96. } finally { & docker exec $cfg.Container rm -f $tmp | Out-Null }
  97. Write-Host "Restored knowledge schema from $Path"
  98. }

Powered by TurnKey Linux.