Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1066 рядки
43KB

  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. Mem_ForgetLinked id
  399. DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id
  400. DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)
  401. If Err.Number <> 0 Then
  402. k = Err.Number : Api_NoteDbError
  403. DAL().RollbackTransaction
  404. Api_DbFailed k, ""
  405. Exit Sub
  406. End If
  407. DAL().CommitTransaction
  408. On Error GoTo 0
  409. Emb_AfterWrite Api_TenantId, 8
  410. Api_Audit "memory.forget", "memory", id, "ok"
  411. Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}"
  412. End Sub
  413. '---------------------------------------------------------------
  414. ' POST /api/v1/memories/:id/retire
  415. '---------------------------------------------------------------
  416. Public Sub Retire(id)
  417. Dim rs, nsId, k
  418. If Not Api_Authenticate() Then Exit Sub
  419. If Not Api_IsId(id) Then
  420. Api_NotFound
  421. Exit Sub
  422. End If
  423. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  424. If rs.EOF Then
  425. rs.Close
  426. Api_NotFound
  427. Exit Sub
  428. End If
  429. nsId = "" & rs(0)
  430. rs.Close
  431. If Not Api_CanAccessNamespace(nsId, "write") Then
  432. Api_NotFound
  433. Exit Sub
  434. End If
  435. On Error Resume Next
  436. DAL().Execute "UPDATE memories SET lifecycle_status = 'retired', updated_at = ? WHERE id = ? AND tenant_id = ?", Array(Api_Now(), id, Api_TenantId)
  437. If Err.Number <> 0 Then
  438. k = Err.Number : Api_NoteDbError
  439. Api_DbFailed k, ""
  440. Exit Sub
  441. End If
  442. On Error GoTo 0
  443. Api_Audit "memory.retire", "memory", id, "ok"
  444. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""status"":""retired""}"
  445. End Sub
  446. '---------------------------------------------------------------
  447. ' GET /api/v1/memories/:id/versions
  448. '---------------------------------------------------------------
  449. Public Sub Versions(id)
  450. Dim rs, nsId, out, count
  451. If Not Api_Authenticate() Then Exit Sub
  452. If Not Api_IsId(id) Then
  453. Api_NotFound
  454. Exit Sub
  455. End If
  456. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  457. If rs.EOF Then
  458. rs.Close
  459. Api_NotFound
  460. Exit Sub
  461. End If
  462. nsId = "" & rs(0)
  463. rs.Close
  464. If Not Api_CanAccessNamespace(nsId, "read") Then
  465. Api_NotFound
  466. Exit Sub
  467. End If
  468. Set rs = DAL().Query("SELECT revision, title, summary, content, tags, confidence, importance, verification_status, change_reason, created_by, created_at " & _
  469. "FROM memory_revisions WHERE memory_id = ? ORDER BY revision DESC", id)
  470. out = ""
  471. count = 0
  472. Do While Not rs.EOF
  473. If count > 0 Then out = out & ","
  474. out = out & "{""revision"":" & CLng(rs(0)) & ",""title"":" & JsonLite_Quote("" & rs(1)) & ",""summary"":" & JStr(rs(2)) & _
  475. ",""content"":" & JsonLite_Quote("" & rs(3)) & ",""tags"":" & JRaw(rs(4), "[]") & ",""confidence"":" & JNum(rs(5)) & _
  476. ",""importance"":" & JNum(rs(6)) & ",""verification_status"":" & JsonLite_Quote("" & rs(7)) & _
  477. ",""change_reason"":" & JStr(rs(8)) & ",""created_by"":" & JsonLite_Quote("" & rs(9)) & ",""created_at"":" & JsonLite_Quote("" & rs(10)) & "}"
  478. count = count + 1
  479. rs.MoveNext
  480. Loop
  481. rs.Close
  482. Api_Send 200, "{""data"":[" & out & "]}"
  483. End Sub
  484. '---------------------------------------------------------------
  485. ' POST /api/v1/memories/:id/verifications
  486. ' {"revision":n,"result":"verified|disputed|rejected","method":"...","notes":"..."} needs the "verify" (or admin) permission.
  487. ' Verification belongs to exactly one revision: it must be the current one.
  488. '---------------------------------------------------------------
  489. Public Sub Verify(id)
  490. Dim body, input, rs, nsId, curRev, rev, result, method, notes, k, ts
  491. If Not Api_Authenticate() Then Exit Sub
  492. If Not Api_IsId(id) Then
  493. Api_NotFound
  494. Exit Sub
  495. End If
  496. body = Api_ReadBody()
  497. If IsEmpty(body) Then Exit Sub
  498. Set input = JsonLite_Parse(body)
  499. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  500. If rs.EOF Then
  501. rs.Close
  502. Api_NotFound
  503. Exit Sub
  504. End If
  505. nsId = "" & rs(0)
  506. curRev = CLng(rs(1))
  507. rs.Close
  508. If Not Api_CanAccessNamespace(nsId, "verify") Then
  509. Api_Audit "memory.verify", "memory", id, "denied"
  510. Api_NotFound
  511. Exit Sub
  512. End If
  513. m_errs = ""
  514. result = LCase("" & ReqString(input, "result", 20))
  515. method = ReqString(input, "method", 200)
  516. notes = OptString(input, "notes", 2000)
  517. If Not input.Exists("revision") Then
  518. AddErr "revision is required."
  519. ElseIf VarType(input.Item("revision")) <> vbDouble Then
  520. AddErr "revision must be a number."
  521. Else
  522. rev = CLng(input.Item("revision"))
  523. End If
  524. If result <> "verified" And result <> "disputed" And result <> "rejected" And Len(m_errs) = 0 Then
  525. AddErr "result must be verified, disputed or rejected."
  526. End If
  527. If Len(m_errs) > 0 Then
  528. Api_Invalid Split(m_errs, Chr(30))
  529. Exit Sub
  530. End If
  531. If rev <> curRev Then
  532. Api_Error 409, "not_current_revision", "Only the current revision (" & curRev & ") can be verified; revision " & rev & " was given."
  533. Exit Sub
  534. End If
  535. ts = Api_Now()
  536. On Error Resume Next
  537. DAL().BeginTransaction
  538. DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  539. Array(Api_NewId(), id, rev, method, result, notes, Api_PrincipalId, ts)
  540. DAL().Execute "UPDATE memory_revisions SET verification_status = ? WHERE memory_id = ? AND revision = ?", Array(result, id, rev)
  541. If Err.Number <> 0 Then
  542. k = Err.Number : Api_NoteDbError
  543. DAL().RollbackTransaction
  544. Api_DbFailed k, ""
  545. Exit Sub
  546. End If
  547. DAL().CommitTransaction
  548. On Error GoTo 0
  549. Api_Audit "memory.verify", "memory", id, result
  550. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(result) & "}"
  551. End Sub
  552. '---------------------------------------------------------------
  553. ' POST /api/v1/recall
  554. ' {"query","types":[],"namespace_ids":[],"verification_filter":"verified_only|include_unverified","max_results","detail_level":"full|summary"}
  555. ' Hybrid retrieval (FTS5/bm25 fused with vector similarity when configured, see core/lib.Embeddings.asp) over
  556. ' active memories the caller can read. Trusted retrieval is the default, so
  557. ' unverified memories are left out unless asked for (they are labelled when included).
  558. '---------------------------------------------------------------
  559. Public Sub Recall()
  560. Dim body, input, query, fts, maxResults, detail, vf, allowed, requested, typesSql, ids(), scores(), n, rs, i, j, idList, sql
  561. Dim rowJson(), out, count, excluded, now_, v, st, params, warnings, ranker, revs(), qid, spec, t0
  562. t0 = Timer
  563. If Not Api_Authenticate() Then Exit Sub
  564. body = Api_ReadBody()
  565. If IsEmpty(body) Then Exit Sub
  566. Set input = JsonLite_Parse(body)
  567. m_errs = ""
  568. query = ReqString(input, "query", 1000)
  569. maxResults = 10
  570. If input.Exists("max_results") Then
  571. If VarType(input.Item("max_results")) = vbDouble Then
  572. maxResults = CLng(input.Item("max_results"))
  573. If maxResults < 1 Or maxResults > 50 Then AddErr "max_results must be between 1 and 50."
  574. Else
  575. AddErr "max_results must be a number."
  576. End If
  577. End If
  578. detail = OptString(input, "detail_level", 20)
  579. If IsNull(detail) Then detail = "full"
  580. detail = LCase(detail)
  581. If detail <> "full" And detail <> "summary" Then AddErr "detail_level must be full or summary."
  582. vf = OptString(input, "verification_filter", 30)
  583. If IsNull(vf) Then vf = "verified_only"
  584. vf = LCase(vf)
  585. If vf <> "verified_only" And vf <> "include_unverified" Then AddErr "verification_filter must be verified_only or include_unverified."
  586. typesSql = TypeListSql(input, "types")
  587. requested = IdListSql(input, "namespace_ids")
  588. If Len(m_errs) > 0 Then
  589. Api_Invalid Split(m_errs, Chr(30))
  590. Exit Sub
  591. End If
  592. fts = Search_FtsQuery(query)
  593. If Len(fts) = 0 Then
  594. Api_Invalid Array("query must contain at least one word.")
  595. Exit Sub
  596. End If
  597. allowed = Api_AllowedNamespaceIds("read")
  598. If Len(allowed) > 0 And Len(requested) > 0 Then allowed = IntersectIds(allowed, requested)
  599. warnings = "[""semantic retrieval is not configured; results are lexical only""]"
  600. qid = Tel_NewQueryId()
  601. spec = ""
  602. If Len(allowed) = 0 Then
  603. Tel_Record qid, "recall", "lexical", query, spec, t0
  604. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":""lexical"",""results"":[],""warnings"":" & warnings & "}"
  605. Exit Sub
  606. End If
  607. ' Lexical + (when configured) semantic candidates, fused; scores are negated here to match the output below
  608. Set ranker = New Ranker_Class
  609. ranker.Run "memory", fts, query, Api_TenantId, allowed
  610. n = ranker.Count
  611. If n > 0 Then
  612. ReDim ids(n - 1)
  613. ReDim scores(n - 1)
  614. For i = 0 To n - 1
  615. ids(i) = ranker.IdAt(i)
  616. scores(i) = -ranker.ScoreAt(i)
  617. Next
  618. End If
  619. warnings = ""
  620. If Len(ranker.Warning) > 0 Then
  621. warnings = JsonLite_Quote(ranker.Warning)
  622. End If
  623. out = ""
  624. count = 0
  625. excluded = 0
  626. If n > 0 Then
  627. idList = ""
  628. For i = 0 To n - 1
  629. If Api_IsId(ids(i)) Then
  630. If Len(idList) > 0 Then idList = idList & ","
  631. idList = idList & "'" & ids(i) & "'"
  632. End If
  633. Next
  634. now_ = Api_Now()
  635. sql = MemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
  636. "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?)"
  637. If Len(typesSql) > 0 Then sql = sql & " AND m.type IN (" & typesSql & ")"
  638. Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
  639. ReDim rowJson(n - 1)
  640. ReDim revs(n - 1)
  641. Do While Not rs.EOF
  642. st = "" & rs(18)
  643. If vf = "verified_only" And st <> "verified" Then
  644. excluded = excluded + 1
  645. Else
  646. For j = 0 To n - 1
  647. If ids(j) = "" & rs(0) Then
  648. v = MemoryJson(rs, (detail = "summary"))
  649. If detail = "summary" Then v = SummaryOnly(v, rs)
  650. rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j)))
  651. If Len(ranker.FeedbackAt(j)) > 0 Then
  652. rowJson(j) = rowJson(j) & ",""feedback"":" & ranker.FeedbackAt(j)
  653. End If
  654. rowJson(j) = rowJson(j) & "}"
  655. revs(j) = CLng(rs(10))
  656. Exit For
  657. End If
  658. Next
  659. End If
  660. rs.MoveNext
  661. Loop
  662. rs.Close
  663. For j = 0 To n - 1
  664. If Len("" & rowJson(j)) > 0 Then
  665. If count >= maxResults Then Exit For
  666. If count > 0 Then out = out & ","
  667. out = out & rowJson(j)
  668. count = count + 1
  669. Tel_AddResult spec, "memory", ids(j), revs(j), -CDbl(scores(j))
  670. End If
  671. Next
  672. End If
  673. If excluded > 0 Then
  674. If Len(warnings) > 0 Then
  675. warnings = warnings & ","
  676. End If
  677. warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them"""
  678. End If
  679. If ranker.Demoted > 0 Then
  680. If Len(warnings) > 0 Then
  681. warnings = warnings & ","
  682. End If
  683. warnings = warnings & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback on their current revision")
  684. End If
  685. Tel_Record qid, "recall", ranker.Strategy, query, spec, t0
  686. Api_Audit "memory.recall", "search", "", "ok"
  687. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}"
  688. End Sub
  689. '===============================================================
  690. ' Helpers
  691. '===============================================================
  692. ' Memory + current revision. Column order is relied on by MemoryJson:
  693. ' 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,
  694. ' 10 revision, 11 title, 12 summary, 13 content, 14 attributes, 15 tags, 16 confidence, 17 importance, 18 verification_status, 19 change_reason
  695. Private Function MemorySelect()
  696. 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, " & _
  697. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  698. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
  699. End Function
  700. ' Same columns but a specific revision (first parameter is the revision number)
  701. Private Function MemorySelectRevision()
  702. 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, " & _
  703. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  704. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = ?"
  705. End Function
  706. Private Function MemoryJson(rs, brief)
  707. Dim s
  708. s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  709. ",""status"":" & JsonLite_Quote("" & rs(4)) & ",""current_revision"":" & CLng(rs(3)) & ",""revision"":" & CLng(rs(10)) & _
  710. ",""verification_status"":" & JsonLite_Quote("" & rs(18)) & ",""title"":" & JsonLite_Quote("" & rs(11)) & ",""summary"":" & JStr(rs(12))
  711. If Not brief Then
  712. s = s & ",""content"":" & JsonLite_Quote("" & rs(13)) & ",""attributes"":" & JRaw(rs(14), "null") & ",""change_reason"":" & JStr(rs(19)) & _
  713. ",""valid_from"":" & JStr(rs(5)) & ",""valid_until"":" & JStr(rs(6)) & ",""created_by"":" & JsonLite_Quote("" & rs(7))
  714. End If
  715. s = s & ",""tags"":" & JRaw(rs(15), "[]") & ",""confidence"":" & JNum(rs(16)) & ",""importance"":" & JNum(rs(17)) & _
  716. ",""created_at"":" & JsonLite_Quote("" & rs(8)) & ",""updated_at"":" & JsonLite_Quote("" & rs(9)) & "}"
  717. MemoryJson = s
  718. End Function
  719. Private Function JStr(v)
  720. If IsNull(v) Then
  721. JStr = "null"
  722. Else
  723. JStr = JsonLite_Quote("" & v)
  724. End If
  725. End Function
  726. Private Function JNum(v)
  727. If IsNull(v) Then
  728. JNum = "null"
  729. ElseIf Len("" & v) = 0 Then
  730. JNum = "null"
  731. Else
  732. JNum = JsonLite_Num(v)
  733. End If
  734. End Function
  735. ' Stored raw JSON text (validated on the way in) or a default
  736. Private Function JRaw(v, dflt)
  737. If IsNull(v) Then
  738. JRaw = dflt
  739. ElseIf Len("" & v) = 0 Then
  740. JRaw = dflt
  741. Else
  742. JRaw = "" & v
  743. End If
  744. End Function
  745. Private Sub AddErr(msg)
  746. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  747. m_errs = m_errs & msg
  748. End Sub
  749. Private Function ReqString(input, name, maxLen)
  750. Dim v
  751. ReqString = ""
  752. If Not input.Exists(name) Then
  753. AddErr name & " is required."
  754. Exit Function
  755. End If
  756. v = input.Item(name)
  757. If IsNull(v) Then
  758. AddErr name & " is required."
  759. Exit Function
  760. End If
  761. If VarType(v) <> vbString Then
  762. AddErr name & " must be a string."
  763. Exit Function
  764. End If
  765. v = Trim(v)
  766. If Len(v) = 0 Then
  767. AddErr name & " must not be empty."
  768. Exit Function
  769. End If
  770. If Len(v) > maxLen Then
  771. AddErr name & " must be at most " & maxLen & " characters."
  772. Exit Function
  773. End If
  774. ReqString = v
  775. End Function
  776. ' Optional string: Null when absent or null
  777. Private Function OptString(input, name, maxLen)
  778. Dim v
  779. OptString = Null
  780. If Not input.Exists(name) Then Exit Function
  781. v = input.Item(name)
  782. If IsNull(v) Then Exit Function
  783. If VarType(v) <> vbString Then
  784. AddErr name & " must be a string."
  785. Exit Function
  786. End If
  787. If Len(v) > maxLen Then
  788. AddErr name & " must be at most " & maxLen & " characters."
  789. Exit Function
  790. End If
  791. OptString = v
  792. End Function
  793. ' Optional number in 0..1: Null when absent or null
  794. Private Function OptUnit(input, name)
  795. Dim v
  796. OptUnit = Null
  797. If Not input.Exists(name) Then Exit Function
  798. v = input.Item(name)
  799. If IsNull(v) Then Exit Function
  800. If VarType(v) <> vbDouble Then
  801. AddErr name & " must be a number between 0 and 1."
  802. Exit Function
  803. End If
  804. If v < 0 Or v > 1 Then
  805. AddErr name & " must be between 0 and 1."
  806. Exit Function
  807. End If
  808. OptUnit = v
  809. End Function
  810. ' tags: optional array of non-empty strings; returns compact JSON text or Null
  811. Private Function TagsJson(input)
  812. Dim arr, i, out, t
  813. TagsJson = Null
  814. If Not input.HasRaw("tags") Then
  815. If input.Exists("tags") Then
  816. If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings."
  817. End If
  818. Exit Function
  819. End If
  820. arr = JsonLite_ParseStringArray(input.Raw("tags"))
  821. If IsNull(arr) Then
  822. AddErr "tags must be an array of strings."
  823. Exit Function
  824. End If
  825. If UBound(arr) > 31 Then
  826. AddErr "tags may contain at most 32 entries."
  827. Exit Function
  828. End If
  829. out = ""
  830. For i = 0 To UBound(arr)
  831. t = Trim(arr(i))
  832. If Len(t) = 0 Or Len(t) > 64 Then
  833. AddErr "each tag must be 1 to 64 characters."
  834. Exit Function
  835. End If
  836. If i > 0 Then out = out & ","
  837. out = out & JsonLite_Quote(t)
  838. Next
  839. TagsJson = "[" & out & "]"
  840. End Function
  841. ' attributes: optional JSON object, stored as its raw text (max 16 KB) or Null
  842. Private Function AttributesJson(input)
  843. Dim raw
  844. AttributesJson = Null
  845. If Not input.HasRaw("attributes") Then
  846. If input.Exists("attributes") Then
  847. If Not IsNull(input.Item("attributes")) Then AddErr "attributes must be a JSON object."
  848. End If
  849. Exit Function
  850. End If
  851. raw = input.Raw("attributes")
  852. If Left(raw, 1) <> "{" Then
  853. AddErr "attributes must be a JSON object."
  854. Exit Function
  855. End If
  856. If Len(raw) > 16384 Then
  857. AddErr "attributes must be at most 16 KB."
  858. Exit Function
  859. End If
  860. AttributesJson = raw
  861. End Function
  862. ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps (same transaction).
  863. Private Sub InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
  864. DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
  865. "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
  866. DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
  867. Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
  868. End Sub
  869. ' summary detail: replace the (omitted) body with the stored summary, or the first 240 characters of the content
  870. Private Function SummaryOnly(json, rs)
  871. Dim sm
  872. If IsNull(rs(12)) Then
  873. sm = "" & rs(13)
  874. If Len(sm) > 240 Then sm = Left(sm, 240) & "..."
  875. Else
  876. sm = "" & rs(12)
  877. End If
  878. SummaryOnly = Left(json, Len(json) - 1) & ",""snippet"":" & JsonLite_Quote(sm) & "}"
  879. End Function
  880. ' "'a','b'" for an optional array of memory type codes (letters only); "" when absent
  881. Private Function TypeListSql(input, name)
  882. Dim arr, i, out, c, j, t
  883. TypeListSql = ""
  884. If Not input.HasRaw(name) Then
  885. If input.Exists(name) Then
  886. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of type codes."
  887. End If
  888. Exit Function
  889. End If
  890. arr = JsonLite_ParseStringArray(input.Raw(name))
  891. If IsNull(arr) Then
  892. AddErr name & " must be an array of type codes."
  893. Exit Function
  894. End If
  895. out = ""
  896. For i = 0 To UBound(arr)
  897. t = LCase(Trim(arr(i)))
  898. If Len(t) = 0 Or Len(t) > 40 Then
  899. AddErr name & " contains an invalid type."
  900. Exit Function
  901. End If
  902. For j = 1 To Len(t)
  903. c = Mid(t, j, 1)
  904. If c < "a" Or c > "z" Then
  905. AddErr name & " contains an invalid type."
  906. Exit Function
  907. End If
  908. Next
  909. If Len(out) > 0 Then out = out & ","
  910. out = out & "'" & t & "'"
  911. Next
  912. TypeListSql = out
  913. End Function
  914. Private Function IdListSql(input, name)
  915. Dim arr, i, out
  916. IdListSql = ""
  917. If Not input.HasRaw(name) Then
  918. If input.Exists(name) Then
  919. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids."
  920. End If
  921. Exit Function
  922. End If
  923. arr = JsonLite_ParseStringArray(input.Raw(name))
  924. If IsNull(arr) Then
  925. AddErr name & " must be an array of ids."
  926. Exit Function
  927. End If
  928. out = ""
  929. For i = 0 To UBound(arr)
  930. If Not Api_IsId(arr(i)) Then
  931. AddErr name & " must contain valid ids."
  932. Exit Function
  933. End If
  934. If Len(out) > 0 Then out = out & ","
  935. out = out & "'" & arr(i) & "'"
  936. Next
  937. If Len(out) = 0 Then AddErr name & " must not be empty when given."
  938. IdListSql = out
  939. End Function
  940. Private Function IntersectIds(allowed, requested)
  941. Dim a, i, out
  942. a = Split(allowed, ",")
  943. out = ""
  944. For i = 0 To UBound(a)
  945. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  946. If Len(out) > 0 Then out = out & ","
  947. out = out & a(i)
  948. End If
  949. Next
  950. IntersectIds = out
  951. End Function
  952. Private Sub StoreIdem(idemKey, reqHash, status, resp)
  953. Api_IdempotencyStore idemKey, reqHash, status, resp
  954. End Sub
  955. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  956. Public Sub Invoke(actionName, args)
  957. Select Case LCase(actionName)
  958. Case "remember" : Remember
  959. Case "recent" : Recent
  960. Case "fetch" : Fetch args(0)
  961. Case "correct" : Correct args(0)
  962. Case "forget" : Forget args(0)
  963. Case "retire" : Retire args(0)
  964. Case "versions" : Versions args(0)
  965. Case "verify" : Verify args(0)
  966. Case "recall" : Recall
  967. Case Else
  968. Err.Raise 438, "ApiMemoriesController_Class", "Action '" & actionName & "' not found"
  969. End Select
  970. End Sub
  971. End Class
  972. Dim ApiMemoriesController_Class__Singleton
  973. Function ApiMemoriesController()
  974. If IsEmpty(ApiMemoriesController_Class__Singleton) Then
  975. Set ApiMemoriesController_Class__Singleton = New ApiMemoriesController_Class
  976. End If
  977. Set ApiMemoriesController = ApiMemoriesController_Class__Singleton
  978. End Function
  979. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  980. Sub ApiMemoriesController_Invoke(actionName, args)
  981. ApiMemoriesController().Invoke actionName, args
  982. End Sub
  983. %>

Powered by TurnKey Linux.