|
- <#
- .SYNOPSIS
- Automated checks for the Foundry Knowledge Engine (module, schema, search, graph, sessions, backup).
-
- .DESCRIPTION
- Runs against the real PostgreSQL container and the real Ollama embedding model, but in a scratch
- database ("foundry_test_<random>") that is created and dropped by the run. Your knowledge
- database is never touched. Needs: the foundry-postgres container running (scripts/Start-Foundry.ps1).
- Checks that need Ollama are skipped, with the reason, when the embedding model is unavailable.
- Uses the same check-runner style as tests/Run-FoundryTests.ps1 (Pester 5 is not required).
- Exit code 0 = no failures.
-
- .EXAMPLE
- pwsh -File tests/Knowledge.Tests.ps1
- #>
- [CmdletBinding()]
- param()
- $ErrorActionPreference = 'Stop'
- $root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
- Import-Module (Join-Path $root 'powershell/Foundry.Knowledge/Foundry.Knowledge.psd1') -Force
-
- $script:Results = [System.Collections.Generic.List[object]]::new()
- function Invoke-Check([string]$Name, [scriptblock]$Body) {
- try {
- $detail = & $Body
- $status = if ($detail -is [string] -and $detail.StartsWith('SKIP:')) { 'SKIP' } else { 'PASS' }
- $script:Results.Add([pscustomobject]@{ Name = $Name; Status = $status; Detail = "$detail" })
- } catch {
- $script:Results.Add([pscustomobject]@{ Name = $Name; Status = 'FAIL'; Detail = $_.Exception.Message })
- }
- $r = $script:Results[-1]
- $color = @{ PASS = 'Green'; FAIL = 'Red'; SKIP = 'Yellow' }[$r.Status]
- Write-Host ("[{0}] {1}{2}" -f $r.Status, $Name, $(if ($r.Detail) { " - $($r.Detail)" } else { '' })) -ForegroundColor $color
- }
- function Assert([bool]$Condition, [string]$Message) { if (-not $Condition) { throw $Message } }
- function Assert-Throws([scriptblock]$Body, [string]$Pattern) {
- try { & $Body } catch { if ($_.Exception.Message -match $Pattern) { return }; throw "Threw the wrong error: $($_.Exception.Message)" }
- throw "Expected an error matching '$Pattern' but nothing was thrown."
- }
- function Invoke-FkeSqlForTest([string]$Sql) { & (Get-Module Foundry.Knowledge) { param($s) Invoke-FkeSql -Sql $s } $Sql }
- function Invoke-AdminSql([string]$Sql) {
- $cfg = Get-Variable -Name cfg -Scope Script -ValueOnly
- $out = & docker exec $cfg.Container psql -U $cfg.User -d postgres -X -q -t -A -v ON_ERROR_STOP=1 -c $Sql 2>&1
- if ($LASTEXITCODE -ne 0) { throw "admin sql failed: $out" }
- }
-
- $h = Test-FoundryKnowledge
- if (-not $h.Ready) { Write-Host 'The knowledge database is not running. Run: pwsh -File scripts/Start-Foundry.ps1' -ForegroundColor Red; exit 1 }
- $embeddings = $h.EmbeddingsReady
- $script:cfg = [pscustomobject]@{ Container = 'foundry-postgres'; User = 'foundry' }
- $db = 'foundry_test_' + [Guid]::NewGuid().ToString('N').Substring(0, 8)
- $savedDb = $env:FOUNDRY_PG_DATABASE
- $savedOllama = $env:FOUNDRY_OLLAMA_URL
- $savedProject = $env:FOUNDRY_PROJECT_KEY
- $env:FOUNDRY_PROJECT_KEY = $null
- Invoke-AdminSql "CREATE DATABASE $db"
- $env:FOUNDRY_PG_DATABASE = $db
- $skipEmb = 'SKIP: Ollama or the embedding model is unavailable'
- $ids = @{}
- try {
- Invoke-Check 'migrations: apply to a fresh database, then re-run applies nothing' {
- $first = Update-FoundryDatabase 6>&1 | Out-String
- Assert ($first -match 'applied migration 001') "first run output: $first"
- $second = Update-FoundryDatabase 6>&1 | Out-String
- Assert (-not ($second -match 'applied migration')) "second run re-applied: $second"
- $t = Test-FoundryKnowledge
- Assert $t.Ready 'Test-FoundryKnowledge not Ready after migration'
- }
-
- Invoke-Check 'add/get: hostile text round-trips exactly (quotes, backslashes, $tags$, unicode, SQL)' {
- $title = "Tricky '; DROP TABLE knowledge.entries; -- `"q`" \ back"
- $content = "line1`nline2 with `$fke`$ and `$`$ and \n literal, unicode: caf$([char]0xE9) $([char]0x2192) $([char]0x4E2D)$([char]0x6587), 100% & <tag>"
- $r = Add-FoundryKnowledge -Title $title -Content $content -Type technical-fact -Project qa-one -Force
- Assert $r.created 'not created'
- $g = Get-FoundryKnowledge -Id $r.id
- Assert ($g.title -ceq $title) "title changed: $($g.title)"
- Assert ($g.content -ceq $content) "content changed: $($g.content)"
- Assert ($g.project -eq 'qa-one' -and $g.status -eq 'unverified' -and $g.confidence -eq 0.5) 'defaults wrong'
- $ids.tricky = $r.id
- "id $($r.id), embedded=$($r.embedded)"
- }
-
- Invoke-Check 'domain rules: secrets, verified-needs-source, unknown type, blank, bad project key' {
- Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'password = hunter2hunter2' -Type lesson-learned -Force } 'credential'
- Assert-Throws { Add-FoundryKnowledge -Title 't' -Content '-----BEGIN RSA PRIVATE KEY-----' -Type lesson-learned -Force } 'credential'
- Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'conn postgres://u:p4ssw0rd@host/db' -Type lesson-learned -Force } 'credential'
- Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'fine' -Type lesson-learned -Status verified -Force } 'needs a Source'
- Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'fine' -Type nonsense -Force } 'Unknown knowledge type'
- Assert-Throws { Add-FoundryKnowledge -Title ' ' -Content 'fine' -Type lesson-learned -Force } 'blank'
- Assert-Throws { Add-FoundryKnowledge -Title 't' -Content 'fine' -Type lesson-learned -Project 'Bad Key' -Force } 'Invalid project key'
- $n = Invoke-FkeSqlForTest "SELECT count(*) FROM knowledge.entries"
- Assert ($n -eq 1) "rejected entries were stored (count $n)"
- }
-
- Invoke-Check 'dedup: same title is refused; -Force stores; different project scope is allowed' {
- $a = Add-FoundryKnowledge -Title 'C128 memory banking' -Content 'The MMU at $D500 selects banks.' -Type technical-fact -Global
- Assert $a.created 'first not created'
- $b = Add-FoundryKnowledge -Title ' c128 MEMORY banking ' -Content 'Entirely different words here.' -Type technical-fact -Global
- Assert (-not $b.created -and $b.duplicateOf -eq $a.id) 'duplicate title not detected'
- $c = Add-FoundryKnowledge -Title 'C128 memory banking' -Content 'x' -Type technical-fact -Project qa-two
- Assert $c.created 'same title in another project scope should be allowed'
- $d = Add-FoundryKnowledge -Title 'C128 memory banking' -Content 'forced copy' -Type technical-fact -Global -Force
- Assert $d.created '-Force did not store'
- $ids.banking = $a.id; $ids.bankingOther = $c.id
- }
-
- Invoke-Check 'dedup: near-identical content under a different title is caught by embedding similarity' {
- if (-not $embeddings) { return $skipEmb }
- $text = 'Controllers should not contain business rules; put them in a service layer.'
- $a = Add-FoundryKnowledge -Title 'MVC separation' -Content $text -Type technical-fact -Project qa-one
- $b = Add-FoundryKnowledge -Title 'Keep controllers thin' -Content $text -Type technical-fact -Project qa-one
- Assert (-not $b.created -and $b.duplicateOf -eq $a.id -and $b.similarity -ge 0.80) "not caught: $($b | ConvertTo-Json -Compress)"
- $ids.mvc = $a.id
- "similarity $($b.similarity)"
- }
-
- Invoke-Check 'search: semantic match without shared keywords' {
- if (-not $embeddings) { return $skipEmb }
- $null = Add-FoundryKnowledge -Title 'SID voice registers' -Content 'The SID chip has three voices with ADSR envelopes.' -Type technical-fact -Global
- $null = Add-FoundryKnowledge -Title 'VICE headless smoke test' -Content 'Run the emulator without a window and compare a screenshot.' -Type procedure -Global
- $r = Search-FoundryKnowledge -Query 'How should I separate presentation from domain logic?' -Project qa-one -Limit 3
- Assert ($r.mode -eq 'hybrid') "mode $($r.mode)"
- Assert ($r.results[0].id -eq $ids.mvc) "top hit was '$($r.results[0].title)', expected the MVC entry"
- $words = 'separate', 'presentation', 'domain', 'logic'
- Assert (-not ($words | Where-Object { $r.results[0].content -match $_ })) 'test premise broken: keywords overlap'
- "top similarity $($r.results[0].similarity), score $($r.results[0].score)"
- }
-
- Invoke-Check 'search: keyword fallback when Ollama is unreachable' {
- $env:FOUNDRY_OLLAMA_URL = 'http://127.0.0.1:9'
- try {
- $r = Search-FoundryKnowledge -Query 'MMU selects banks' -WarningAction SilentlyContinue
- Assert ($r.mode -eq 'keyword-only') "mode $($r.mode)"
- Assert (@($r.results).Count -ge 1 -and $r.results[0].title -match 'memory banking') 'keyword search did not find the entry'
- $w = Add-FoundryKnowledge -Title 'Stored offline' -Content 'saved while Ollama was down' -Type lesson-learned -Global -WarningAction SilentlyContinue
- Assert ($w.created -and -not $w.embedded) 'offline add should store without embedding'
- } finally { $env:FOUNDRY_OLLAMA_URL = $savedOllama }
- }
-
- Invoke-Check 'search: project scope returns project + global, never another project' {
- $r = Search-FoundryKnowledge -Query 'C128 memory banking' -Project qa-one -Limit 10
- Assert (-not ($r.results | Where-Object { $_.project -eq 'qa-two' })) 'leaked qa-two entry into qa-one'
- Assert (@($r.results | Where-Object { -not $_.project }).Count -gt 0) 'global entry missing'
- $env:FOUNDRY_PROJECT_KEY = 'qa-two'
- try { Assert ((Get-FoundryProjectContext) -eq 'qa-two') 'env project not used' } finally { $env:FOUNDRY_PROJECT_KEY = $null }
- }
-
- Invoke-Check 'search: -VerifiedOnly, -Type and update (status, tags, metadata merge, re-embed)' {
- $before = Search-FoundryKnowledge -Query 'MMU selects banks' -VerifiedOnly
- Assert (@($before.results).Count -eq 0) 'unverified entry returned with -VerifiedOnly'
- $u = Update-FoundryKnowledge -Id $ids.banking -Status verified -Source 'C128 Programmer''s Reference Guide' -Confidence 0.95 -Tags 'c128', 'mmu' -Metadata @{ a = 1 }
- $u = Update-FoundryKnowledge -Id $ids.banking -Metadata @{ b = 2 } -Content 'The MMU at $D500 selects banks; $FF00 is the configuration register.'
- $g = Get-FoundryKnowledge -Id $ids.banking
- Assert ($g.status -eq 'verified' -and $g.confidence -eq 0.95) 'status/confidence not updated'
- Assert (($g.tags -join ',') -eq 'c128,mmu') 'tags not updated'
- Assert ($g.metadata.a -eq 1 -and $g.metadata.b -eq 2) 'metadata not merged'
- Assert ($g.content -match 'FF00') 'content not updated'
- $after = Search-FoundryKnowledge -Query 'MMU selects banks' -VerifiedOnly
- Assert (@($after.results).Count -eq 1 -and $after.results[0].id -eq $ids.banking) 'verified entry not found'
- $typed = Search-FoundryKnowledge -Query 'MMU banks' -Type procedure
- Assert (-not ($typed.results | Where-Object { $_.type -ne 'procedure' })) '-Type filter ignored'
- Assert-Throws { Update-FoundryKnowledge -Id $ids.banking -Content 'password = abcdef123456' } 'credential'
- Assert-Throws { Update-FoundryKnowledge -Id 999999 -Title 'x' } 'No knowledge entry'
- }
-
- Invoke-Check 'graph: edges, idempotence, cycle-safe traversal, direction, depth' {
- $a = (Add-FoundryKnowledge -Title 'Graph A' -Content 'node a' -Type technical-fact -Global -Force).id
- $b = (Add-FoundryKnowledge -Title 'Graph B' -Content 'node b' -Type technical-fact -Global -Force).id
- $c = (Add-FoundryKnowledge -Title 'Graph C' -Content 'node c' -Type technical-fact -Global -Force).id
- $d = (Add-FoundryKnowledge -Title 'Graph D' -Content 'node d' -Type technical-fact -Global -Force).id
- $e1 = Add-FoundryRelationship -SourceId $a -TargetId $b -Type depends_on
- Assert ($e1.created -and $e1.relationship_type -eq 'DEPENDS_ON') 'edge 1'
- $again = Add-FoundryRelationship -SourceId $a -TargetId $b -Type DEPENDS_ON
- Assert (-not $again.created -and $again.id -eq $e1.id) 'duplicate edge should report created=false with the same id'
- $null = Add-FoundryRelationship -SourceId $b -TargetId $c -Type RELATED_TO
- $null = Add-FoundryRelationship -SourceId $c -TargetId $a -Type RELATED_TO # cycle a>b>c>a
- $null = Add-FoundryRelationship -SourceId $c -TargetId $d -Type SOLVES
- $d1 = Get-FoundryRelationships -Id $a -Depth 1
- Assert ((@($d1.related.id | Sort-Object) -join ',') -eq (@($b, $c | Sort-Object) -join ',')) "depth 1 (both): $($d1.related.id -join ',')"
- $d3 = Get-FoundryRelationships -Id $a -Depth 3
- $got = @($d3.related.id | Sort-Object)
- 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"
- Assert (($d3.related | Where-Object id -eq $d).depth -eq 2) 'd should be at depth 2 via c'
- $out = Get-FoundryRelationships -Id $a -Depth 3 -Direction Out
- Assert (@($out.related.id).Count -eq 3) "out traversal: $($out.related.id -join ',')"
- $in = Get-FoundryRelationships -Id $d -Depth 1 -Direction In
- Assert (@($in.related).Count -eq 1 -and $in.related[0].id -eq $c -and $in.related[0].relationship -eq 'SOLVES') 'in traversal'
- $typed = Get-FoundryRelationships -Id $a -Depth 3 -Type DEPENDS_ON
- Assert (@($typed.related).Count -eq 1) 'type filter'
- Assert-Throws { Add-FoundryRelationship -SourceId $a -TargetId $a -Type X } 'itself'
- Assert-Throws { Add-FoundryRelationship -SourceId $a -TargetId 999999 -Type X } 'No knowledge entry'
- Assert-Throws { Add-FoundryRelationship -SourceId $a -TargetId $b -Type 'bad type' } 'Invalid relationship type'
- $ids.ga = $a; $ids.gd = $d
- }
-
- Invoke-Check 'search: -IncludeRelated adds graph neighbours of top results' {
- $r = Search-FoundryKnowledge -Query 'Graph A node a' -IncludeRelated -Limit 1
- Assert ($r.results[0].id -eq $ids.ga) "top was $($r.results[0].title)"
- Assert (@($r.related).Count -ge 2 -and ($r.related | Where-Object { $_.relationship -eq 'DEPENDS_ON' })) 'neighbours missing'
- }
-
- Invoke-Check 'supersede: old entry leaves search, SUPERSEDES edge recorded, self-supersede refused' {
- $old = Add-FoundryKnowledge -Title 'Old advice' -Content 'zebra-unique-token old guidance' -Type lesson-learned -Global
- $new = Add-FoundryKnowledge -Title 'New advice' -Content 'replacement guidance' -Type lesson-learned -Global
- $u = Update-FoundryKnowledge -Id $old.id -SupersededBy $new.id
- Assert ($u.status -eq 'superseded') 'status'
- Assert (-not (@((Search-FoundryKnowledge -Query 'zebra-unique-token').results) | Where-Object id -eq $old.id)) 'superseded entry still searchable'
- Assert ((Search-FoundryKnowledge -Query 'zebra-unique-token' -IncludeSuperseded).results[0].id -eq $old.id) '-IncludeSuperseded'
- $rel = Get-FoundryRelationships -Id $new.id -Direction Out -IncludeSuperseded
- Assert ($rel.related[0].id -eq $old.id -and $rel.related[0].relationship -eq 'SUPERSEDES') 'edge'
- Assert-Throws { Update-FoundryKnowledge -Id $new.id -SupersededBy $new.id } 'itself'
- }
-
- Invoke-Check 'token budget: results cut to budget, top result always kept, omitted reported' {
- 1..12 | ForEach-Object { $null = Add-FoundryKnowledge -Title "Budget entry $_" -Content ("budgetword filler text " * 60) -Type lesson-learned -Project qa-budget -Force }
- $big = Search-FoundryKnowledge -Query 'budgetword' -Project qa-budget -Limit 12 -MaxTokens 0
- Assert (@($big.results).Count -eq 12 -and $big.omittedForBudget -eq 0) 'unbudgeted should return all 12'
- $small = Search-FoundryKnowledge -Query 'budgetword' -Project qa-budget -Limit 12 -MaxTokens 600
- Assert (@($small.results).Count -ge 1 -and @($small.results).Count -lt 12) "budget not applied: $(@($small.results).Count) results"
- Assert ($small.estimatedTokens -le 600) "estimated $($small.estimatedTokens) > 600"
- Assert ($small.omittedForBudget -eq (12 - @($small.results).Count)) 'omitted count wrong'
- $tiny = Search-FoundryKnowledge -Query 'budgetword' -Project qa-budget -Limit 12 -MaxTokens 1
- Assert (@($tiny.results).Count -eq 1) 'top result must always be returned'
- Assert ($small.results[0].truncated -and $small.results[0].content.Length -le 503) 'content not truncated to ContentChars'
- "12 results = $($big.estimatedTokens) est. tokens; budget 600 -> $(@($small.results).Count) results, $($small.estimatedTokens) est. tokens"
- }
-
- Invoke-Check 'lessons and decisions: typed wrappers' {
- $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
- Assert ($l.type -eq 'lesson-learned' -and $l.status -eq 'verified') 'lesson'
- $dec = Add-FoundryDecision -Title 'Use cc65' -Decision 'Use cc65 for C.' -Rationale 'Verified starter exists.' -Alternatives 'KickC' -Project qa-one
- $g = Get-FoundryKnowledge -Id $dec.id
- Assert ($g.type -eq 'decision' -and $g.content -match 'Rationale: Verified' -and $g.content -match 'Alternatives considered: KickC') 'decision content'
- }
-
- Invoke-Check 'sessions: start, save (state merged), resume, complete, no-session message' {
- $s = Start-FoundrySession -Agent 'test-agent' -Objective 'Build the thing' -Project qa-one
- $null = Save-FoundrySession -Summary 'half done' -NextAction 'write tests' -State @{ a = 1 }
- $null = Save-FoundrySession -State @{ b = @('x', 'y') }
- $r = Resume-FoundrySession -Project qa-one
- Assert ($r.id -eq $s.id -and $r.summary -eq 'half done' -and $r.next_action -eq 'write tests') 'resume fields'
- Assert ($r.state.a -eq 1 -and @($r.state.b).Count -eq 2) 'state merge'
- $done = Save-FoundrySession -Complete
- Assert ([bool]$done.completed_at) 'completed_at'
- Assert-Throws { Save-FoundrySession -Id '00000000-0000-0000-0000-000000000000' -Summary 'x' } 'No session'
- Assert-Throws { Save-FoundrySession -Summary 'api_key = abcdef123456' } 'credential'
- $none = Resume-FoundrySession -Project qa-none 6>&1 | Out-String
- Assert ($none -match 'No earlier session') 'no-session message'
- }
-
- Invoke-Check 'backup and restore: round trip; restore refuses without -Force' {
- $file = Join-Path ([IO.Path]::GetTempPath()) "fke-test-$db.dump"
- try {
- $p = Backup-FoundryKnowledge -Path $file
- Assert ((Get-Item -LiteralPath $p).Length -gt 0) 'empty dump'
- $extra = Add-FoundryKnowledge -Title 'Added after backup' -Content 'should vanish on restore' -Type lesson-learned -Global -Force
- Assert-Throws { Restore-FoundryKnowledge -Path $p } '-Force'
- Restore-FoundryKnowledge -Path $p -Force 6>$null
- Assert-Throws { Get-FoundryKnowledge -Id $extra.id } 'No knowledge entry'
- $g = Get-FoundryKnowledge -Id $ids.tricky
- Assert ($g.title -match 'DROP TABLE') 'earlier data missing after restore'
- } finally { Remove-Item -LiteralPath $file -Force -ErrorAction SilentlyContinue }
- }
-
- Invoke-Check 'health: Test-FoundryKnowledge reports a stopped dependency instead of throwing' {
- $saved = $env:FOUNDRY_PG_CONTAINER
- $env:FOUNDRY_PG_CONTAINER = 'no-such-container'
- try {
- $t = Test-FoundryKnowledge
- Assert (-not $t.Ready) 'Ready should be false'
- Assert (($t.Checks | Where-Object { -not $_.ok }).Count -ge 1) 'no failing check reported'
- } finally { $env:FOUNDRY_PG_CONTAINER = $saved }
- }
- } finally {
- $env:FOUNDRY_PG_DATABASE = $savedDb
- $env:FOUNDRY_OLLAMA_URL = $savedOllama
- $env:FOUNDRY_PROJECT_KEY = $savedProject
- try { Invoke-AdminSql "DROP DATABASE IF EXISTS $db WITH (FORCE)" } catch { Write-Host "Could not drop scratch database ${db}: $_" -ForegroundColor Yellow }
- }
-
- $fail = @($script:Results | Where-Object Status -eq 'FAIL').Count
- $skip = @($script:Results | Where-Object Status -eq 'SKIP').Count
- Write-Host ("`n{0} checks: {1} passed, {2} failed, {3} skipped" -f $script:Results.Count, ($script:Results.Count - $fail - $skip), $fail, $skip)
- exit $(if ($fail) { 1 } else { 0 })
|