Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

285 рядки
20KB

  1. <#
  2. .SYNOPSIS
  3. Automated checks for the Foundry Knowledge Engine (module, schema, search, graph, sessions, backup).
  4. .DESCRIPTION
  5. Runs against the real PostgreSQL container and the real Ollama embedding model, but in a scratch
  6. database ("foundry_test_<random>") that is created and dropped by the run. Your knowledge
  7. database is never touched. Needs: the foundry-postgres container running (scripts/Start-Foundry.ps1).
  8. Checks that need Ollama are skipped, with the reason, when the embedding model is unavailable.
  9. Uses the same check-runner style as tests/Run-FoundryTests.ps1 (Pester 5 is not required).
  10. Exit code 0 = no failures.
  11. .EXAMPLE
  12. pwsh -File tests/Knowledge.Tests.ps1
  13. #>
  14. [CmdletBinding()]
  15. param()
  16. $ErrorActionPreference = 'Stop'
  17. $root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
  18. Import-Module (Join-Path $root 'powershell/Foundry.Knowledge/Foundry.Knowledge.psd1') -Force
  19. $script:Results = [System.Collections.Generic.List[object]]::new()
  20. function Invoke-Check([string]$Name, [scriptblock]$Body) {
  21. try {
  22. $detail = & $Body
  23. $status = if ($detail -is [string] -and $detail.StartsWith('SKIP:')) { 'SKIP' } else { 'PASS' }
  24. $script:Results.Add([pscustomobject]@{ Name = $Name; Status = $status; Detail = "$detail" })
  25. } catch {
  26. $script:Results.Add([pscustomobject]@{ Name = $Name; Status = 'FAIL'; Detail = $_.Exception.Message })
  27. }
  28. $r = $script:Results[-1]
  29. $color = @{ PASS = 'Green'; FAIL = 'Red'; SKIP = 'Yellow' }[$r.Status]
  30. Write-Host ("[{0}] {1}{2}" -f $r.Status, $Name, $(if ($r.Detail) { " - $($r.Detail)" } else { '' })) -ForegroundColor $color
  31. }
  32. function Assert([bool]$Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
  33. function Assert-Throws([scriptblock]$Body, [string]$Pattern) {
  34. try { & $Body } catch { if ($_.Exception.Message -match $Pattern) { return }; throw "Threw the wrong error: $($_.Exception.Message)" }
  35. throw "Expected an error matching '$Pattern' but nothing was thrown."
  36. }
  37. function Invoke-FkeSqlForTest([string]$Sql) { & (Get-Module Foundry.Knowledge) { param($s) Invoke-FkeSql -Sql $s } $Sql }
  38. function Invoke-AdminSql([string]$Sql) {
  39. $cfg = Get-Variable -Name cfg -Scope Script -ValueOnly
  40. $out = & docker exec $cfg.Container psql -U $cfg.User -d postgres -X -q -t -A -v ON_ERROR_STOP=1 -c $Sql 2>&1
  41. if ($LASTEXITCODE -ne 0) { throw "admin sql failed: $out" }
  42. }
  43. $h = Test-FoundryKnowledge
  44. if (-not $h.Ready) { Write-Host 'The knowledge database is not running. Run: pwsh -File scripts/Start-Foundry.ps1' -ForegroundColor Red; exit 1 }
  45. $embeddings = $h.EmbeddingsReady
  46. $script:cfg = [pscustomobject]@{ Container = 'foundry-postgres'; User = 'foundry' }
  47. $db = 'foundry_test_' + [Guid]::NewGuid().ToString('N').Substring(0, 8)
  48. $savedDb = $env:FOUNDRY_PG_DATABASE
  49. $savedOllama = $env:FOUNDRY_OLLAMA_URL
  50. $savedProject = $env:FOUNDRY_PROJECT_KEY
  51. $env:FOUNDRY_PROJECT_KEY = $null
  52. Invoke-AdminSql "CREATE DATABASE $db"
  53. $env:FOUNDRY_PG_DATABASE = $db
  54. $skipEmb = 'SKIP: Ollama or the embedding model is unavailable'
  55. $ids = @{}
  56. try {
  57. Invoke-Check 'migrations: apply to a fresh database, then re-run applies nothing' {
  58. $first = Update-FoundryDatabase 6>&1 | Out-String
  59. Assert ($first -match 'applied migration 001') "first run output: $first"
  60. $second = Update-FoundryDatabase 6>&1 | Out-String
  61. Assert (-not ($second -match 'applied migration')) "second run re-applied: $second"
  62. $t = Test-FoundryKnowledge
  63. Assert $t.Ready 'Test-FoundryKnowledge not Ready after migration'
  64. }
  65. Invoke-Check 'add/get: hostile text round-trips exactly (quotes, backslashes, $tags$, unicode, SQL)' {
  66. $title = "Tricky '; DROP TABLE knowledge.entries; -- `"q`" \ back"
  67. $content = "line1`nline2 with `$fke`$ and `$`$ and \n literal, unicode: caf$([char]0xE9) $([char]0x2192) $([char]0x4E2D)$([char]0x6587), 100% & <tag>"
  68. $r = Add-FoundryKnowledge -Title $title -Content $content -Type technical-fact -Project qa-one -Force
  69. Assert $r.created 'not created'
  70. $g = Get-FoundryKnowledge -Id $r.id
  71. Assert ($g.title -ceq $title) "title changed: $($g.title)"
  72. Assert ($g.content -ceq $content) "content changed: $($g.content)"
  73. Assert ($g.project -eq 'qa-one' -and $g.status -eq 'unverified' -and $g.confidence -eq 0.5) 'defaults wrong'
  74. $ids.tricky = $r.id
  75. "id $($r.id), embedded=$($r.embedded)"
  76. }
  77. Invoke-Check 'domain rules: secrets, verified-needs-source, unknown type, blank, bad project key' {
  78. Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'password = hunter2hunter2' -Type lesson-learned -Force } 'credential'
  79. Assert-Throws { Add-FoundryKnowledge -Title 't' -Content '-----BEGIN RSA PRIVATE KEY-----' -Type lesson-learned -Force } 'credential'
  80. Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'conn postgres://u:p4ssw0rd@host/db' -Type lesson-learned -Force } 'credential'
  81. Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'fine' -Type lesson-learned -Status verified -Force } 'needs a Source'
  82. Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'fine' -Type nonsense -Force } 'Unknown knowledge type'
  83. Assert-Throws { Add-FoundryKnowledge -Title ' ' -Content 'fine' -Type lesson-learned -Force } 'blank'
  84. Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'fine' -Type lesson-learned -Project 'Bad Key' -Force } 'Invalid project key'
  85. $n = Invoke-FkeSqlForTest "SELECT count(*) FROM knowledge.entries"
  86. Assert ($n -eq 1) "rejected entries were stored (count $n)"
  87. }
  88. Invoke-Check 'dedup: same title is refused; -Force stores; different project scope is allowed' {
  89. $a = Add-FoundryKnowledge -Title 'C128 memory banking' -Content 'The MMU at $D500 selects banks.' -Type technical-fact -Global
  90. Assert $a.created 'first not created'
  91. $b = Add-FoundryKnowledge -Title ' c128 MEMORY banking ' -Content 'Entirely different words here.' -Type technical-fact -Global
  92. Assert (-not $b.created -and $b.duplicateOf -eq $a.id) 'duplicate title not detected'
  93. $c = Add-FoundryKnowledge -Title 'C128 memory banking' -Content 'x' -Type technical-fact -Project qa-two
  94. Assert $c.created 'same title in another project scope should be allowed'
  95. $d = Add-FoundryKnowledge -Title 'C128 memory banking' -Content 'forced copy' -Type technical-fact -Global -Force
  96. Assert $d.created '-Force did not store'
  97. $ids.banking = $a.id; $ids.bankingOther = $c.id
  98. }
  99. Invoke-Check 'dedup: near-identical content under a different title is caught by embedding similarity' {
  100. if (-not $embeddings) { return $skipEmb }
  101. $text = 'Controllers should not contain business rules; put them in a service layer.'
  102. $a = Add-FoundryKnowledge -Title 'MVC separation' -Content $text -Type technical-fact -Project qa-one
  103. $b = Add-FoundryKnowledge -Title 'Keep controllers thin' -Content $text -Type technical-fact -Project qa-one
  104. Assert (-not $b.created -and $b.duplicateOf -eq $a.id -and $b.similarity -ge 0.80) "not caught: $($b | ConvertTo-Json -Compress)"
  105. $ids.mvc = $a.id
  106. "similarity $($b.similarity)"
  107. }
  108. Invoke-Check 'search: semantic match without shared keywords' {
  109. if (-not $embeddings) { return $skipEmb }
  110. $null = Add-FoundryKnowledge -Title 'SID voice registers' -Content 'The SID chip has three voices with ADSR envelopes.' -Type technical-fact -Global
  111. $null = Add-FoundryKnowledge -Title 'VICE headless smoke test' -Content 'Run the emulator without a window and compare a screenshot.' -Type procedure -Global
  112. $r = Search-FoundryKnowledge -Query 'How should I separate presentation from domain logic?' -Project qa-one -Limit 3
  113. Assert ($r.mode -eq 'hybrid') "mode $($r.mode)"
  114. Assert ($r.results[0].id -eq $ids.mvc) "top hit was '$($r.results[0].title)', expected the MVC entry"
  115. $words = 'separate', 'presentation', 'domain', 'logic'
  116. Assert (-not ($words | Where-Object { $r.results[0].content -match $_ })) 'test premise broken: keywords overlap'
  117. "top similarity $($r.results[0].similarity), score $($r.results[0].score)"
  118. }
  119. Invoke-Check 'search: keyword fallback when Ollama is unreachable' {
  120. $env:FOUNDRY_OLLAMA_URL = 'http://127.0.0.1:9'
  121. try {
  122. $r = Search-FoundryKnowledge -Query 'MMU selects banks' -WarningAction SilentlyContinue
  123. Assert ($r.mode -eq 'keyword-only') "mode $($r.mode)"
  124. Assert (@($r.results).Count -ge 1 -and $r.results[0].title -match 'memory banking') 'keyword search did not find the entry'
  125. $w = Add-FoundryKnowledge -Title 'Stored offline' -Content 'saved while Ollama was down' -Type lesson-learned -Global -WarningAction SilentlyContinue
  126. Assert ($w.created -and -not $w.embedded) 'offline add should store without embedding'
  127. } finally { $env:FOUNDRY_OLLAMA_URL = $savedOllama }
  128. }
  129. Invoke-Check 'search: project scope returns project + global, never another project' {
  130. $r = Search-FoundryKnowledge -Query 'C128 memory banking' -Project qa-one -Limit 10
  131. Assert (-not ($r.results | Where-Object { $_.project -eq 'qa-two' })) 'leaked qa-two entry into qa-one'
  132. Assert (@($r.results | Where-Object { -not $_.project }).Count -gt 0) 'global entry missing'
  133. $env:FOUNDRY_PROJECT_KEY = 'qa-two'
  134. try { Assert ((Get-FoundryProjectContext) -eq 'qa-two') 'env project not used' } finally { $env:FOUNDRY_PROJECT_KEY = $null }
  135. }
  136. Invoke-Check 'search: -VerifiedOnly, -Type and update (status, tags, metadata merge, re-embed)' {
  137. $before = Search-FoundryKnowledge -Query 'MMU selects banks' -VerifiedOnly
  138. Assert (@($before.results).Count -eq 0) 'unverified entry returned with -VerifiedOnly'
  139. $u = Update-FoundryKnowledge -Id $ids.banking -Status verified -Source 'C128 Programmer''s Reference Guide' -Confidence 0.95 -Tags 'c128', 'mmu' -Metadata @{ a = 1 }
  140. $u = Update-FoundryKnowledge -Id $ids.banking -Metadata @{ b = 2 } -Content 'The MMU at $D500 selects banks; $FF00 is the configuration register.'
  141. $g = Get-FoundryKnowledge -Id $ids.banking
  142. Assert ($g.status -eq 'verified' -and $g.confidence -eq 0.95) 'status/confidence not updated'
  143. Assert (($g.tags -join ',') -eq 'c128,mmu') 'tags not updated'
  144. Assert ($g.metadata.a -eq 1 -and $g.metadata.b -eq 2) 'metadata not merged'
  145. Assert ($g.content -match 'FF00') 'content not updated'
  146. $after = Search-FoundryKnowledge -Query 'MMU selects banks' -VerifiedOnly
  147. Assert (@($after.results).Count -eq 1 -and $after.results[0].id -eq $ids.banking) 'verified entry not found'
  148. $typed = Search-FoundryKnowledge -Query 'MMU banks' -Type procedure
  149. Assert (-not ($typed.results | Where-Object { $_.type -ne 'procedure' })) '-Type filter ignored'
  150. Assert-Throws { Update-FoundryKnowledge -Id $ids.banking -Content 'password = abcdef123456' } 'credential'
  151. Assert-Throws { Update-FoundryKnowledge -Id 999999 -Title 'x' } 'No knowledge entry'
  152. }
  153. Invoke-Check 'graph: edges, idempotence, cycle-safe traversal, direction, depth' {
  154. $a = (Add-FoundryKnowledge -Title 'Graph A' -Content 'node a' -Type technical-fact -Global -Force).id
  155. $b = (Add-FoundryKnowledge -Title 'Graph B' -Content 'node b' -Type technical-fact -Global -Force).id
  156. $c = (Add-FoundryKnowledge -Title 'Graph C' -Content 'node c' -Type technical-fact -Global -Force).id
  157. $d = (Add-FoundryKnowledge -Title 'Graph D' -Content 'node d' -Type technical-fact -Global -Force).id
  158. $e1 = Add-FoundryRelationship -SourceId $a -TargetId $b -Type depends_on
  159. Assert ($e1.created -and $e1.relationship_type -eq 'DEPENDS_ON') 'edge 1'
  160. $again = Add-FoundryRelationship -SourceId $a -TargetId $b -Type DEPENDS_ON
  161. Assert (-not $again.created -and $again.id -eq $e1.id) 'duplicate edge should report created=false with the same id'
  162. $null = Add-FoundryRelationship -SourceId $b -TargetId $c -Type RELATED_TO
  163. $null = Add-FoundryRelationship -SourceId $c -TargetId $a -Type RELATED_TO # cycle a>b>c>a
  164. $null = Add-FoundryRelationship -SourceId $c -TargetId $d -Type SOLVES
  165. $d1 = Get-FoundryRelationships -Id $a -Depth 1
  166. Assert ((@($d1.related.id | Sort-Object) -join ',') -eq (@($b, $c | Sort-Object) -join ',')) "depth 1 (both): $($d1.related.id -join ',')"
  167. $d3 = Get-FoundryRelationships -Id $a -Depth 3
  168. $got = @($d3.related.id | Sort-Object)
  169. Assert ($got.Count -eq 3 -and $got -contains $b -and $got -contains $c -and $got -contains $d) "depth 3 should reach b,c,d once each: $got"
  170. Assert (($d3.related | Where-Object id -eq $d).depth -eq 2) 'd should be at depth 2 via c'
  171. $out = Get-FoundryRelationships -Id $a -Depth 3 -Direction Out
  172. Assert (@($out.related.id).Count -eq 3) "out traversal: $($out.related.id -join ',')"
  173. $in = Get-FoundryRelationships -Id $d -Depth 1 -Direction In
  174. Assert (@($in.related).Count -eq 1 -and $in.related[0].id -eq $c -and $in.related[0].relationship -eq 'SOLVES') 'in traversal'
  175. $typed = Get-FoundryRelationships -Id $a -Depth 3 -Type DEPENDS_ON
  176. Assert (@($typed.related).Count -eq 1) 'type filter'
  177. Assert-Throws { Add-FoundryRelationship -SourceId $a -TargetId $a -Type X } 'itself'
  178. Assert-Throws { Add-FoundryRelationship -SourceId $a -TargetId 999999 -Type X } 'No knowledge entry'
  179. Assert-Throws { Add-FoundryRelationship -SourceId $a -TargetId $b -Type 'bad type' } 'Invalid relationship type'
  180. $ids.ga = $a; $ids.gd = $d
  181. }
  182. Invoke-Check 'search: -IncludeRelated adds graph neighbours of top results' {
  183. $r = Search-FoundryKnowledge -Query 'Graph A node a' -IncludeRelated -Limit 1
  184. Assert ($r.results[0].id -eq $ids.ga) "top was $($r.results[0].title)"
  185. Assert (@($r.related).Count -ge 2 -and ($r.related | Where-Object { $_.relationship -eq 'DEPENDS_ON' })) 'neighbours missing'
  186. }
  187. Invoke-Check 'supersede: old entry leaves search, SUPERSEDES edge recorded, self-supersede refused' {
  188. $old = Add-FoundryKnowledge -Title 'Old advice' -Content 'zebra-unique-token old guidance' -Type lesson-learned -Global
  189. $new = Add-FoundryKnowledge -Title 'New advice' -Content 'replacement guidance' -Type lesson-learned -Global
  190. $u = Update-FoundryKnowledge -Id $old.id -SupersededBy $new.id
  191. Assert ($u.status -eq 'superseded') 'status'
  192. Assert (-not (@((Search-FoundryKnowledge -Query 'zebra-unique-token').results) | Where-Object id -eq $old.id)) 'superseded entry still searchable'
  193. Assert ((Search-FoundryKnowledge -Query 'zebra-unique-token' -IncludeSuperseded).results[0].id -eq $old.id) '-IncludeSuperseded'
  194. $rel = Get-FoundryRelationships -Id $new.id -Direction Out -IncludeSuperseded
  195. Assert ($rel.related[0].id -eq $old.id -and $rel.related[0].relationship -eq 'SUPERSEDES') 'edge'
  196. Assert-Throws { Update-FoundryKnowledge -Id $new.id -SupersededBy $new.id } 'itself'
  197. }
  198. Invoke-Check 'token budget: results cut to budget, top result always kept, omitted reported' {
  199. 1..12 | ForEach-Object { $null = Add-FoundryKnowledge -Title "Budget entry $_" -Content ("budgetword filler text " * 60) -Type lesson-learned -Project qa-budget -Force }
  200. $big = Search-FoundryKnowledge -Query 'budgetword' -Project qa-budget -Limit 12 -MaxTokens 0
  201. Assert (@($big.results).Count -eq 12 -and $big.omittedForBudget -eq 0) 'unbudgeted should return all 12'
  202. $small = Search-FoundryKnowledge -Query 'budgetword' -Project qa-budget -Limit 12 -MaxTokens 600
  203. Assert (@($small.results).Count -ge 1 -and @($small.results).Count -lt 12) "budget not applied: $(@($small.results).Count) results"
  204. Assert ($small.estimatedTokens -le 600) "estimated $($small.estimatedTokens) > 600"
  205. Assert ($small.omittedForBudget -eq (12 - @($small.results).Count)) 'omitted count wrong'
  206. $tiny = Search-FoundryKnowledge -Query 'budgetword' -Project qa-budget -Limit 12 -MaxTokens 1
  207. Assert (@($tiny.results).Count -eq 1) 'top result must always be returned'
  208. Assert ($small.results[0].truncated -and $small.results[0].content.Length -le 503) 'content not truncated to ContentChars'
  209. "12 results = $($big.estimatedTokens) est. tokens; budget 600 -> $(@($small.results).Count) results, $($small.estimatedTokens) est. tokens"
  210. }
  211. Invoke-Check 'lessons and decisions: typed wrappers' {
  212. $l = Add-FoundryLesson -Title 'Quote paths' -Lesson 'Paths with spaces must be quoted.' -Project qa-one -Source 'tests/Run-FoundryTests.ps1' -Status verified -Confidence 0.9
  213. Assert ($l.type -eq 'lesson-learned' -and $l.status -eq 'verified') 'lesson'
  214. $dec = Add-FoundryDecision -Title 'Use cc65' -Decision 'Use cc65 for C.' -Rationale 'Verified starter exists.' -Alternatives 'KickC' -Project qa-one
  215. $g = Get-FoundryKnowledge -Id $dec.id
  216. Assert ($g.type -eq 'decision' -and $g.content -match 'Rationale: Verified' -and $g.content -match 'Alternatives considered: KickC') 'decision content'
  217. }
  218. Invoke-Check 'sessions: start, save (state merged), resume, complete, no-session message' {
  219. $s = Start-FoundrySession -Agent 'test-agent' -Objective 'Build the thing' -Project qa-one
  220. $null = Save-FoundrySession -Summary 'half done' -NextAction 'write tests' -State @{ a = 1 }
  221. $null = Save-FoundrySession -State @{ b = @('x', 'y') }
  222. $r = Resume-FoundrySession -Project qa-one
  223. Assert ($r.id -eq $s.id -and $r.summary -eq 'half done' -and $r.next_action -eq 'write tests') 'resume fields'
  224. Assert ($r.state.a -eq 1 -and @($r.state.b).Count -eq 2) 'state merge'
  225. $done = Save-FoundrySession -Complete
  226. Assert ([bool]$done.completed_at) 'completed_at'
  227. Assert-Throws { Save-FoundrySession -Id '00000000-0000-0000-0000-000000000000' -Summary 'x' } 'No session'
  228. Assert-Throws { Save-FoundrySession -Summary 'api_key = abcdef123456' } 'credential'
  229. $none = Resume-FoundrySession -Project qa-none 6>&1 | Out-String
  230. Assert ($none -match 'No earlier session') 'no-session message'
  231. }
  232. Invoke-Check 'backup and restore: round trip; restore refuses without -Force' {
  233. $file = Join-Path ([IO.Path]::GetTempPath()) "fke-test-$db.dump"
  234. try {
  235. $p = Backup-FoundryKnowledge -Path $file
  236. Assert ((Get-Item -LiteralPath $p).Length -gt 0) 'empty dump'
  237. $extra = Add-FoundryKnowledge -Title 'Added after backup' -Content 'should vanish on restore' -Type lesson-learned -Global -Force
  238. Assert-Throws { Restore-FoundryKnowledge -Path $p } '-Force'
  239. Restore-FoundryKnowledge -Path $p -Force 6>$null
  240. Assert-Throws { Get-FoundryKnowledge -Id $extra.id } 'No knowledge entry'
  241. $g = Get-FoundryKnowledge -Id $ids.tricky
  242. Assert ($g.title -match 'DROP TABLE') 'earlier data missing after restore'
  243. } finally { Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue }
  244. }
  245. Invoke-Check 'health: Test-FoundryKnowledge reports a stopped dependency instead of throwing' {
  246. $saved = $env:FOUNDRY_PG_CONTAINER
  247. $env:FOUNDRY_PG_CONTAINER = 'no-such-container'
  248. try {
  249. $t = Test-FoundryKnowledge
  250. Assert (-not $t.Ready) 'Ready should be false'
  251. Assert (($t.Checks | Where-Object { -not $_.ok }).Count -ge 1) 'no failing check reported'
  252. } finally { $env:FOUNDRY_PG_CONTAINER = $saved }
  253. }
  254. } finally {
  255. $env:FOUNDRY_PG_DATABASE = $savedDb
  256. $env:FOUNDRY_OLLAMA_URL = $savedOllama
  257. $env:FOUNDRY_PROJECT_KEY = $savedProject
  258. try { Invoke-AdminSql "DROP DATABASE IF EXISTS $db WITH (FORCE)" } catch { Write-Host "Could not drop scratch database ${db}: $_" -ForegroundColor Yellow }
  259. }
  260. $fail = @($script:Results | Where-Object Status -eq 'FAIL').Count
  261. $skip = @($script:Results | Where-Object Status -eq 'SKIP').Count
  262. Write-Host ("`n{0} checks: {1} passed, {2} failed, {3} skipped" -f $script:Results.Count, ($script:Results.Count - $fail - $skip), $fail, $skip)
  263. exit $(if ($fail) { 1 } else { 0 })

Powered by TurnKey Linux.