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.

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

Powered by TurnKey Linux.