You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

344 lines
18KB

  1. # Knowledge entries: add, get, update, hybrid search, lessons and decisions.
  2. $script:FkeEntryColumns = 'e.id, e.title, e.knowledge_type AS type, e.project_key AS project, e.status, e.confidence, e.source, e.tags, e.created_at, e.updated_at'
  3. function Out-FkeResult($Object, [switch]$AsJson, [int]$Depth = 8) {
  4. if ($AsJson) { $Object | ConvertTo-Json -Depth $Depth -Compress } else { $Object }
  5. }
  6. function Set-FoundryProjectContext {
  7. <# .SYNOPSIS Set the default project key for this session (project entries; global entries stay visible). #>
  8. [CmdletBinding()] param([Parameter(Mandatory)][string]$Project)
  9. $null = Resolve-FkeProject -Project $Project
  10. $script:DefaultProject = $Project
  11. }
  12. function Get-FoundryProjectContext {
  13. <# .SYNOPSIS Show the project key commands will use when -Project is not given. #>
  14. [CmdletBinding()] param()
  15. Resolve-FkeProject
  16. }
  17. function Add-FoundryKnowledge {
  18. <#
  19. .SYNOPSIS Store a piece of knowledge, unless a duplicate already exists.
  20. .DESCRIPTION
  21. Without -Project (and with no project context) or with -Global the entry is global and visible
  22. to every project. Duplicate = same title, or embedding similarity >= -DuplicateThreshold,
  23. within the same project scope. A duplicate is not stored; the existing id is returned so you
  24. can Update-FoundryKnowledge it instead. -Force stores anyway.
  25. If Ollama is unavailable the entry is stored without an embedding (keyword search still finds
  26. it) and a warning says so.
  27. #>
  28. [CmdletBinding()]
  29. param(
  30. [Parameter(Mandatory)][string]$Title,
  31. [Parameter(Mandatory)][string]$Content,
  32. [Parameter(Mandatory)][string]$Type,
  33. [string]$Project,
  34. [switch]$Global,
  35. [string]$Source,
  36. [string[]]$Tags = @(),
  37. [ValidateRange(0, 1)][double]$Confidence = 0.5,
  38. [ValidateSet('unverified', 'verified')][string]$Status = 'unverified',
  39. [hashtable]$Metadata = @{},
  40. [ValidateRange(0, 1)][double]$DuplicateThreshold = 0.80,
  41. [switch]$Force,
  42. [switch]$AsJson
  43. )
  44. Assert-FkeEntryRules -Title $Title -Content $Content -Type $Type -Status $Status -Source $Source
  45. $proj = Resolve-FkeProject -Project $Project -Global:$Global
  46. $payload = @{
  47. title = $Title.Trim(); content = $Content; type = $Type; project = $proj; source = $Source
  48. tags = [string[]]@($Tags); confidence = $Confidence; status = $Status; metadata = $Metadata
  49. threshold = $DuplicateThreshold
  50. }
  51. try {
  52. $payload.embedding = Get-FkeEmbedding -Text "$($payload.title)`n$Content"
  53. $payload.embeddingModel = (Get-FkeConfig).EmbeddingModel
  54. } catch {
  55. Write-Warning "Stored without an embedding (semantic search will not find it until it is re-embedded): $($_.Exception.Message)"
  56. }
  57. if (-not $Force) {
  58. $dup = @(Invoke-FkeSql -Payload $payload -Sql @'
  59. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j)
  60. SELECT COALESCE(jsonb_agg(d), '[]'::jsonb) FROM (
  61. SELECT e.id, e.title,
  62. CASE WHEN p.j ? 'embedding' AND e.embedding IS NOT NULL
  63. THEN ROUND((1 - (e.embedding <=> (p.j->'embedding')::text::vector))::numeric, 3) END AS similarity,
  64. (lower(btrim(e.title)) = lower(btrim(p.j->>'title'))) AS same_title
  65. FROM knowledge.entries e, p
  66. WHERE e.status <> 'superseded'
  67. AND e.project_key IS NOT DISTINCT FROM NULLIF(p.j->>'project', '')
  68. AND ( lower(btrim(e.title)) = lower(btrim(p.j->>'title'))
  69. OR (p.j ? 'embedding' AND e.embedding IS NOT NULL
  70. AND 1 - (e.embedding <=> (p.j->'embedding')::text::vector) >= (p.j->>'threshold')::float8) )
  71. ORDER BY 3 DESC NULLS LAST, e.id LIMIT 3) d;
  72. '@)
  73. if ($dup.Count) {
  74. $top = $dup[0]
  75. $why = if ($top.same_title) { 'an entry with the same title exists' } else { "an entry is $($top.similarity) similar (threshold $DuplicateThreshold)" }
  76. return Out-FkeResult ([pscustomobject]@{
  77. created = $false; duplicateOf = $top.id; duplicateTitle = $top.title; similarity = $top.similarity
  78. reason = "Not stored: $why. Use Update-FoundryKnowledge -Id $($top.id), or -Force to store anyway."
  79. candidates = $dup
  80. }) -AsJson:$AsJson
  81. }
  82. }
  83. $row = Invoke-FkeSql -Payload $payload -Sql @'
  84. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j),
  85. ins AS (
  86. INSERT INTO knowledge.entries (title, content, knowledge_type, project_key, source, tags, confidence, status, metadata, embedding, embedding_model)
  87. SELECT p.j->>'title', p.j->>'content', p.j->>'type', NULLIF(p.j->>'project', ''), NULLIF(p.j->>'source', ''),
  88. ARRAY(SELECT jsonb_array_elements_text(p.j->'tags')), (p.j->>'confidence')::numeric, p.j->>'status',
  89. COALESCE(p.j->'metadata', '{}'::jsonb),
  90. CASE WHEN p.j ? 'embedding' THEN (p.j->'embedding')::text::vector END, p.j->>'embeddingModel'
  91. FROM p
  92. RETURNING id, title, knowledge_type AS type, project_key AS project, status, confidence, (embedding IS NOT NULL) AS embedded)
  93. SELECT to_jsonb(ins) FROM ins;
  94. '@
  95. $row | Add-Member -NotePropertyName created -NotePropertyValue $true -PassThru | ForEach-Object { Out-FkeResult $_ -AsJson:$AsJson }
  96. }
  97. function Get-FoundryKnowledge {
  98. <# .SYNOPSIS Fetch one entry in full (without the embedding vector). #>
  99. [CmdletBinding()]
  100. param([Parameter(Mandatory)][long]$Id, [switch]$AsJson)
  101. $row = Invoke-FkeSql -Payload @{ id = $Id } -Sql @"
  102. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j)
  103. SELECT to_jsonb(r) FROM (
  104. SELECT $script:FkeEntryColumns, e.content, e.metadata, e.embedding_model, (e.embedding IS NOT NULL) AS embedded,
  105. (SELECT count(*) FROM knowledge.relationships r WHERE r.source_id = e.id OR r.target_id = e.id) AS relationship_count
  106. FROM knowledge.entries e, p WHERE e.id = (p.j->>'id')::bigint) r;
  107. "@
  108. if (-not $row) { throw "No knowledge entry with id $Id." }
  109. Out-FkeResult $row -AsJson:$AsJson
  110. }
  111. function Update-FoundryKnowledge {
  112. <#
  113. .SYNOPSIS Correct an entry, or supersede it with a newer one.
  114. .DESCRIPTION
  115. Only the parameters you pass change. Changing Title or Content re-embeds. -Metadata is merged
  116. into the existing metadata. -SupersededBy <newId> marks this entry 'superseded' (it stops
  117. appearing in searches) and records (new)-[SUPERSEDES]->(old).
  118. #>
  119. [CmdletBinding()]
  120. param(
  121. [Parameter(Mandatory)][long]$Id,
  122. [string]$Title, [string]$Content, [string]$Type, [string]$Source,
  123. [string[]]$Tags,
  124. [ValidateRange(0, 1)][double]$Confidence,
  125. [ValidateSet('unverified', 'verified')][string]$Status,
  126. [hashtable]$Metadata,
  127. [long]$SupersededBy,
  128. [switch]$AsJson
  129. )
  130. $current = Get-FoundryKnowledge -Id $Id
  131. $effStatus = if ($PSBoundParameters.ContainsKey('Status')) { $Status } else { $current.status }
  132. $effSource = if ($PSBoundParameters.ContainsKey('Source')) { $Source } else { $current.source }
  133. $rules = @{ Partial = $true }
  134. foreach ($k in 'Title', 'Content', 'Type', 'Source') { if ($PSBoundParameters.ContainsKey($k)) { $rules[$k] = $PSBoundParameters[$k] } }
  135. if ($effStatus -eq 'verified') { $rules.Status = 'verified'; $rules.Source = $effSource }
  136. Assert-FkeEntryRules @rules
  137. $payload = @{ id = $Id }
  138. $map = @{ Title = 'title'; Content = 'content'; Type = 'type'; Source = 'source'; Confidence = 'confidence'; Status = 'status' }
  139. foreach ($k in $map.Keys) { if ($PSBoundParameters.ContainsKey($k)) { $payload[$map[$k]] = $PSBoundParameters[$k] } }
  140. if ($PSBoundParameters.ContainsKey('Tags')) { $payload.tags = [string[]]@($Tags) }
  141. if ($PSBoundParameters.ContainsKey('Metadata')) { $payload.metadata = $Metadata }
  142. if ($PSBoundParameters.ContainsKey('Title') -or $PSBoundParameters.ContainsKey('Content')) {
  143. $t = if ($payload.title) { $payload.title } else { $current.title }
  144. $c = if ($payload.content) { $payload.content } else { $current.content }
  145. try {
  146. $payload.embedding = Get-FkeEmbedding -Text "$t`n$c"
  147. $payload.embeddingModel = (Get-FkeConfig).EmbeddingModel
  148. } catch { Write-Warning "Re-embedding failed; the old embedding is kept and may be stale: $($_.Exception.Message)" }
  149. }
  150. if ($PSBoundParameters.ContainsKey('SupersededBy')) {
  151. if ($SupersededBy -eq $Id) { throw 'An entry cannot supersede itself.' }
  152. $null = Get-FoundryKnowledge -Id $SupersededBy
  153. $payload.supersededBy = $SupersededBy
  154. $payload.status = 'superseded'
  155. }
  156. $sql = @'
  157. BEGIN;
  158. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j)
  159. UPDATE knowledge.entries e SET
  160. title = COALESCE(p.j->>'title', e.title),
  161. content = COALESCE(p.j->>'content', e.content),
  162. knowledge_type = COALESCE(p.j->>'type', e.knowledge_type),
  163. source = CASE WHEN p.j ? 'source' THEN NULLIF(p.j->>'source', '') ELSE e.source END,
  164. tags = CASE WHEN p.j ? 'tags' THEN ARRAY(SELECT jsonb_array_elements_text(p.j->'tags')) ELSE e.tags END,
  165. confidence = COALESCE((p.j->>'confidence')::numeric, e.confidence),
  166. status = COALESCE(p.j->>'status', e.status),
  167. metadata = CASE WHEN p.j ? 'metadata' THEN e.metadata || (p.j->'metadata') ELSE e.metadata END,
  168. embedding = CASE WHEN p.j ? 'embedding' THEN (p.j->'embedding')::text::vector ELSE e.embedding END,
  169. embedding_model = CASE WHEN p.j ? 'embedding' THEN p.j->>'embeddingModel' ELSE e.embedding_model END,
  170. updated_at = NOW()
  171. FROM p WHERE e.id = (p.j->>'id')::bigint;
  172. INSERT INTO knowledge.relationships (source_id, target_id, relationship_type)
  173. SELECT (j->>'supersededBy')::bigint, (j->>'id')::bigint, 'SUPERSEDES'
  174. FROM (SELECT current_setting('fke.p')::jsonb AS j) p WHERE p.j ? 'supersededBy'
  175. ON CONFLICT DO NOTHING;
  176. COMMIT;
  177. SELECT to_jsonb(r) FROM (SELECT e.id, e.title, e.knowledge_type AS type, e.status, e.confidence, e.updated_at FROM knowledge.entries e WHERE e.id = (current_setting('fke.p')::jsonb->>'id')::bigint) r;
  178. '@
  179. Out-FkeResult (Invoke-FkeSql -Payload $payload -Sql $sql) -AsJson:$AsJson
  180. }
  181. function Search-FoundryKnowledge {
  182. <#
  183. .SYNOPSIS Hybrid search (vector + keyword), ranked, graph-expanded and cut to a token budget.
  184. .DESCRIPTION
  185. Ranking: reciprocal-rank fusion (k=60) of the semantic and keyword rankings, scaled by
  186. (0.5 + 0.5 x confidence); ties go to the more recently updated entry. Superseded entries are
  187. excluded unless -IncludeSuperseded. With a project (parameter, FOUNDRY_PROJECT_KEY or
  188. Set-FoundryProjectContext) results are that project's plus global entries.
  189. -IncludeRelated adds graph neighbours (one hop) of the top results, as id/title/relationship
  190. only. -MaxTokens bounds the response using a ~4-characters-per-token estimate; the top result
  191. is always returned. Long content is cut to -ContentChars; use Get-FoundryKnowledge for all of it.
  192. If Ollama is unavailable the search degrades to keyword-only and says so in 'mode'.
  193. #>
  194. [CmdletBinding()]
  195. param(
  196. [Parameter(Mandatory)][string]$Query,
  197. [string]$Project,
  198. [string]$Type,
  199. [ValidateRange(1, 50)][int]$Limit = 5,
  200. [ValidateRange(0, 1000000)][int]$MaxTokens = 3000,
  201. [ValidateRange(50, 100000)][int]$ContentChars = 500,
  202. [ValidateRange(-1, 1)][double]$MinSimilarity = 0,
  203. [switch]$IncludeRelated,
  204. [switch]$VerifiedOnly,
  205. [switch]$IncludeSuperseded,
  206. [switch]$AsJson
  207. )
  208. $proj = Resolve-FkeProject -Project $Project
  209. $words = [regex]::Matches($Query.ToLowerInvariant(), '[a-z0-9]{2,}') | ForEach-Object Value | Select-Object -Unique
  210. $payload = @{
  211. project = $proj; type = $Type; verifiedOnly = [bool]$VerifiedOnly; includeSuperseded = [bool]$IncludeSuperseded
  212. tsquery = ($words -join ' | '); candidates = $Limit * 4; minSimilarity = $MinSimilarity; limit = $Limit
  213. }
  214. $mode = 'hybrid'
  215. try { $payload.embedding = Get-FkeEmbedding -Text $Query }
  216. catch { $mode = 'keyword-only'; Write-Warning "Semantic search unavailable, using keyword search only: $($_.Exception.Message)" }
  217. $rows = @(Invoke-FkeSql -Payload $payload -Sql @'
  218. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j),
  219. cfg AS (
  220. SELECT NULLIF(j->>'project', '') AS project, NULLIF(j->>'type', '') AS type,
  221. (j->>'verifiedOnly')::boolean AS verified_only, (j->>'includeSuperseded')::boolean AS incl_sup,
  222. NULLIF(j->>'tsquery', '') AS tsq_text,
  223. CASE WHEN j ? 'embedding' THEN (j->'embedding')::text::vector END AS emb,
  224. (j->>'candidates')::int AS cand, (j->>'minSimilarity')::float8 AS min_sim, (j->>'limit')::int AS lim
  225. FROM p),
  226. eligible AS (
  227. SELECT e.* FROM knowledge.entries e, cfg
  228. WHERE (cfg.incl_sup OR e.status <> 'superseded')
  229. AND (NOT cfg.verified_only OR e.status = 'verified')
  230. AND (cfg.type IS NULL OR e.knowledge_type = cfg.type)
  231. AND (cfg.project IS NULL OR e.project_key = cfg.project OR e.project_key IS NULL)),
  232. vec AS (
  233. SELECT e.id, 1 - (e.embedding <=> cfg.emb) AS sim,
  234. ROW_NUMBER() OVER (ORDER BY e.embedding <=> cfg.emb) AS rk
  235. FROM eligible e, cfg
  236. WHERE cfg.emb IS NOT NULL AND e.embedding IS NOT NULL AND 1 - (e.embedding <=> cfg.emb) >= cfg.min_sim
  237. ORDER BY e.embedding <=> cfg.emb LIMIT (SELECT cand FROM cfg)),
  238. fts AS (
  239. SELECT e.id, ts_rank_cd(e.search_vector, q.tsq) AS rnk,
  240. ROW_NUMBER() OVER (ORDER BY ts_rank_cd(e.search_vector, q.tsq) DESC) AS rk
  241. FROM eligible e, (SELECT to_tsquery('english', cfg.tsq_text) AS tsq FROM cfg WHERE cfg.tsq_text IS NOT NULL) q
  242. WHERE e.search_vector @@ q.tsq
  243. ORDER BY rnk DESC LIMIT (SELECT cand FROM cfg)),
  244. fused AS (
  245. SELECT COALESCE(v.id, f.id) AS id, v.sim,
  246. COALESCE(1.0 / (60 + v.rk), 0) + COALESCE(1.0 / (60 + f.rk), 0) AS rrf
  247. FROM vec v FULL JOIN fts f ON f.id = v.id)
  248. SELECT COALESCE(jsonb_agg(r ORDER BY r.score DESC, r.updated_at DESC), '[]'::jsonb) FROM (
  249. SELECT e.id, e.title, e.knowledge_type AS type, e.project_key AS project, e.status, e.confidence, e.source, e.tags,
  250. e.updated_at, e.content,
  251. ROUND((fz.rrf * (0.5 + 0.5 * e.confidence))::numeric, 5) AS score,
  252. ROUND(fz.sim::numeric, 3) AS similarity
  253. FROM fused fz JOIN knowledge.entries e ON e.id = fz.id
  254. ORDER BY score DESC, e.updated_at DESC LIMIT (SELECT lim FROM cfg)) r;
  255. '@)
  256. $included = [System.Collections.Generic.List[object]]::new()
  257. $used = 0; $omitted = 0
  258. foreach ($row in $rows) {
  259. $truncated = $row.content.Length -gt $ContentChars
  260. $item = [ordered]@{
  261. id = $row.id; title = $row.title; type = $row.type; project = $row.project; status = $row.status
  262. confidence = $row.confidence; score = $row.score; similarity = $row.similarity; source = $row.source
  263. content = if ($truncated) { $row.content.Substring(0, $ContentChars) + '...' } else { $row.content }
  264. truncated = $truncated
  265. }
  266. $cost = Get-FkeTokenEstimate ($item | ConvertTo-Json -Compress)
  267. if ($MaxTokens -gt 0 -and $included.Count -gt 0 -and ($used + $cost) -gt $MaxTokens) { $omitted++; continue }
  268. $included.Add([pscustomobject]$item); $used += $cost
  269. }
  270. $related = @()
  271. if ($IncludeRelated -and $included.Count) {
  272. $top = @($included | Select-Object -First 5 | ForEach-Object { $_.id })
  273. $rel = @(Invoke-FkeSql -Payload @{ ids = $top; project = $proj; verifiedOnly = [bool]$VerifiedOnly } -Sql @'
  274. WITH p AS (SELECT current_setting('fke.p')::jsonb AS j),
  275. ids AS (SELECT ARRAY(SELECT (jsonb_array_elements_text(j->'ids'))::bigint) AS a, NULLIF(j->>'project', '') AS project, (j->>'verifiedOnly')::boolean AS vo FROM p)
  276. SELECT COALESCE(jsonb_agg(x), '[]'::jsonb) FROM (
  277. SELECT DISTINCT ON (n.id) n.id, n.title, n.knowledge_type AS type, n.status, r.relationship_type AS relationship,
  278. CASE WHEN r.source_id = ANY(ids.a) THEN r.source_id ELSE r.target_id END AS "from",
  279. CASE WHEN r.source_id = ANY(ids.a) THEN 'out' ELSE 'in' END AS direction
  280. FROM ids CROSS JOIN knowledge.relationships r
  281. JOIN knowledge.entries n ON n.id = CASE WHEN r.source_id = ANY(ids.a) THEN r.target_id ELSE r.source_id END
  282. WHERE (r.source_id = ANY(ids.a) OR r.target_id = ANY(ids.a))
  283. AND n.id <> ALL(ids.a) AND n.status <> 'superseded'
  284. AND (NOT ids.vo OR n.status = 'verified')
  285. AND (ids.project IS NULL OR n.project_key = ids.project OR n.project_key IS NULL)
  286. ORDER BY n.id) x;
  287. '@)
  288. foreach ($r in $rel) {
  289. $cost = Get-FkeTokenEstimate ($r | ConvertTo-Json -Compress)
  290. if ($MaxTokens -gt 0 -and ($used + $cost) -gt $MaxTokens) { $omitted++; continue }
  291. $related += $r; $used += $cost
  292. }
  293. }
  294. Out-FkeResult ([pscustomobject]@{
  295. query = $Query; mode = $mode; embeddingModel = (Get-FkeConfig).EmbeddingModel; project = $proj
  296. results = @($included); related = @($related)
  297. estimatedTokens = $used; maxTokens = $MaxTokens; omittedForBudget = $omitted
  298. }) -AsJson:$AsJson
  299. }
  300. function Add-FoundryLesson {
  301. <# .SYNOPSIS Record a reusable lesson learned (type lesson-learned). #>
  302. [CmdletBinding()]
  303. param(
  304. [Parameter(Mandatory)][string]$Title, [Parameter(Mandatory)][string]$Lesson,
  305. [string]$Project, [switch]$Global, [string]$Source, [string[]]$Tags = @(),
  306. [ValidateRange(0, 1)][double]$Confidence = 0.5,
  307. [ValidateSet('unverified', 'verified')][string]$Status = 'unverified',
  308. [switch]$Force, [switch]$AsJson
  309. )
  310. Add-FoundryKnowledge -Title $Title -Content $Lesson -Type 'lesson-learned' -Project $Project -Global:$Global `
  311. -Source $Source -Tags $Tags -Confidence $Confidence -Status $Status -Force:$Force -AsJson:$AsJson
  312. }
  313. function Add-FoundryDecision {
  314. <# .SYNOPSIS Record an architectural decision with its reasoning (type decision). #>
  315. [CmdletBinding()]
  316. param(
  317. [Parameter(Mandatory)][string]$Title, [Parameter(Mandatory)][string]$Decision,
  318. [Parameter(Mandatory)][string]$Rationale, [string]$Alternatives,
  319. [string]$Project, [switch]$Global, [string]$Source, [string[]]$Tags = @(),
  320. [ValidateRange(0, 1)][double]$Confidence = 0.5,
  321. [ValidateSet('unverified', 'verified')][string]$Status = 'unverified',
  322. [switch]$Force, [switch]$AsJson
  323. )
  324. $content = "Decision: $Decision`nRationale: $Rationale"
  325. if ($Alternatives) { $content += "`nAlternatives considered: $Alternatives" }
  326. Add-FoundryKnowledge -Title $Title -Content $content -Type 'decision' -Project $Project -Global:$Global `
  327. -Source $Source -Tags $Tags -Confidence $Confidence -Status $Status -Force:$Force -AsJson:$AsJson
  328. }

Powered by TurnKey Linux.