25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

1047 satır
42KB

  1. <%
  2. ' ApiMemoriesController: canonical memory records (spec FR-001..FR-005, FR-011, FR-015).
  3. ' Stateless JSON API, no layout. Helpers (auth, errors, idempotency) are in core/lib.Api.asp.
  4. '
  5. ' POST /api/v1/remember Remember create a memory (Idempotency-Key supported; exact duplicates detected)
  6. ' GET /api/v1/memories Recent list/filter, newest first, cursor pagination
  7. ' GET /api/v1/memories/:id Fetch one memory (?revision=n for an older revision)
  8. ' PATCH /api/v1/memories/:id Correct new revision; needs If-Match: <current revision> (or "expected_revision")
  9. ' DELETE /api/v1/memories/:id Forget permanent delete incl. revision history
  10. ' POST /api/v1/memories/:id/retire Retire exclude from ordinary retrieval
  11. ' GET /api/v1/memories/:id/versions Versions revision history
  12. '
  13. ' Permissions on the memory's namespace: read (Fetch/Recent/Versions), write (Remember/Correct/Retire), delete (Forget).
  14. ' Anything the caller may not see is a 404.
  15. Class ApiMemoriesController_Class
  16. Private m_errs
  17. Public Property Get useLayout()
  18. useLayout = False
  19. End Property
  20. Public Property Let useLayout(v)
  21. End Property
  22. Public Property Get Title()
  23. Title = "Memories API"
  24. End Property
  25. '---------------------------------------------------------------
  26. ' POST /api/v1/remember
  27. '---------------------------------------------------------------
  28. Public Sub Remember()
  29. Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, attrRaw
  30. Dim confidence, importance, hash, memId, revId, ts, resp, rs, errs, k, warnings
  31. If Not Api_Authenticate() Then Exit Sub
  32. body = Api_ReadBody()
  33. If IsEmpty(body) Then Exit Sub
  34. Set input = JsonLite_Parse(body)
  35. idemKey = Api_Header("Idempotency-Key")
  36. If Len(idemKey) > 200 Then
  37. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  38. Exit Sub
  39. End If
  40. reqHash = Api_Sha256(body)
  41. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  42. m_errs = ""
  43. nsId = ReqString(input, "namespace_id", 64)
  44. memType = ReqString(input, "type", 40)
  45. title = ReqString(input, "title", 200)
  46. content = ReqString(input, "content", 100000)
  47. summary = OptString(input, "summary", 2000)
  48. tagsRaw = TagsJson(input)
  49. attrRaw = AttributesJson(input)
  50. confidence = OptUnit(input, "confidence")
  51. importance = OptUnit(input, "importance")
  52. If Len(m_errs) > 0 Then
  53. Api_Invalid Split(m_errs, Chr(30))
  54. Exit Sub
  55. End If
  56. ' Concealment: a namespace the caller cannot write to looks the same as one that does not exist.
  57. If Not Api_CanAccessNamespace(nsId, "write") Then
  58. Api_Audit "memory.remember", "namespace", nsId, "denied"
  59. Api_Error 404, "namespace_not_found", "Namespace not found."
  60. Exit Sub
  61. End If
  62. Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType)
  63. If rs.EOF Then
  64. rs.Close
  65. Api_Invalid Array("type '" & memType & "' is not a known memory type.")
  66. Exit Sub
  67. End If
  68. rs.Close
  69. hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
  70. ' Exact duplicate of an active memory in the same namespace: return it instead of creating another.
  71. Set rs = DAL().Query("SELECT m.id, m.current_revision, r.verification_status FROM memories m " & _
  72. "JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _
  73. "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", _
  74. Array(Api_TenantId, nsId, memType, hash))
  75. If Not rs.EOF Then
  76. resp = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""revision"":" & CLng(rs(1)) & ",""status"":""active"",""verification_status"":" & _
  77. JsonLite_Quote("" & rs(2)) & ",""indexing_status"":""lexical_indexed"",""duplicate"":true}"
  78. rs.Close
  79. StoreIdem idemKey, reqHash, 200, resp
  80. Api_Send 200, resp
  81. Exit Sub
  82. End If
  83. rs.Close
  84. memId = Api_NewId()
  85. revId = Api_NewId()
  86. ts = Api_Now()
  87. On Error Resume Next
  88. DAL().BeginTransaction
  89. DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _
  90. "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts)
  91. InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts
  92. Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw
  93. Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1
  94. resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed"",""duplicate"":false}"
  95. StoreIdem idemKey, reqHash, 201, resp
  96. If Err.Number <> 0 Then
  97. k = Err.Number : Api_NoteDbError
  98. DAL().RollbackTransaction
  99. Api_DbFailed k, ""
  100. Exit Sub
  101. End If
  102. DAL().CommitTransaction
  103. If Err.Number <> 0 Then
  104. k = Err.Number : Api_NoteDbError
  105. Api_DbFailed k, ""
  106. Exit Sub
  107. End If
  108. On Error GoTo 0
  109. Emb_AfterWrite Api_TenantId, 8
  110. Api_Audit "memory.remember", "memory", memId, "ok"
  111. Response.AddHeader "Location", "/api/v1/memories/" & memId
  112. Api_Send 201, resp
  113. End Sub
  114. '---------------------------------------------------------------
  115. ' GET /api/v1/memories ?namespace_id= &type= &status=active|retired|superseded|all &verification_status= &limit= &cursor=
  116. '---------------------------------------------------------------
  117. Public Sub Recent()
  118. Dim nsId, memType, status, ver, lim, cursor, allowed, sql, params(), n, rs, out, count, lastTs, lastId, p, cts, cid, nextCursor
  119. If Not Api_Authenticate() Then Exit Sub
  120. nsId = Trim("" & Request.QueryString("namespace_id"))
  121. memType = Trim("" & Request.QueryString("type"))
  122. status = LCase(Trim("" & Request.QueryString("status")))
  123. ver = LCase(Trim("" & Request.QueryString("verification_status")))
  124. lim = Api_ToInt(Request.QueryString("limit"), 20, 1, 100)
  125. cursor = Trim("" & Request.QueryString("cursor"))
  126. If Len(status) = 0 Then status = "active"
  127. If status <> "active" And status <> "retired" And status <> "superseded" And status <> "all" Then
  128. Api_Invalid Array("status must be active, retired, superseded or all.")
  129. Exit Sub
  130. End If
  131. If Len(ver) > 0 And ver <> "unverified" And ver <> "verified" And ver <> "disputed" And ver <> "rejected" Then
  132. Api_Invalid Array("verification_status must be unverified, verified, disputed or rejected.")
  133. Exit Sub
  134. End If
  135. If Len(nsId) > 0 Then
  136. If Not Api_CanAccessNamespace(nsId, "read") Then
  137. Api_Error 404, "namespace_not_found", "Namespace not found."
  138. Exit Sub
  139. End If
  140. allowed = "'" & nsId & "'"
  141. Else
  142. allowed = Api_AllowedNamespaceIds("read")
  143. End If
  144. If Len(allowed) = 0 Then
  145. Api_Send 200, "{""data"":[],""next_cursor"":null}"
  146. Exit Sub
  147. End If
  148. sql = MemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ")"
  149. ReDim params(0)
  150. params(0) = Api_TenantId
  151. n = 1
  152. If Len(memType) > 0 Then
  153. sql = sql & " AND m.type = ?"
  154. ReDim Preserve params(n)
  155. params(n) = memType
  156. n = n + 1
  157. End If
  158. If status <> "all" Then
  159. sql = sql & " AND m.lifecycle_status = ?"
  160. ReDim Preserve params(n)
  161. params(n) = status
  162. n = n + 1
  163. End If
  164. If Len(ver) > 0 Then
  165. sql = sql & " AND r.verification_status = ?"
  166. ReDim Preserve params(n)
  167. params(n) = ver
  168. n = n + 1
  169. End If
  170. If Len(cursor) > 0 Then
  171. p = InStr(cursor, "|")
  172. cts = ""
  173. cid = ""
  174. If p > 0 Then
  175. cts = Left(cursor, p - 1)
  176. cid = Mid(cursor, p + 1)
  177. End If
  178. If Len(cts) = 0 Or Not Api_IsId(cid) Then
  179. Api_Error 400, "invalid_cursor", "The cursor is not valid."
  180. Exit Sub
  181. End If
  182. sql = sql & " AND (m.created_at < ? OR (m.created_at = ? AND m.id < ?))"
  183. ReDim Preserve params(n + 2)
  184. params(n) = cts
  185. params(n + 1) = cts
  186. params(n + 2) = cid
  187. n = n + 3
  188. End If
  189. ' G3DB accepts at most 8 parameters (tenant + type + status + verification + 3 cursor = 7)
  190. sql = sql & " ORDER BY m.created_at DESC, m.id DESC LIMIT " & (lim + 1)
  191. Set rs = DAL().Query(sql, params)
  192. out = ""
  193. count = 0
  194. lastTs = ""
  195. lastId = ""
  196. nextCursor = "null"
  197. Do While Not rs.EOF
  198. If count >= lim Then
  199. nextCursor = JsonLite_Quote(lastTs & "|" & lastId)
  200. Exit Do
  201. End If
  202. If count > 0 Then out = out & ","
  203. out = out & MemoryJson(rs, True)
  204. lastTs = "" & rs(8)
  205. lastId = "" & rs(0)
  206. count = count + 1
  207. rs.MoveNext
  208. Loop
  209. rs.Close
  210. Api_Send 200, "{""data"":[" & out & "],""next_cursor"":" & nextCursor & "}"
  211. End Sub
  212. '---------------------------------------------------------------
  213. ' GET /api/v1/memories/:id (?revision=n)
  214. '---------------------------------------------------------------
  215. Public Sub Fetch(id)
  216. Dim rs, nsId, revParam, rev, json
  217. If Not Api_Authenticate() Then Exit Sub
  218. If Not Api_IsId(id) Then
  219. Api_NotFound
  220. Exit Sub
  221. End If
  222. ' The row is copied out and the result set closed BEFORE the permission check: a second query while a
  223. ' result set is still open hangs the request under G3DB/SQLite (script timeout).
  224. Set rs = DAL().Query(MemorySelect() & " WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId))
  225. If rs.EOF Then
  226. rs.Close
  227. Api_NotFound
  228. Exit Sub
  229. End If
  230. nsId = "" & rs(1)
  231. json = MemoryJson(rs, False)
  232. rs.Close
  233. If Not Api_CanAccessNamespace(nsId, "read") Then
  234. Api_NotFound
  235. Exit Sub
  236. End If
  237. revParam = Trim("" & Request.QueryString("revision"))
  238. If Len(revParam) = 0 Then
  239. Api_Send 200, "{""data"":" & json & "}"
  240. Exit Sub
  241. End If
  242. If Not IsNumeric(revParam) Then
  243. Api_Invalid Array("revision must be a positive integer.")
  244. Exit Sub
  245. End If
  246. rev = CLng(revParam)
  247. Set rs = DAL().Query(MemorySelectRevision() & " WHERE m.id = ? AND m.tenant_id = ?", Array(rev, id, Api_TenantId))
  248. If rs.EOF Then
  249. rs.Close
  250. Api_NotFound
  251. Exit Sub
  252. End If
  253. json = MemoryJson(rs, False)
  254. rs.Close
  255. Api_Send 200, "{""data"":" & json & "}"
  256. End Sub
  257. '---------------------------------------------------------------
  258. ' PATCH /api/v1/memories/:id creates revision n+1 (unverified)
  259. '---------------------------------------------------------------
  260. Public Sub Correct(id)
  261. Dim body, input, rs, nsId, curRev, expected, ifMatch, lifecycle
  262. Dim title, content, summary, tagsRaw, attrRaw, confidence, importance, reason, hash, ts, newRev, memType, k, resp
  263. Dim hasTitle, hasContent, hasSummary, hasTags, hasAttr, hasConf, hasImp
  264. If Not Api_Authenticate() Then Exit Sub
  265. If Not Api_IsId(id) Then
  266. Api_NotFound
  267. Exit Sub
  268. End If
  269. body = Api_ReadBody()
  270. If IsEmpty(body) Then Exit Sub
  271. Set input = JsonLite_Parse(body)
  272. 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 " & _
  273. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _
  274. "WHERE m.id = ? AND m.tenant_id = ?", Array(id, Api_TenantId))
  275. If rs.EOF Then
  276. rs.Close
  277. Api_NotFound
  278. Exit Sub
  279. End If
  280. nsId = "" & rs(0)
  281. curRev = CLng(rs(1))
  282. lifecycle = "" & rs(2)
  283. memType = "" & rs(3)
  284. title = rs(4)
  285. summary = rs(5)
  286. content = rs(6)
  287. attrRaw = rs(7)
  288. tagsRaw = rs(8)
  289. confidence = rs(9)
  290. importance = rs(10)
  291. rs.Close
  292. If Not Api_CanAccessNamespace(nsId, "write") Then
  293. Api_NotFound
  294. Exit Sub
  295. End If
  296. ' Optimistic concurrency: the caller must say which revision they edited.
  297. ifMatch = Replace(Replace(Api_Header("If-Match"), """", ""), "W/", "")
  298. expected = ifMatch
  299. If Len(expected) = 0 And input.Exists("expected_revision") Then expected = "" & input.Item("expected_revision")
  300. If Len(expected) = 0 Then
  301. Api_Error 428, "precondition_required", "Send If-Match: <current revision> (or ""expected_revision"" in the body)."
  302. Exit Sub
  303. End If
  304. If Not IsNumeric(expected) Then
  305. Api_Error 400, "invalid_revision", "If-Match / expected_revision must be a revision number."
  306. Exit Sub
  307. End If
  308. If CLng(expected) <> curRev Then
  309. Response.AddHeader "ETag", """" & curRev & """"
  310. Api_Error 412, "stale_revision", "The memory is at revision " & curRev & ", not " & CLng(expected) & ". Re-read it and retry."
  311. Exit Sub
  312. End If
  313. If lifecycle <> "active" Then
  314. Api_Error 409, "not_active", "A " & lifecycle & " memory cannot be corrected."
  315. Exit Sub
  316. End If
  317. m_errs = ""
  318. hasTitle = input.Exists("title")
  319. hasContent = input.Exists("content")
  320. hasSummary = input.Exists("summary")
  321. hasTags = input.Exists("tags") Or input.HasRaw("tags")
  322. hasAttr = input.Exists("attributes") Or input.HasRaw("attributes")
  323. hasConf = input.Exists("confidence")
  324. hasImp = input.Exists("importance")
  325. If hasTitle Then title = ReqString(input, "title", 200)
  326. If hasContent Then content = ReqString(input, "content", 100000)
  327. If hasSummary Then summary = OptString(input, "summary", 2000)
  328. If hasTags Then tagsRaw = TagsJson(input)
  329. If hasAttr Then attrRaw = AttributesJson(input)
  330. If hasConf Then confidence = OptUnit(input, "confidence")
  331. If hasImp Then importance = OptUnit(input, "importance")
  332. reason = OptString(input, "change_reason", 500)
  333. If Not (hasTitle Or hasContent Or hasSummary Or hasTags Or hasAttr Or hasConf Or hasImp) Then
  334. m_errs = m_errs & Chr(30) & "Send at least one field to change."
  335. End If
  336. If Left(m_errs, 1) = Chr(30) Then m_errs = Mid(m_errs, 2)
  337. If Len(m_errs) > 0 Then
  338. Api_Invalid Split(m_errs, Chr(30))
  339. Exit Sub
  340. End If
  341. If IsNull(reason) Or Len("" & reason) = 0 Then reason = "corrected"
  342. hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content)
  343. ts = Api_Now()
  344. newRev = curRev + 1
  345. On Error Resume Next
  346. DAL().BeginTransaction
  347. InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts
  348. Search_IndexMemory id, newRev, Api_TenantId, nsId, title, content, tagsRaw
  349. Emb_MarkPending "memory", id, Api_TenantId, nsId, newRev
  350. DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _
  351. Array(newRev, ts, id, Api_TenantId, curRev)
  352. If Err.Number <> 0 Then
  353. k = Err.Number : Api_NoteDbError
  354. DAL().RollbackTransaction
  355. Api_DbFailed k, ""
  356. Exit Sub
  357. End If
  358. DAL().CommitTransaction
  359. If Err.Number <> 0 Then
  360. k = Err.Number : Api_NoteDbError
  361. Api_DbFailed k, ""
  362. Exit Sub
  363. End If
  364. On Error GoTo 0
  365. Emb_AfterWrite Api_TenantId, 8
  366. Api_Audit "memory.correct", "memory", id, "ok"
  367. Response.AddHeader "ETag", """" & newRev & """"
  368. resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed""}"
  369. Api_Send 200, resp
  370. End Sub
  371. '---------------------------------------------------------------
  372. ' DELETE /api/v1/memories/:id
  373. '---------------------------------------------------------------
  374. Public Sub Forget(id)
  375. Dim rs, nsId, k
  376. If Not Api_Authenticate() Then Exit Sub
  377. If Not Api_IsId(id) Then
  378. Api_NotFound
  379. Exit Sub
  380. End If
  381. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  382. If rs.EOF Then
  383. rs.Close
  384. Api_NotFound
  385. Exit Sub
  386. End If
  387. nsId = "" & rs(0)
  388. rs.Close
  389. If Not Api_CanAccessNamespace(nsId, "delete") Then
  390. Api_Audit "memory.forget", "memory", id, "denied"
  391. Api_NotFound
  392. Exit Sub
  393. End If
  394. On Error Resume Next
  395. DAL().BeginTransaction
  396. Search_UnindexMemory id
  397. Emb_MarkDelete "memory", id
  398. DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id
  399. DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)
  400. If Err.Number <> 0 Then
  401. k = Err.Number : Api_NoteDbError
  402. DAL().RollbackTransaction
  403. Api_DbFailed k, ""
  404. Exit Sub
  405. End If
  406. DAL().CommitTransaction
  407. On Error GoTo 0
  408. Emb_AfterWrite Api_TenantId, 8
  409. Api_Audit "memory.forget", "memory", id, "ok"
  410. Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}"
  411. End Sub
  412. '---------------------------------------------------------------
  413. ' POST /api/v1/memories/:id/retire
  414. '---------------------------------------------------------------
  415. Public Sub Retire(id)
  416. Dim rs, nsId, k
  417. If Not Api_Authenticate() Then Exit Sub
  418. If Not Api_IsId(id) Then
  419. Api_NotFound
  420. Exit Sub
  421. End If
  422. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  423. If rs.EOF Then
  424. rs.Close
  425. Api_NotFound
  426. Exit Sub
  427. End If
  428. nsId = "" & rs(0)
  429. rs.Close
  430. If Not Api_CanAccessNamespace(nsId, "write") Then
  431. Api_NotFound
  432. Exit Sub
  433. End If
  434. On Error Resume Next
  435. DAL().Execute "UPDATE memories SET lifecycle_status = 'retired', updated_at = ? WHERE id = ? AND tenant_id = ?", Array(Api_Now(), id, Api_TenantId)
  436. If Err.Number <> 0 Then
  437. k = Err.Number : Api_NoteDbError
  438. Api_DbFailed k, ""
  439. Exit Sub
  440. End If
  441. On Error GoTo 0
  442. Api_Audit "memory.retire", "memory", id, "ok"
  443. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""retired""}"
  444. End Sub
  445. '---------------------------------------------------------------
  446. ' GET /api/v1/memories/:id/versions
  447. '---------------------------------------------------------------
  448. Public Sub Versions(id)
  449. Dim rs, nsId, out, count
  450. If Not Api_Authenticate() Then Exit Sub
  451. If Not Api_IsId(id) Then
  452. Api_NotFound
  453. Exit Sub
  454. End If
  455. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  456. If rs.EOF Then
  457. rs.Close
  458. Api_NotFound
  459. Exit Sub
  460. End If
  461. nsId = "" & rs(0)
  462. rs.Close
  463. If Not Api_CanAccessNamespace(nsId, "read") Then
  464. Api_NotFound
  465. Exit Sub
  466. End If
  467. Set rs = DAL().Query("SELECT revision, title, summary, content, tags, confidence, importance, verification_status, change_reason, created_by, created_at " & _
  468. "FROM memory_revisions WHERE memory_id = ? ORDER BY revision DESC", id)
  469. out = ""
  470. count = 0
  471. Do While Not rs.EOF
  472. If count > 0 Then out = out & ","
  473. out = out & "{""revision"":" & CLng(rs(0)) & ",""title"":" & JsonLite_Quote("" & rs(1)) & ",""summary"":" & JStr(rs(2)) & _
  474. ",""content"":" & JsonLite_Quote("" & rs(3)) & ",""tags"":" & JRaw(rs(4), "[]") & ",""confidence"":" & JNum(rs(5)) & _
  475. ",""importance"":" & JNum(rs(6)) & ",""verification_status"":" & JsonLite_Quote("" & rs(7)) & _
  476. ",""change_reason"":" & JStr(rs(8)) & ",""created_by"":" & JsonLite_Quote("" & rs(9)) & ",""created_at"":" & JsonLite_Quote("" & rs(10)) & "}"
  477. count = count + 1
  478. rs.MoveNext
  479. Loop
  480. rs.Close
  481. Api_Send 200, "{""data"":[" & out & "]}"
  482. End Sub
  483. '---------------------------------------------------------------
  484. ' POST /api/v1/memories/:id/verifications
  485. ' {"revision":n,"result":"verified|disputed|rejected","method":"...","notes":"..."} needs the "verify" (or admin) permission.
  486. ' Verification belongs to exactly one revision: it must be the current one.
  487. '---------------------------------------------------------------
  488. Public Sub Verify(id)
  489. Dim body, input, rs, nsId, curRev, rev, result, method, notes, k, ts
  490. If Not Api_Authenticate() Then Exit Sub
  491. If Not Api_IsId(id) Then
  492. Api_NotFound
  493. Exit Sub
  494. End If
  495. body = Api_ReadBody()
  496. If IsEmpty(body) Then Exit Sub
  497. Set input = JsonLite_Parse(body)
  498. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  499. If rs.EOF Then
  500. rs.Close
  501. Api_NotFound
  502. Exit Sub
  503. End If
  504. nsId = "" & rs(0)
  505. curRev = CLng(rs(1))
  506. rs.Close
  507. If Not Api_CanAccessNamespace(nsId, "verify") Then
  508. Api_Audit "memory.verify", "memory", id, "denied"
  509. Api_NotFound
  510. Exit Sub
  511. End If
  512. m_errs = ""
  513. result = LCase("" & ReqString(input, "result", 20))
  514. method = ReqString(input, "method", 200)
  515. notes = OptString(input, "notes", 2000)
  516. If Not input.Exists("revision") Then
  517. AddErr "revision is required."
  518. ElseIf VarType(input.Item("revision")) <> vbDouble Then
  519. AddErr "revision must be a number."
  520. Else
  521. rev = CLng(input.Item("revision"))
  522. End If
  523. If result <> "verified" And result <> "disputed" And result <> "rejected" And Len(m_errs) = 0 Then
  524. AddErr "result must be verified, disputed or rejected."
  525. End If
  526. If Len(m_errs) > 0 Then
  527. Api_Invalid Split(m_errs, Chr(30))
  528. Exit Sub
  529. End If
  530. If rev <> curRev Then
  531. Api_Error 409, "not_current_revision", "Only the current revision (" & curRev & ") can be verified; revision " & rev & " was given."
  532. Exit Sub
  533. End If
  534. ts = Api_Now()
  535. On Error Resume Next
  536. DAL().BeginTransaction
  537. DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  538. Array(Api_NewId(), id, rev, method, result, notes, Api_PrincipalId, ts)
  539. DAL().Execute "UPDATE memory_revisions SET verification_status = ? WHERE memory_id = ? AND revision = ?", Array(result, id, rev)
  540. If Err.Number <> 0 Then
  541. k = Err.Number : Api_NoteDbError
  542. DAL().RollbackTransaction
  543. Api_DbFailed k, ""
  544. Exit Sub
  545. End If
  546. DAL().CommitTransaction
  547. On Error GoTo 0
  548. Api_Audit "memory.verify", "memory", id, result
  549. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(result) & "}"
  550. End Sub
  551. '---------------------------------------------------------------
  552. ' POST /api/v1/recall
  553. ' {"query","types":[],"namespace_ids":[],"verification_filter":"verified_only|include_unverified","max_results","detail_level":"full|summary"}
  554. ' Hybrid retrieval (FTS5/bm25 fused with vector similarity when configured, see core/lib.Embeddings.asp) over
  555. ' active memories the caller can read. Trusted retrieval is the default, so
  556. ' unverified memories are left out unless asked for (they are labelled when included).
  557. '---------------------------------------------------------------
  558. Public Sub Recall()
  559. Dim body, input, query, fts, maxResults, detail, vf, allowed, requested, typesSql, ids(), scores(), n, rs, i, j, idList, sql
  560. Dim rowJson(), out, count, excluded, now_, v, st, params, warnings, ranker
  561. If Not Api_Authenticate() Then Exit Sub
  562. body = Api_ReadBody()
  563. If IsEmpty(body) Then Exit Sub
  564. Set input = JsonLite_Parse(body)
  565. m_errs = ""
  566. query = ReqString(input, "query", 1000)
  567. maxResults = 10
  568. If input.Exists("max_results") Then
  569. If VarType(input.Item("max_results")) = vbDouble Then
  570. maxResults = CLng(input.Item("max_results"))
  571. If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50."
  572. Else
  573. AddErr "max_results must be a number."
  574. End If
  575. End If
  576. detail = OptString(input, "detail_level", 20)
  577. If IsNull(detail) Then detail = "full"
  578. detail = LCase(detail)
  579. If detail <> "full" And detail <> "summary" Then AddErr "detail_level must be full or summary."
  580. vf = OptString(input, "verification_filter", 30)
  581. If IsNull(vf) Then vf = "verified_only"
  582. vf = LCase(vf)
  583. If vf <> "verified_only" And vf <> "include_unverified" Then AddErr "verification_filter must be verified_only or include_unverified."
  584. typesSql = TypeListSql(input, "types")
  585. requested = IdListSql(input, "namespace_ids")
  586. If Len(m_errs) > 0 Then
  587. Api_Invalid Split(m_errs, Chr(30))
  588. Exit Sub
  589. End If
  590. fts = Search_FtsQuery(query)
  591. If Len(fts) = 0 Then
  592. Api_Invalid Array("query must contain at least one word.")
  593. Exit Sub
  594. End If
  595. allowed = Api_AllowedNamespaceIds("read")
  596. If Len(allowed) > 0 And Len(requested) > 0 Then allowed = IntersectIds(allowed, requested)
  597. warnings = "[""semantic retrieval is not configured; results are lexical only""]"
  598. If Len(allowed) = 0 Then
  599. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""results"":[],""warnings"":" & warnings & "}"
  600. Exit Sub
  601. End If
  602. ' Lexical + (when configured) semantic candidates, fused; scores are negated here to match the output below
  603. Set ranker = New Ranker_Class
  604. ranker.Run "memory", fts, query, Api_TenantId, allowed
  605. n = ranker.Count
  606. If n > 0 Then
  607. ReDim ids(n - 1)
  608. ReDim scores(n - 1)
  609. For i = 0 To n - 1
  610. ids(i) = ranker.IdAt(i)
  611. scores(i) = -ranker.ScoreAt(i)
  612. Next
  613. End If
  614. warnings = ""
  615. If Len(ranker.Warning) > 0 Then
  616. warnings = JsonLite_Quote(ranker.Warning)
  617. End If
  618. out = ""
  619. count = 0
  620. excluded = 0
  621. If n > 0 Then
  622. idList = ""
  623. For i = 0 To n - 1
  624. If Api_IsId(ids(i)) Then
  625. If Len(idList) > 0 Then idList = idList & ","
  626. idList = idList & "'" & ids(i) & "'"
  627. End If
  628. Next
  629. now_ = Api_Now()
  630. sql = MemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
  631. "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?)"
  632. If Len(typesSql) > 0 Then sql = sql & " AND m.type IN (" & typesSql & ")"
  633. Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
  634. ReDim rowJson(n - 1)
  635. Do While Not rs.EOF
  636. st = "" & rs(18)
  637. If vf = "verified_only" And st <> "verified" Then
  638. excluded = excluded + 1
  639. Else
  640. For j = 0 To n - 1
  641. If ids(j) = "" & rs(0) Then
  642. v = MemoryJson(rs, (detail = "summary"))
  643. If detail = "summary" Then v = SummaryOnly(v, rs)
  644. rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j))) & "}"
  645. Exit For
  646. End If
  647. Next
  648. End If
  649. rs.MoveNext
  650. Loop
  651. rs.Close
  652. For j = 0 To n - 1
  653. If Len("" & rowJson(j)) > 0 Then
  654. If count >= maxResults Then Exit For
  655. If count > 0 Then out = out & ","
  656. out = out & rowJson(j)
  657. count = count + 1
  658. End If
  659. Next
  660. End If
  661. If excluded > 0 Then
  662. If Len(warnings) > 0 Then
  663. warnings = warnings & ","
  664. End If
  665. warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them"""
  666. End If
  667. Api_Audit "memory.recall", "search", "", "ok"
  668. Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}"
  669. End Sub
  670. '===============================================================
  671. ' Helpers
  672. '===============================================================
  673. ' Memory + current revision. Column order is relied on by MemoryJson:
  674. ' 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,
  675. ' 10 revision, 11 title, 12 summary, 13 content, 14 attributes, 15 tags, 16 confidence, 17 importance, 18 verification_status, 19 change_reason
  676. Private Function MemorySelect()
  677. 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, " & _
  678. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  679. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
  680. End Function
  681. ' Same columns but a specific revision (first parameter is the revision number)
  682. Private Function MemorySelectRevision()
  683. 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, " & _
  684. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  685. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = ?"
  686. End Function
  687. Private Function MemoryJson(rs, brief)
  688. Dim s
  689. s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  690. ",""status"":" & JsonLite_Quote("" & rs(4)) & ",""current_revision"":" & CLng(rs(3)) & ",""revision"":" & CLng(rs(10)) & _
  691. ",""verification_status"":" & JsonLite_Quote("" & rs(18)) & ",""title"":" & JsonLite_Quote("" & rs(11)) & ",""summary"":" & JStr(rs(12))
  692. If Not brief Then
  693. s = s & ",""content"":" & JsonLite_Quote("" & rs(13)) & ",""attributes"":" & JRaw(rs(14), "null") & ",""change_reason"":" & JStr(rs(19)) & _
  694. ",""valid_from"":" & JStr(rs(5)) & ",""valid_until"":" & JStr(rs(6)) & ",""created_by"":" & JsonLite_Quote("" & rs(7))
  695. End If
  696. s = s & ",""tags"":" & JRaw(rs(15), "[]") & ",""confidence"":" & JNum(rs(16)) & ",""importance"":" & JNum(rs(17)) & _
  697. ",""created_at"":" & JsonLite_Quote("" & rs(8)) & ",""updated_at"":" & JsonLite_Quote("" & rs(9)) & "}"
  698. MemoryJson = s
  699. End Function
  700. Private Function JStr(v)
  701. If IsNull(v) Then
  702. JStr = "null"
  703. Else
  704. JStr = JsonLite_Quote("" & v)
  705. End If
  706. End Function
  707. Private Function JNum(v)
  708. If IsNull(v) Then
  709. JNum = "null"
  710. ElseIf Len("" & v) = 0 Then
  711. JNum = "null"
  712. Else
  713. JNum = JsonLite_Num(v)
  714. End If
  715. End Function
  716. ' Stored raw JSON text (validated on the way in) or a default
  717. Private Function JRaw(v, dflt)
  718. If IsNull(v) Then
  719. JRaw = dflt
  720. ElseIf Len("" & v) = 0 Then
  721. JRaw = dflt
  722. Else
  723. JRaw = "" & v
  724. End If
  725. End Function
  726. Private Sub AddErr(msg)
  727. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  728. m_errs = m_errs & msg
  729. End Sub
  730. Private Function ReqString(input, name, maxLen)
  731. Dim v
  732. ReqString = ""
  733. If Not input.Exists(name) Then
  734. AddErr name & " is required."
  735. Exit Function
  736. End If
  737. v = input.Item(name)
  738. If IsNull(v) Then
  739. AddErr name & " is required."
  740. Exit Function
  741. End If
  742. If VarType(v) <> vbString Then
  743. AddErr name & " must be a string."
  744. Exit Function
  745. End If
  746. v = Trim(v)
  747. If Len(v) = 0 Then
  748. AddErr name & " must not be empty."
  749. Exit Function
  750. End If
  751. If Len(v) > maxLen Then
  752. AddErr name & " must be at most " & maxLen & " characters."
  753. Exit Function
  754. End If
  755. ReqString = v
  756. End Function
  757. ' Optional string: Null when absent or null
  758. Private Function OptString(input, name, maxLen)
  759. Dim v
  760. OptString = Null
  761. If Not input.Exists(name) Then Exit Function
  762. v = input.Item(name)
  763. If IsNull(v) Then Exit Function
  764. If VarType(v) <> vbString Then
  765. AddErr name & " must be a string."
  766. Exit Function
  767. End If
  768. If Len(v) > maxLen Then
  769. AddErr name & " must be at most " & maxLen & " characters."
  770. Exit Function
  771. End If
  772. OptString = v
  773. End Function
  774. ' Optional number in 0..1: Null when absent or null
  775. Private Function OptUnit(input, name)
  776. Dim v
  777. OptUnit = Null
  778. If Not input.Exists(name) Then Exit Function
  779. v = input.Item(name)
  780. If IsNull(v) Then Exit Function
  781. If VarType(v) <> vbDouble Then
  782. AddErr name & " must be a number between 0 and 1."
  783. Exit Function
  784. End If
  785. If v < 0 Or v > 1 Then
  786. AddErr name & " must be between 0 and 1."
  787. Exit Function
  788. End If
  789. OptUnit = v
  790. End Function
  791. ' tags: optional array of non-empty strings; returns compact JSON text or Null
  792. Private Function TagsJson(input)
  793. Dim arr, i, out, t
  794. TagsJson = Null
  795. If Not input.HasRaw("tags") Then
  796. If input.Exists("tags") Then
  797. If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings."
  798. End If
  799. Exit Function
  800. End If
  801. arr = JsonLite_ParseStringArray(input.Raw("tags"))
  802. If IsNull(arr) Then
  803. AddErr "tags must be an array of strings."
  804. Exit Function
  805. End If
  806. If UBound(arr) > 31 Then
  807. AddErr "tags may contain at most 32 entries."
  808. Exit Function
  809. End If
  810. out = ""
  811. For i = 0 To UBound(arr)
  812. t = Trim(arr(i))
  813. If Len(t) = 0 Or Len(t) > 64 Then
  814. AddErr "each tag must be 1 to 64 characters."
  815. Exit Function
  816. End If
  817. If i > 0 Then out = out & ","
  818. out = out & JsonLite_Quote(t)
  819. Next
  820. TagsJson = "[" & out & "]"
  821. End Function
  822. ' attributes: optional JSON object, stored as its raw text (max 16 KB) or Null
  823. Private Function AttributesJson(input)
  824. Dim raw
  825. AttributesJson = Null
  826. If Not input.HasRaw("attributes") Then
  827. If input.Exists("attributes") Then
  828. If Not IsNull(input.Item("attributes")) Then AddErr "attributes must be a JSON object."
  829. End If
  830. Exit Function
  831. End If
  832. raw = input.Raw("attributes")
  833. If Left(raw, 1) <> "{" Then
  834. AddErr "attributes must be a JSON object."
  835. Exit Function
  836. End If
  837. If Len(raw) > 16384 Then
  838. AddErr "attributes must be at most 16 KB."
  839. Exit Function
  840. End If
  841. AttributesJson = raw
  842. End Function
  843. ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps (same transaction).
  844. Private Sub InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
  845. DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
  846. "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
  847. DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
  848. Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
  849. End Sub
  850. ' summary detail: replace the (omitted) body with the stored summary, or the first 240 characters of the content
  851. Private Function SummaryOnly(json, rs)
  852. Dim sm
  853. If IsNull(rs(12)) Then
  854. sm = "" & rs(13)
  855. If Len(sm) > 240 Then sm = Left(sm, 240) & "..."
  856. Else
  857. sm = "" & rs(12)
  858. End If
  859. SummaryOnly = Left(json, Len(json) - 1) & ",""snippet"":" & JsonLite_Quote(sm) & "}"
  860. End Function
  861. ' "'a','b'" for an optional array of memory type codes (letters only); "" when absent
  862. Private Function TypeListSql(input, name)
  863. Dim arr, i, out, c, j, t
  864. TypeListSql = ""
  865. If Not input.HasRaw(name) Then
  866. If input.Exists(name) Then
  867. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of type codes."
  868. End If
  869. Exit Function
  870. End If
  871. arr = JsonLite_ParseStringArray(input.Raw(name))
  872. If IsNull(arr) Then
  873. AddErr name & " must be an array of type codes."
  874. Exit Function
  875. End If
  876. out = ""
  877. For i = 0 To UBound(arr)
  878. t = LCase(Trim(arr(i)))
  879. If Len(t) = 0 Or Len(t) > 40 Then
  880. AddErr name & " contains an invalid type."
  881. Exit Function
  882. End If
  883. For j = 1 To Len(t)
  884. c = Mid(t, j, 1)
  885. If c < "a" Or c > "z" Then
  886. AddErr name & " contains an invalid type."
  887. Exit Function
  888. End If
  889. Next
  890. If Len(out) > 0 Then out = out & ","
  891. out = out & "'" & t & "'"
  892. Next
  893. TypeListSql = out
  894. End Function
  895. Private Function IdListSql(input, name)
  896. Dim arr, i, out
  897. IdListSql = ""
  898. If Not input.HasRaw(name) Then
  899. If input.Exists(name) Then
  900. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids."
  901. End If
  902. Exit Function
  903. End If
  904. arr = JsonLite_ParseStringArray(input.Raw(name))
  905. If IsNull(arr) Then
  906. AddErr name & " must be an array of ids."
  907. Exit Function
  908. End If
  909. out = ""
  910. For i = 0 To UBound(arr)
  911. If Not Api_IsId(arr(i)) Then
  912. AddErr name & " must contain valid ids."
  913. Exit Function
  914. End If
  915. If Len(out) > 0 Then out = out & ","
  916. out = out & "'" & arr(i) & "'"
  917. Next
  918. If Len(out) = 0 Then AddErr name & " must not be empty when given."
  919. IdListSql = out
  920. End Function
  921. Private Function IntersectIds(allowed, requested)
  922. Dim a, i, out
  923. a = Split(allowed, ",")
  924. out = ""
  925. For i = 0 To UBound(a)
  926. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  927. If Len(out) > 0 Then out = out & ","
  928. out = out & a(i)
  929. End If
  930. Next
  931. IntersectIds = out
  932. End Function
  933. Private Sub StoreIdem(idemKey, reqHash, status, resp)
  934. Api_IdempotencyStore idemKey, reqHash, status, resp
  935. End Sub
  936. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  937. Public Sub Invoke(actionName, args)
  938. Select Case LCase(actionName)
  939. Case "remember" : Remember
  940. Case "recent" : Recent
  941. Case "fetch" : Fetch args(0)
  942. Case "correct" : Correct args(0)
  943. Case "forget" : Forget args(0)
  944. Case "retire" : Retire args(0)
  945. Case "versions" : Versions args(0)
  946. Case "verify" : Verify args(0)
  947. Case "recall" : Recall
  948. Case Else
  949. Err.Raise 438, "ApiMemoriesController_Class", "Action '" & actionName & "' not found"
  950. End Select
  951. End Sub
  952. End Class
  953. Dim ApiMemoriesController_Class__Singleton
  954. Function ApiMemoriesController()
  955. If IsEmpty(ApiMemoriesController_Class__Singleton) Then
  956. Set ApiMemoriesController_Class__Singleton = New ApiMemoriesController_Class
  957. End If
  958. Set ApiMemoriesController = ApiMemoriesController_Class__Singleton
  959. End Function
  960. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  961. Sub ApiMemoriesController_Invoke(actionName, args)
  962. ApiMemoriesController().Invoke actionName, args
  963. End Sub
  964. %>

Powered by TurnKey Linux.