|
- <%
- ' 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: <current revision> (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"":""not_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
- resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""not_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
-
- 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: <current revision> (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
- 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
-
- 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"":""not_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
- 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
-
- 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
-
- '===============================================================
- ' 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
-
- 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 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
- %>
|