<% ' ApiMemoriesController: canonical memory records (spec FR-001..FR-005, FR-011, FR-015). ' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp. ' ' POST /api/v1/remember Remember create a memory (Idempotency-Key supported; exact duplicates detected) ' GET /api/v1/memories Recent list/filter, newest first, cursor pagination ' GET /api/v1/memories/:id Fetch one memory (?revision=n for an older revision) ' PATCH /api/v1/memories/:id Correct new revision; needs If-Match: (or "expected_revision") ' DELETE /api/v1/memories/:id Forget permanent delete incl. revision history ' POST /api/v1/memories/:id/retire Retire exclude from ordinary retrieval ' GET /api/v1/memories/:id/versions Versions revision history ' ' Permissions on the memory's namespace: read (Fetch/Recent/Versions), write (Remember/Correct/Retire), delete (Forget). ' Anything the caller may not see is a 404. Class ApiMemoriesController_Class Private m_errs Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Memories API" End Property '--------------------------------------------------------------- ' POST /api/v1/remember '--------------------------------------------------------------- Public Sub Remember() Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, attrRaw Dim confidence, importance, hash, memId, revId, ts, resp, rs, errs, k, warnings If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) idemKey = Api_Header("Idempotency-Key") If Len(idemKey) > 200 Then Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." Exit Sub End If reqHash = Api_Sha256(body) If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub m_errs = "" nsId = ReqString(input, "namespace_id", 64) memType = ReqString(input, "type", 40) title = ReqString(input, "title", 200) content = ReqString(input, "content", 100000) summary = OptString(input, "summary", 2000) tagsRaw = TagsJson(input) attrRaw = AttributesJson(input) confidence = OptUnit(input, "confidence") importance = OptUnit(input, "importance") If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If ' Concealment: a namespace the caller cannot write to looks the same as one that does not exist. If Not Api_CanAccessNamespace(nsId, "write") Then Api_Audit "memory.remember", "namespace", nsId, "denied" Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType) If rs.EOF Then rs.Close Api_Invalid Array("type '" & memType & "' is not a known memory type.") Exit Sub End If rs.Close hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content) ' Exact duplicate of an active memory in the same namespace: return it instead of creating another. Set rs = DAL().Query("SELECT m.id, m.current_revision, r.verification_status FROM memories m " & _ "JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _ "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", _ Array(Api_TenantId, nsId, memType, hash)) If Not rs.EOF Then resp = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""revision"":" & CLng(rs(1)) & ",""status"":""active"",""verification_status"":" & _ JsonLite_Quote("" & rs(2)) & ",""indexing_status"":""lexical_indexed"",""duplicate"":true}" rs.Close StoreIdem idemKey, reqHash, 200, resp Api_Send 200, resp Exit Sub End If rs.Close memId = Api_NewId() revId = Api_NewId() ts = Api_Now() On Error Resume Next DAL().BeginTransaction 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) InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1 resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed"",""duplicate"":false}" StoreIdem idemKey, reqHash, 201, resp If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Emb_AfterWrite Api_TenantId, 8 Api_Audit "memory.remember", "memory", memId, "ok" Response.AddHeader "Location", "/api/v1/memories/" & memId Api_Send 201, resp End Sub '--------------------------------------------------------------- ' GET /api/v1/memories ?namespace_id= &type= &status=active|retired|superseded|all &verification_status= &limit= &cursor= '--------------------------------------------------------------- Public Sub Recent() Dim nsId, memType, status, ver, lim, cursor, allowed, sql, params(), n, rs, out, count, lastTs, lastId, p, cts, cid, nextCursor If Not Api_Authenticate() Then Exit Sub nsId = Trim("" & Request.QueryString("namespace_id")) memType = Trim("" & Request.QueryString("type")) status = LCase(Trim("" & Request.QueryString("status"))) ver = LCase(Trim("" & Request.QueryString("verification_status"))) lim = Api_ToInt(Request.QueryString("limit"), 20, 1, 100) cursor = Trim("" & Request.QueryString("cursor")) If Len(status) = 0 Then status = "active" If status <> "active" And status <> "retired" And status <> "superseded" And status <> "all" Then Api_Invalid Array("status must be active, retired, superseded or all.") Exit Sub End If If Len(ver) > 0 And ver <> "unverified" And ver <> "verified" And ver <> "disputed" And ver <> "rejected" Then Api_Invalid Array("verification_status must be unverified, verified, disputed or rejected.") Exit Sub End If If Len(nsId) > 0 Then If Not Api_CanAccessNamespace(nsId, "read") Then Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If allowed = "'" & nsId & "'" Else allowed = Api_AllowedNamespaceIds("read") End If If Len(allowed) = 0 Then Api_Send 200, "{""data"":[],""next_cursor"":null}" Exit Sub End If sql = MemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ")" ReDim params(0) params(0) = Api_TenantId n = 1 If Len(memType) > 0 Then sql = sql & " AND m.type = ?" ReDim Preserve params(n) params(n) = memType n = n + 1 End If If status <> "all" Then sql = sql & " AND m.lifecycle_status = ?" ReDim Preserve params(n) params(n) = status n = n + 1 End If If Len(ver) > 0 Then sql = sql & " AND r.verification_status = ?" ReDim Preserve params(n) params(n) = ver n = n + 1 End If If Len(cursor) > 0 Then p = InStr(cursor, "|") cts = "" cid = "" If p > 0 Then cts = Left(cursor, p - 1) cid = Mid(cursor, p + 1) End If If Len(cts) = 0 Or Not Api_IsId(cid) Then Api_Error 400, "invalid_cursor", "The cursor is not valid." Exit Sub End If sql = sql & " AND (m.created_at < ? OR (m.created_at = ? AND m.id < ?))" ReDim Preserve params(n + 2) params(n) = cts params(n + 1) = cts params(n + 2) = cid n = n + 3 End If ' G3DB accepts at most 8 parameters (tenant + type + status + verification + 3 cursor = 7) sql = sql & " ORDER BY m.created_at DESC, m.id DESC LIMIT " & (lim + 1) Set rs = DAL().Query(sql, params) out = "" count = 0 lastTs = "" lastId = "" nextCursor = "null" Do While Not rs.EOF If count >= lim Then nextCursor = JsonLite_Quote(lastTs & "|" & lastId) Exit Do End If If count > 0 Then out = out & "," out = out & MemoryJson(rs, True) lastTs = "" & rs(8) lastId = "" & rs(0) count = count + 1 rs.MoveNext Loop rs.Close Api_Send 200, "{""data"":[" & out & "],""next_cursor"":" & nextCursor & "}" End Sub '--------------------------------------------------------------- ' GET /api/v1/memories/:id (?revision=n) '--------------------------------------------------------------- Public Sub Fetch(id) Dim rs, nsId, revParam, rev, json If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If ' The row is copied out and the result set closed BEFORE the permission check: a second query while a ' result set is still open hangs the request under G3DB/SQLite (script timeout). Set rs = DAL().Query(MemorySelect() & " WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(1) json = MemoryJson(rs, False) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If revParam = Trim("" & Request.QueryString("revision")) If Len(revParam) = 0 Then Api_Send 200, "{""data"":" & json & "}" Exit Sub End If If Not IsNumeric(revParam) Then Api_Invalid Array("revision must be a positive integer.") Exit Sub End If rev = CLng(revParam) Set rs = DAL().Query(MemorySelectRevision() & " WHERE m.id = ? AND m.tenant_id = ?", Array(rev, id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If json = MemoryJson(rs, False) rs.Close Api_Send 200, "{""data"":" & json & "}" End Sub '--------------------------------------------------------------- ' PATCH /api/v1/memories/:id creates revision n+1 (unverified) '--------------------------------------------------------------- Public Sub Correct(id) Dim body, input, rs, nsId, curRev, expected, ifMatch, lifecycle Dim title, content, summary, tagsRaw, attrRaw, confidence, importance, reason, hash, ts, newRev, memType, k, resp Dim hasTitle, hasContent, hasSummary, hasTags, hasAttr, hasConf, hasImp If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) Set rs = DAL().Query("SELECT m.namespace_id, m.current_revision, m.lifecycle_status, m.type, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance " & _ "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _ "WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) curRev = CLng(rs(1)) lifecycle = "" & rs(2) memType = "" & rs(3) title = rs(4) summary = rs(5) content = rs(6) attrRaw = rs(7) tagsRaw = rs(8) confidence = rs(9) importance = rs(10) rs.Close If Not Api_CanAccessNamespace(nsId, "write") Then Api_NotFound Exit Sub End If ' Optimistic concurrency: the caller must say which revision they edited. ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "") expected = ifMatch If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision") If Len(expected) = 0 Then Api_Error 428, "precondition_required", "Send If-Match: (or ""expected_revision"" in the body)." Exit Sub End If If Not IsNumeric(expected) Then Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number." Exit Sub End If If CLng(expected) <> curRev Then Response.AddHeader "ETag", """" & curRev & """" Api_Error 412, "stale_revision", "The memory is at revision " & curRev & ", not " & CLng(expected) & ". Re-read it and retry." Exit Sub End If If lifecycle <> "active" Then Api_Error 409, "not_active", "A " & lifecycle & " memory cannot be corrected." Exit Sub End If m_errs = "" hasTitle = input.Exists("title") hasContent = input.Exists("content") hasSummary = input.Exists("summary") hasTags = input.Exists("tags") Or input.HasRaw("tags") hasAttr = input.Exists("attributes") Or input.HasRaw("attributes") hasConf = input.Exists("confidence") hasImp = input.Exists("importance") If hasTitle Then title = ReqString(input, "title", 200) If hasContent Then content = ReqString(input, "content", 100000) If hasSummary Then summary = OptString(input, "summary", 2000) If hasTags Then tagsRaw = TagsJson(input) If hasAttr Then attrRaw = AttributesJson(input) If hasConf Then confidence = OptUnit(input, "confidence") If hasImp Then importance = OptUnit(input, "importance") reason = OptString(input, "change_reason", 500) If Not (hasTitle Or hasContent Or hasSummary Or hasTags Or hasAttr Or hasConf Or hasImp) Then m_errs = m_errs & Chr(30) & "Send at least one field to change." End If If Left(m_errs, 1) = Chr(30) Then m_errs = Mid(m_errs, 2) If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If IsNull(reason) Or Len("" & reason) = 0 Then reason = "corrected" hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content) ts = Api_Now() newRev = curRev + 1 On Error Resume Next DAL().BeginTransaction InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts Search_IndexMemory id, newRev, Api_TenantId, nsId, title, content, tagsRaw Emb_MarkPending "memory", id, Api_TenantId, nsId, newRev DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _ Array(newRev, ts, id, Api_TenantId, curRev) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Emb_AfterWrite Api_TenantId, 8 Api_Audit "memory.correct", "memory", id, "ok" Response.AddHeader "ETag", """" & newRev & """" resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed""}" Api_Send 200, resp End Sub '--------------------------------------------------------------- ' DELETE /api/v1/memories/:id '--------------------------------------------------------------- Public Sub Forget(id) Dim rs, nsId, k If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) rs.Close If Not Api_CanAccessNamespace(nsId, "delete") Then Api_Audit "memory.forget", "memory", id, "denied" Api_NotFound Exit Sub End If On Error Resume Next DAL().BeginTransaction Search_UnindexMemory id Emb_MarkDelete "memory", id Mem_ForgetLinked id DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction On Error GoTo 0 Emb_AfterWrite Api_TenantId, 8 Api_Audit "memory.forget", "memory", id, "ok" Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/memories/:id/retire '--------------------------------------------------------------- Public Sub Retire(id) Dim rs, nsId, k If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) rs.Close If Not Api_CanAccessNamespace(nsId, "write") Then Api_NotFound Exit Sub End If On Error Resume Next DAL().Execute "UPDATE memories SET lifecycle_status = 'retired', updated_at = ? WHERE id = ? AND tenant_id = ?", Array(Api_Now(), id, Api_TenantId) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "memory.retire", "memory", id, "ok" Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""retired""}" End Sub '--------------------------------------------------------------- ' GET /api/v1/memories/:id/versions '--------------------------------------------------------------- Public Sub Versions(id) Dim rs, nsId, out, count If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT revision, title, summary, content, tags, confidence, importance, verification_status, change_reason, created_by, created_at " & _ "FROM memory_revisions WHERE memory_id = ? ORDER BY revision DESC", id) out = "" count = 0 Do While Not rs.EOF If count > 0 Then out = out & "," out = out & "{""revision"":" & CLng(rs(0)) & ",""title"":" & JsonLite_Quote("" & rs(1)) & ",""summary"":" & JStr(rs(2)) & _ ",""content"":" & JsonLite_Quote("" & rs(3)) & ",""tags"":" & JRaw(rs(4), "[]") & ",""confidence"":" & JNum(rs(5)) & _ ",""importance"":" & JNum(rs(6)) & ",""verification_status"":" & JsonLite_Quote("" & rs(7)) & _ ",""change_reason"":" & JStr(rs(8)) & ",""created_by"":" & JsonLite_Quote("" & rs(9)) & ",""created_at"":" & JsonLite_Quote("" & rs(10)) & "}" count = count + 1 rs.MoveNext Loop rs.Close Api_Send 200, "{""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' POST /api/v1/memories/:id/verifications ' {"revision":n,"result":"verified|disputed|rejected","method":"...","notes":"..."} needs the "verify" (or admin) permission. ' Verification belongs to exactly one revision: it must be the current one. '--------------------------------------------------------------- Public Sub Verify(id) Dim body, input, rs, nsId, curRev, rev, result, method, notes, k, ts If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) curRev = CLng(rs(1)) rs.Close If Not Api_CanAccessNamespace(nsId, "verify") Then Api_Audit "memory.verify", "memory", id, "denied" Api_NotFound Exit Sub End If m_errs = "" result = LCase("" & ReqString(input, "result", 20)) method = ReqString(input, "method", 200) notes = OptString(input, "notes", 2000) If Not input.Exists("revision") Then AddErr "revision is required." ElseIf VarType(input.Item("revision")) <> vbDouble Then AddErr "revision must be a number." Else rev = CLng(input.Item("revision")) End If If result <> "verified" And result <> "disputed" And result <> "rejected" And Len(m_errs) = 0 Then AddErr "result must be verified, disputed or rejected." End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If rev <> curRev Then Api_Error 409, "not_current_revision", "Only the current revision (" & curRev & ") can be verified; revision " & rev & " was given." Exit Sub End If ts = Api_Now() On Error Resume Next DAL().BeginTransaction DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ Array(Api_NewId(), id, rev, method, result, notes, Api_PrincipalId, ts) DAL().Execute "UPDATE memory_revisions SET verification_status = ? WHERE memory_id = ? AND revision = ?", Array(result, id, rev) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction On Error GoTo 0 Api_Audit "memory.verify", "memory", id, result Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(result) & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/recall ' {"query","types":[],"namespace_ids":[],"verification_filter":"verified_only|include_unverified","max_results","detail_level":"full|summary"} ' Hybrid retrieval (FTS5/bm25 fused with vector similarity when configured, see core/lib.Embeddings.asp) over ' active memories the caller can read. Trusted retrieval is the default, so ' unverified memories are left out unless asked for (they are labelled when included). '--------------------------------------------------------------- Public Sub Recall() Dim body, input, query, fts, maxResults, detail, vf, allowed, requested, typesSql, ids(), scores(), n, rs, i, j, idList, sql Dim rowJson(), out, count, excluded, now_, v, st, params, warnings, ranker, revs(), qid, spec, t0 t0 = Timer If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" query = ReqString(input, "query", 1000) maxResults = 10 If input.Exists("max_results") Then If VarType(input.Item("max_results")) = vbDouble Then maxResults = CLng(input.Item("max_results")) If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50." Else AddErr "max_results must be a number." End If End If detail = OptString(input, "detail_level", 20) If IsNull(detail) Then detail = "full" detail = LCase(detail) If detail <> "full" And detail <> "summary" Then AddErr "detail_level must be full or summary." vf = OptString(input, "verification_filter", 30) If IsNull(vf) Then vf = "verified_only" vf = LCase(vf) If vf <> "verified_only" And vf <> "include_unverified" Then AddErr "verification_filter must be verified_only or include_unverified." typesSql = TypeListSql(input, "types") requested = IdListSql(input, "namespace_ids") If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If fts = Search_FtsQuery(query) If Len(fts) = 0 Then Api_Invalid Array("query must contain at least one word.") Exit Sub End If allowed = Api_AllowedNamespaceIds("read") If Len(allowed) > 0 And Len(requested) > 0 Then allowed = IntersectIds(allowed, requested) warnings = "[""semantic retrieval is not configured; results are lexical only""]" qid = Tel_NewQueryId() spec = "" If Len(allowed) = 0 Then Tel_Record qid, "recall", "lexical", query, spec, t0 Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":""lexical"",""results"":[],""warnings"":" & warnings & "}" Exit Sub End If ' Lexical + (when configured) semantic candidates, fused; scores are negated here to match the output below Set ranker = New Ranker_Class ranker.Run "memory", fts, query, Api_TenantId, allowed n = ranker.Count If n > 0 Then ReDim ids(n - 1) ReDim scores(n - 1) For i = 0 To n - 1 ids(i) = ranker.IdAt(i) scores(i) = -ranker.ScoreAt(i) Next End If warnings = "" If Len(ranker.Warning) > 0 Then warnings = JsonLite_Quote(ranker.Warning) End If out = "" count = 0 excluded = 0 If n > 0 Then idList = "" For i = 0 To n - 1 If Api_IsId(ids(i)) Then If Len(idList) > 0 Then idList = idList & "," idList = idList & "'" & ids(i) & "'" End If Next now_ = Api_Now() sql = MemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?)" If Len(typesSql) > 0 Then sql = sql & " AND m.type IN (" & typesSql & ")" Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_)) ReDim rowJson(n - 1) ReDim revs(n - 1) Do While Not rs.EOF st = "" & rs(18) If vf = "verified_only" And st <> "verified" Then excluded = excluded + 1 Else For j = 0 To n - 1 If ids(j) = "" & rs(0) Then v = MemoryJson(rs, (detail = "summary")) If detail = "summary" Then v = SummaryOnly(v, rs) rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j))) If Len(ranker.FeedbackAt(j)) > 0 Then rowJson(j) = rowJson(j) & ",""feedback"":" & ranker.FeedbackAt(j) End If rowJson(j) = rowJson(j) & "}" revs(j) = CLng(rs(10)) Exit For End If Next End If rs.MoveNext Loop rs.Close For j = 0 To n - 1 If Len("" & rowJson(j)) > 0 Then If count >= maxResults Then Exit For If count > 0 Then out = out & "," out = out & rowJson(j) count = count + 1 Tel_AddResult spec, "memory", ids(j), revs(j), -CDbl(scores(j)) End If Next End If If excluded > 0 Then If Len(warnings) > 0 Then warnings = warnings & "," End If warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them""" End If If ranker.Demoted > 0 Then If Len(warnings) > 0 Then warnings = warnings & "," End If warnings = warnings & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback on their current revision") End If Tel_Record qid, "recall", ranker.Strategy, query, spec, t0 Api_Audit "memory.recall", "search", "", "ok" Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}" End Sub '=============================================================== ' Helpers '=============================================================== ' Memory + current revision. Column order is relied on by MemoryJson: ' 0 id, 1 namespace_id, 2 type, 3 current_revision, 4 lifecycle_status, 5 valid_from, 6 valid_until, 7 creator, 8 created_at, 9 updated_at, ' 10 revision, 11 title, 12 summary, 13 content, 14 attributes, 15 tags, 16 confidence, 17 importance, 18 verification_status, 19 change_reason Private Function MemorySelect() MemorySelect = "SELECT m.id, m.namespace_id, m.type, m.current_revision, m.lifecycle_status, m.valid_from, m.valid_until, m.creator_principal_id, m.created_at, m.updated_at, " & _ "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _ "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision" End Function ' Same columns but a specific revision (first parameter is the revision number) Private Function MemorySelectRevision() MemorySelectRevision = "SELECT m.id, m.namespace_id, m.type, m.current_revision, m.lifecycle_status, m.valid_from, m.valid_until, m.creator_principal_id, m.created_at, m.updated_at, " & _ "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _ "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = ?" End Function Private Function MemoryJson(rs, brief) Dim s s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _ ",""status"":" & JsonLite_Quote("" & rs(4)) & ",""current_revision"":" & CLng(rs(3)) & ",""revision"":" & CLng(rs(10)) & _ ",""verification_status"":" & JsonLite_Quote("" & rs(18)) & ",""title"":" & JsonLite_Quote("" & rs(11)) & ",""summary"":" & JStr(rs(12)) If Not brief Then s = s & ",""content"":" & JsonLite_Quote("" & rs(13)) & ",""attributes"":" & JRaw(rs(14), "null") & ",""change_reason"":" & JStr(rs(19)) & _ ",""valid_from"":" & JStr(rs(5)) & ",""valid_until"":" & JStr(rs(6)) & ",""created_by"":" & JsonLite_Quote("" & rs(7)) End If s = s & ",""tags"":" & JRaw(rs(15), "[]") & ",""confidence"":" & JNum(rs(16)) & ",""importance"":" & JNum(rs(17)) & _ ",""created_at"":" & JsonLite_Quote("" & rs(8)) & ",""updated_at"":" & JsonLite_Quote("" & rs(9)) & "}" MemoryJson = s End Function Private Function JStr(v) If IsNull(v) Then JStr = "null" Else JStr = JsonLite_Quote("" & v) End If End Function Private Function JNum(v) If IsNull(v) Then JNum = "null" ElseIf Len("" & v) = 0 Then JNum = "null" Else JNum = JsonLite_Num(v) End If End Function ' Stored raw JSON text (validated on the way in) or a default Private Function JRaw(v, dflt) If IsNull(v) Then JRaw = dflt ElseIf Len("" & v) = 0 Then JRaw = dflt Else JRaw = "" & v End If End Function Private Sub AddErr(msg) If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) m_errs = m_errs & msg End Sub Private Function ReqString(input, name, maxLen) Dim v ReqString = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If v = Trim(v) If Len(v) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqString = v End Function ' Optional string: Null when absent or null Private Function OptString(input, name, maxLen) Dim v OptString = Null If Not input.Exists(name) Then Exit Function v = input.Item(name) If IsNull(v) Then Exit Function If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If OptString = v End Function ' Optional number in 0..1: Null when absent or null Private Function OptUnit(input, name) Dim v OptUnit = Null If Not input.Exists(name) Then Exit Function v = input.Item(name) If IsNull(v) Then Exit Function If VarType(v) <> vbDouble Then AddErr name & " must be a number between 0 and 1." Exit Function End If If v < 0 Or v > 1 Then AddErr name & " must be between 0 and 1." Exit Function End If OptUnit = v End Function ' tags: optional array of non-empty strings; returns compact JSON text or Null Private Function TagsJson(input) Dim arr, i, out, t TagsJson = Null If Not input.HasRaw("tags") Then If input.Exists("tags") Then If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings." End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw("tags")) If IsNull(arr) Then AddErr "tags must be an array of strings." Exit Function End If If UBound(arr) > 31 Then AddErr "tags may contain at most 32 entries." Exit Function End If out = "" For i = 0 To UBound(arr) t = Trim(arr(i)) If Len(t) = 0 Or Len(t) > 64 Then AddErr "each tag must be 1 to 64 characters." Exit Function End If If i > 0 Then out = out & "," out = out & JsonLite_Quote(t) Next TagsJson = "[" & out & "]" End Function ' attributes: optional JSON object, stored as its raw text (max 16 KB) or Null Private Function AttributesJson(input) Dim raw AttributesJson = Null If Not input.HasRaw("attributes") Then If input.Exists("attributes") Then If Not IsNull(input.Item("attributes")) Then AddErr "attributes must be a JSON object." End If Exit Function End If raw = input.Raw("attributes") If Left(raw, 1) <> "{" Then AddErr "attributes must be a JSON object." Exit Function End If If Len(raw) > 16384 Then AddErr "attributes must be at most 16 KB." Exit Function End If AttributesJson = raw End Function ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps (same transaction). Private Sub 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 ' summary detail: replace the (omitted) body with the stored summary, or the first 240 characters of the content Private Function SummaryOnly(json, rs) Dim sm If IsNull(rs(12)) Then sm = "" & rs(13) If Len(sm) > 240 Then sm = Left(sm, 240) & "..." Else sm = "" & rs(12) End If SummaryOnly = Left(json, Len(json) - 1) & ",""snippet"":" & JsonLite_Quote(sm) & "}" End Function ' "'a','b'" for an optional array of memory type codes (letters only); "" when absent Private Function TypeListSql(input, name) Dim arr, i, out, c, j, t TypeListSql = "" If Not input.HasRaw(name) Then If input.Exists(name) Then If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of type codes." End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw(name)) If IsNull(arr) Then AddErr name & " must be an array of type codes." Exit Function End If out = "" For i = 0 To UBound(arr) t = LCase(Trim(arr(i))) If Len(t) = 0 Or Len(t) > 40 Then AddErr name & " contains an invalid type." Exit Function End If For j = 1 To Len(t) c = Mid(t, j, 1) If c < "a" Or c > "z" Then AddErr name & " contains an invalid type." Exit Function End If Next If Len(out) > 0 Then out = out & "," out = out & "'" & t & "'" Next TypeListSql = out End Function Private Function IdListSql(input, name) Dim arr, i, out IdListSql = "" If Not input.HasRaw(name) Then If input.Exists(name) Then If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids." End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw(name)) If IsNull(arr) Then AddErr name & " must be an array of ids." Exit Function End If out = "" For i = 0 To UBound(arr) If Not Api_IsId(arr(i)) Then AddErr name & " must contain valid ids." Exit Function End If If Len(out) > 0 Then out = out & "," out = out & "'" & arr(i) & "'" Next If Len(out) = 0 Then AddErr name & " must not be empty when given." IdListSql = out End Function Private Function IntersectIds(allowed, requested) Dim a, i, out a = Split(allowed, ",") out = "" For i = 0 To UBound(a) If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then If Len(out) > 0 Then out = out & "," out = out & a(i) End If Next IntersectIds = out End Function Private Sub StoreIdem(idemKey, reqHash, status, resp) Api_IdempotencyStore idemKey, reqHash, status, resp End Sub ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "remember" : Remember Case "recent" : Recent Case "fetch" : Fetch args(0) Case "correct" : Correct args(0) Case "forget" : Forget args(0) Case "retire" : Retire args(0) Case "versions" : Versions args(0) Case "verify" : Verify args(0) Case "recall" : Recall Case Else Err.Raise 438, "ApiMemoriesController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiMemoriesController_Class__Singleton Function ApiMemoriesController() If IsEmpty(ApiMemoriesController_Class__Singleton) Then Set ApiMemoriesController_Class__Singleton = New ApiMemoriesController_Class End If Set ApiMemoriesController = ApiMemoriesController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiMemoriesController_Invoke(actionName, args) ApiMemoriesController().Invoke actionName, args End Sub %>