|
- <%
- '=======================================================================================================================
- ' Learning loop support (spec FR-012, FR-013, FR-014, FR-020, section 12): evidence links, memory writes shared by
- ' remember/correct and candidate review, and retrieval telemetry for feedback (AC-18).
- '
- ' Evidence : Set ev = New Evidence_Class : msg = ev.Load(input, "evidence") ("" = ok, else a validation message)
- ' then, inside the write transaction: ev.Save "memory"|"candidate", ownerId, ownerRevision (or Null)
- ' Every target must be in the caller's tenant and readable by the caller; the target revision is
- ' pinned at link time (memory/document current revision, chunk document revision).
- ' Memories : Mem_InsertRevision, Mem_Create, Mem_Revise (call inside a transaction; they also update the lexical
- ' index and mark the semantic index pending; call Emb_AfterWrite after commit)
- ' Evidence_Json ownerKind, ownerId, ownerRev: the evidence of an owner as JSON (unreadable targets shown without id)
- ' Telemetry : Tel_Record queryId, operation, strategy, queryText, resultsSpec, startTimer
- ' resultsSpec = "kind|id|revision|score" items joined by Chr(30). Only a hash of the query is kept.
- '=======================================================================================================================
- Const EVIDENCE_MAX = 20
-
- Class Evidence_Class
- Private m_kind(), m_id(), m_rev(), m_role(), m_excerpt(), m_n
-
- Private Sub Class_Initialize()
- m_n = 0
- ReDim m_kind(EVIDENCE_MAX)
- ReDim m_id(EVIDENCE_MAX)
- ReDim m_rev(EVIDENCE_MAX)
- ReDim m_role(EVIDENCE_MAX)
- ReDim m_excerpt(EVIDENCE_MAX)
- End Sub
-
- Public Property Get Count()
- Count = m_n
- End Property
-
- ' Reads and validates input(name): an optional array of {"kind","id","role","excerpt"}.
- Public Function Load(input, name)
- Dim items, i, o, kind, id, role, excerpt, rev, ns, rs, pos
- Load = ""
- m_n = 0
- If Not input.HasRaw(name) Then
- If input.Exists(name) Then
- If Not IsNull(input.Item(name)) Then
- Load = name & " must be an array of objects."
- End If
- End If
- Exit Function
- End If
- items = JsonLite_SplitObjectArray(input.Raw(name))
- If IsNull(items) Then
- Load = name & " must be an array of objects."
- Exit Function
- End If
- If UBound(items) + 1 > EVIDENCE_MAX Then
- Load = name & " may contain at most " & EVIDENCE_MAX & " items."
- Exit Function
- End If
- For i = 0 To UBound(items)
- pos = name & "[" & i & "]"
- Set o = JsonLite_Parse(items(i))
- If o Is Nothing Then
- Load = pos & " must be an object."
- Exit Function
- End If
- kind = LCase("" & StrField(o, "kind"))
- id = "" & StrField(o, "id")
- role = LCase("" & StrField(o, "role"))
- excerpt = StrField(o, "excerpt")
- If Len(role) = 0 Then
- role = "supports"
- End If
- If kind <> "experience" And kind <> "chunk" And kind <> "memory" And kind <> "document" Then
- Load = pos & ".kind must be experience, chunk, memory or document."
- Exit Function
- End If
- If role <> "supports" And role <> "contradicts" And role <> "context" Then
- Load = pos & ".role must be supports, contradicts or context."
- Exit Function
- End If
- If Not IsNull(excerpt) Then
- If Len(excerpt) > 2000 Then
- Load = pos & ".excerpt must be at most 2000 characters."
- Exit Function
- End If
- End If
- If Not Api_IsId(id) Then
- Load = pos & ".id must be a valid id."
- Exit Function
- End If
- ' Resolve the target in this tenant; a target the caller cannot read is reported like a missing one.
- ns = ""
- rev = Null
- Select Case kind
- Case "experience"
- Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
- If Not rs.EOF Then
- ns = "" & rs(0)
- End If
- rs.Close
- Case "chunk"
- Set rs = DAL().Query("SELECT d.namespace_id, c.document_revision FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId))
- If Not rs.EOF Then
- ns = "" & rs(0)
- rev = CLng(rs(1))
- End If
- rs.Close
- Case "memory"
- Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
- If Not rs.EOF Then
- ns = "" & rs(0)
- rev = CLng(rs(1))
- End If
- rs.Close
- Case "document"
- Set rs = DAL().Query("SELECT namespace_id, current_revision FROM documents WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
- If Not rs.EOF Then
- ns = "" & rs(0)
- rev = CLng(rs(1))
- End If
- rs.Close
- End Select
- If Len(ns) = 0 Then
- Load = pos & " was not found."
- Exit Function
- End If
- If Not Api_CanAccessNamespace(ns, "read") Then
- Load = pos & " was not found."
- Exit Function
- End If
- m_kind(m_n) = kind
- m_id(m_n) = id
- m_rev(m_n) = rev
- m_role(m_n) = role
- m_excerpt(m_n) = excerpt
- m_n = m_n + 1
- Next
- End Function
-
- Private Function StrField(o, k)
- Dim v
- StrField = Null
- If o.Exists(k) Then
- v = o.Item(k)
- If VarType(v) = vbString Then
- StrField = v
- End If
- End If
- End Function
-
- ' Writes the links (call inside the caller's transaction). ownerRevision: memory revision, or Null for candidates.
- Public Sub Save(ownerKind, ownerId, ownerRevision)
- Dim i, linkId
- For i = 0 To m_n - 1
- linkId = Api_NewId()
- DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
- Array(linkId, Api_TenantId, ownerKind, ownerId, m_kind(i), m_id(i), Api_PrincipalId, Api_Now())
- DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
- Array(ownerRevision, m_rev(i), m_role(i), m_excerpt(i), linkId)
- Next
- End Sub
- End Class
-
- ' Copies a candidate's evidence to a memory revision (candidate acceptance; inside the transaction)
- Sub Evidence_CopyCandidate(candidateId, memoryId, revision)
- Dim rs, rows, i, linkId
- Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt FROM evidence_links WHERE owner_kind = 'candidate' AND owner_id = ?", candidateId)
- rows = Empty
- If Not rs.EOF Then
- rows = rs.GetRows()
- End If
- rs.Close
- If IsEmpty(rows) Then
- Exit Sub
- End If
- For i = 0 To UBound(rows, 2)
- linkId = Api_NewId()
- DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, 'memory', ?, ?, ?, ?, ?)", _
- Array(linkId, Api_TenantId, memoryId, "" & rows(0, i), "" & rows(1, i), Api_PrincipalId, Api_Now())
- DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
- Array(CLng(revision), rows(2, i), "" & rows(3, i), rows(4, i), linkId)
- Next
- End Sub
-
- ' Evidence of an owner as a JSON array. A target the caller cannot read (or that is gone) is shown without its id.
- Function Evidence_Json(ownerKind, ownerId, ownerRev)
- Dim rs, rows, i, out, kind, tid, ns, avail, r2
- If IsNull(ownerRev) Then
- Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND tenant_id = ? ORDER BY created_at, id", _
- Array(ownerKind, ownerId, Api_TenantId))
- Else
- Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND owner_revision = ? AND tenant_id = ? ORDER BY created_at, id", _
- Array(ownerKind, ownerId, CLng(ownerRev), Api_TenantId))
- End If
- rows = Empty
- If Not rs.EOF Then
- rows = rs.GetRows()
- End If
- rs.Close
- out = ""
- If Not IsEmpty(rows) Then
- For i = 0 To UBound(rows, 2)
- kind = "" & rows(0, i)
- tid = "" & rows(1, i)
- ns = Evidence_TargetNamespace(kind, tid)
- avail = False
- If Len(ns) > 0 Then
- avail = Api_CanAccessNamespace(ns, "read")
- End If
- If i > 0 Then
- out = out & ","
- End If
- out = out & "{""kind"":" & JsonLite_Quote(kind)
- If avail Then
- out = out & ",""id"":" & JsonLite_Quote(tid) & ",""revision"":" & Evidence_JNum(rows(2, i))
- End If
- out = out & ",""available"":" & LCase(CStr(avail)) & ",""role"":" & JsonLite_Quote("" & rows(3, i))
- If avail Then
- out = out & ",""excerpt"":" & Evidence_JStr(rows(4, i))
- End If
- out = out & ",""content_trust"":"""
- If kind = "chunk" Or kind = "document" Then
- out = out & "untrusted_reference"
- Else
- out = out & "evidence"
- End If
- out = out & """}"
- Next
- End If
- Evidence_Json = "[" & out & "]"
- End Function
-
- Function Evidence_TargetNamespace(kind, tid)
- Dim rs
- Evidence_TargetNamespace = ""
- Select Case kind
- Case "experience"
- Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
- Case "chunk"
- Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(tid, Api_TenantId))
- Case "memory"
- Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
- Case Else
- Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
- End Select
- If Not rs.EOF Then
- Evidence_TargetNamespace = "" & rs(0)
- End If
- rs.Close
- End Function
-
- Function Evidence_JStr(v)
- If IsNull(v) Then
- Evidence_JStr = "null"
- Else
- Evidence_JStr = JsonLite_Quote("" & v)
- End If
- End Function
-
- Function Evidence_JNum(v)
- If IsNull(v) Then
- Evidence_JNum = "null"
- ElseIf Len("" & v) = 0 Then
- Evidence_JNum = "null"
- Else
- Evidence_JNum = JsonLite_Num(v)
- End If
- End Function
-
- '-----------------------------------------------------------------------------------------------------------------------
- ' Memory writes (inside a transaction)
- '-----------------------------------------------------------------------------------------------------------------------
- ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps.
- Sub Mem_InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
- DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
- "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
- DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
- Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
- End Sub
-
- Function Mem_Hash(nsId, memType, title, content)
- Mem_Hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
- End Function
-
- ' New memory, revision 1. Returns the id.
- Function Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, reason)
- Dim memId, ts
- memId = Api_NewId()
- ts = Api_Now()
- DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _
- "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts)
- Mem_InsertRevision Api_NewId(), memId, 1, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts
- Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw
- Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1
- Mem_Create = memId
- End Function
-
- ' New revision curRev + 1 of an existing memory (type and namespace unchanged). Returns the new revision number.
- Function Mem_Revise(memId, nsId, memType, curRev, title, summary, content, tagsRaw, confidence, reason)
- Dim newRev, ts
- newRev = curRev + 1
- ts = Api_Now()
- Mem_InsertRevision Api_NewId(), memId, newRev, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts
- Search_IndexMemory memId, newRev, Api_TenantId, nsId, title, content, tagsRaw
- Emb_MarkPending "memory", memId, Api_TenantId, nsId, newRev
- DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _
- Array(newRev, ts, memId, Api_TenantId, CLng(curRev))
- Mem_Revise = newRev
- End Function
-
- Sub Mem_Verify(memId, revision, method, notes)
- DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, 'verified', ?, ?, ?)", _
- Array(Api_NewId(), memId, CLng(revision), method, notes, Api_PrincipalId, Api_Now())
- DAL().Execute "UPDATE memory_revisions SET verification_status = 'verified' WHERE memory_id = ? AND revision = ?", Array(memId, CLng(revision))
- End Sub
-
- ' Derived and linked data of a memory that is being forgotten (inside the forget transaction, AC-13)
- Sub Mem_ForgetLinked(memId)
- DAL().Execute "DELETE FROM evidence_links WHERE owner_kind = 'memory' AND owner_id = ?", memId
- ' Edges need valid endpoints (spec 8.1): drop every relationship touching the memory
- Graph_ForgetNode "memory", memId
- DAL().Execute "DELETE FROM verifications WHERE memory_id = ?", memId
- DAL().Execute "DELETE FROM feedback WHERE target_kind = 'memory' AND target_id = ?", memId
- DAL().Execute "DELETE FROM retrieval_results WHERE target_kind = 'memory' AND target_id = ?", memId
- ' Open proposals to revise it can no longer be applied; all candidates drop the reference (foreign key)
- DAL().Execute "UPDATE learning_candidates SET state = 'rejected', review_notes = 'target memory was forgotten', reviewed_at = ? " & _
- "WHERE target_memory_id = ? AND state = 'proposed'", Array(Api_Now(), memId)
- DAL().Execute "UPDATE learning_candidates SET target_memory_id = NULL WHERE target_memory_id = ?", memId
- End Sub
-
- '-----------------------------------------------------------------------------------------------------------------------
- ' Retrieval telemetry (never fails the retrieval)
- '-----------------------------------------------------------------------------------------------------------------------
- Function Tel_NewQueryId()
- Tel_NewQueryId = "qry-" & Api_NewId()
- End Function
-
- Sub Tel_AddResult(ByRef spec, kind, id, revision, score)
- If Len(spec) > 0 Then
- spec = spec & Chr(30)
- End If
- spec = spec & kind & "|" & id & "|" & CLng(revision) & "|" & JsonLite_Num(score)
- End Sub
-
- Sub Tel_Record(queryId, operation, strategy, queryText, spec, startTimer)
- Dim items, i, parts, ms, cnt
- On Error Resume Next
- If Len(spec) = 0 Then
- items = Array()
- Else
- items = Split(spec, Chr(30))
- End If
- cnt = UBound(items) + 1
- ms = CLng((Timer - startTimer) * 1000)
- If ms < 0 Then
- ms = 0
- End If
- DAL().BeginTransaction
- DAL().Execute "INSERT INTO retrieval_queries (id, tenant_id, principal_id, operation, strategy, query_hash, result_count, duration_ms, created_at) " & _
- "VALUES (?, ?, ?, ?, ?, ?, " & cnt & ", " & ms & ", ?)", Array(queryId, Api_TenantId, Api_PrincipalId, operation, strategy, Api_Sha256("" & queryText), Api_Now())
- For i = 0 To cnt - 1
- parts = Split(items(i), "|")
- DAL().Execute "INSERT OR IGNORE INTO retrieval_results (query_id, target_kind, target_id, target_revision, rank, score) VALUES (?, ?, ?, ?, ?, ?)", _
- Array(queryId, parts(0), parts(1), CLng(parts(2)), i + 1, CDbl(Replace(parts(3), ".", Mid(CStr(1.5), 2, 1))))
- Next
- If Err.Number <> 0 Then
- Err.Clear
- DAL().RollbackTransaction
- Else
- DAL().CommitTransaction
- End If
- Err.Clear
- On Error GoTo 0
- End Sub
- %>
|