Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1056 linhas
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. revs(j) = CLng(rs(10))
  652. Exit For
  653. End If
  654. Next
  655. End If
  656. rs.MoveNext
  657. Loop
  658. rs.Close
  659. For j = 0 To n - 1
  660. If Len("" & rowJson(j)) > 0 Then
  661. If count >= maxResults Then Exit For
  662. If count > 0 Then out = out & ","
  663. out = out & rowJson(j)
  664. count = count + 1
  665. Tel_AddResult spec, "memory", ids(j), revs(j), -CDbl(scores(j))
  666. End If
  667. Next
  668. End If
  669. If excluded > 0 Then
  670. If Len(warnings) > 0 Then
  671. warnings = warnings & ","
  672. End If
  673. warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them"""
  674. End If
  675. Tel_Record qid, "recall", ranker.Strategy, query, spec, t0
  676. Api_Audit "memory.recall", "search", "", "ok"
  677. Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}"
  678. End Sub
  679. '===============================================================
  680. ' Helpers
  681. '===============================================================
  682. ' Memory + current revision. Column order is relied on by MemoryJson:
  683. ' 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,
  684. ' 10 revision, 11 title, 12 summary, 13 content, 14 attributes, 15 tags, 16 confidence, 17 importance, 18 verification_status, 19 change_reason
  685. Private Function MemorySelect()
  686. 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, " & _
  687. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  688. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
  689. End Function
  690. ' Same columns but a specific revision (first parameter is the revision number)
  691. Private Function MemorySelectRevision()
  692. 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, " & _
  693. "r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.verification_status, r.change_reason " & _
  694. "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = ?"
  695. End Function
  696. Private Function MemoryJson(rs, brief)
  697. Dim s
  698. s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  699. ",""status"":" & JsonLite_Quote("" & rs(4)) & ",""current_revision"":" & CLng(rs(3)) & ",""revision"":" & CLng(rs(10)) & _
  700. ",""verification_status"":" & JsonLite_Quote("" & rs(18)) & ",""title"":" & JsonLite_Quote("" & rs(11)) & ",""summary"":" & JStr(rs(12))
  701. If Not brief Then
  702. s = s & ",""content"":" & JsonLite_Quote("" & rs(13)) & ",""attributes"":" & JRaw(rs(14), "null") & ",""change_reason"":" & JStr(rs(19)) & _
  703. ",""valid_from"":" & JStr(rs(5)) & ",""valid_until"":" & JStr(rs(6)) & ",""created_by"":" & JsonLite_Quote("" & rs(7))
  704. End If
  705. s = s & ",""tags"":" & JRaw(rs(15), "[]") & ",""confidence"":" & JNum(rs(16)) & ",""importance"":" & JNum(rs(17)) & _
  706. ",""created_at"":" & JsonLite_Quote("" & rs(8)) & ",""updated_at"":" & JsonLite_Quote("" & rs(9)) & "}"
  707. MemoryJson = s
  708. End Function
  709. Private Function JStr(v)
  710. If IsNull(v) Then
  711. JStr = "null"
  712. Else
  713. JStr = JsonLite_Quote("" & v)
  714. End If
  715. End Function
  716. Private Function JNum(v)
  717. If IsNull(v) Then
  718. JNum = "null"
  719. ElseIf Len("" & v) = 0 Then
  720. JNum = "null"
  721. Else
  722. JNum = JsonLite_Num(v)
  723. End If
  724. End Function
  725. ' Stored raw JSON text (validated on the way in) or a default
  726. Private Function JRaw(v, dflt)
  727. If IsNull(v) Then
  728. JRaw = dflt
  729. ElseIf Len("" & v) = 0 Then
  730. JRaw = dflt
  731. Else
  732. JRaw = "" & v
  733. End If
  734. End Function
  735. Private Sub AddErr(msg)
  736. If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30)
  737. m_errs = m_errs & msg
  738. End Sub
  739. Private Function ReqString(input, name, maxLen)
  740. Dim v
  741. ReqString = ""
  742. If Not input.Exists(name) Then
  743. AddErr name & " is required."
  744. Exit Function
  745. End If
  746. v = input.Item(name)
  747. If IsNull(v) Then
  748. AddErr name & " is required."
  749. Exit Function
  750. End If
  751. If VarType(v) <> vbString Then
  752. AddErr name & " must be a string."
  753. Exit Function
  754. End If
  755. v = Trim(v)
  756. If Len(v) = 0 Then
  757. AddErr name & " must not be empty."
  758. Exit Function
  759. End If
  760. If Len(v) > maxLen Then
  761. AddErr name & " must be at most " & maxLen & " characters."
  762. Exit Function
  763. End If
  764. ReqString = v
  765. End Function
  766. ' Optional string: Null when absent or null
  767. Private Function OptString(input, name, maxLen)
  768. Dim v
  769. OptString = Null
  770. If Not input.Exists(name) Then Exit Function
  771. v = input.Item(name)
  772. If IsNull(v) Then Exit Function
  773. If VarType(v) <> vbString Then
  774. AddErr name & " must be a string."
  775. Exit Function
  776. End If
  777. If Len(v) > maxLen Then
  778. AddErr name & " must be at most " & maxLen & " characters."
  779. Exit Function
  780. End If
  781. OptString = v
  782. End Function
  783. ' Optional number in 0..1: Null when absent or null
  784. Private Function OptUnit(input, name)
  785. Dim v
  786. OptUnit = Null
  787. If Not input.Exists(name) Then Exit Function
  788. v = input.Item(name)
  789. If IsNull(v) Then Exit Function
  790. If VarType(v) <> vbDouble Then
  791. AddErr name & " must be a number between 0 and 1."
  792. Exit Function
  793. End If
  794. If v < 0 Or v > 1 Then
  795. AddErr name & " must be between 0 and 1."
  796. Exit Function
  797. End If
  798. OptUnit = v
  799. End Function
  800. ' tags: optional array of non-empty strings; returns compact JSON text or Null
  801. Private Function TagsJson(input)
  802. Dim arr, i, out, t
  803. TagsJson = Null
  804. If Not input.HasRaw("tags") Then
  805. If input.Exists("tags") Then
  806. If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings."
  807. End If
  808. Exit Function
  809. End If
  810. arr = JsonLite_ParseStringArray(input.Raw("tags"))
  811. If IsNull(arr) Then
  812. AddErr "tags must be an array of strings."
  813. Exit Function
  814. End If
  815. If UBound(arr) > 31 Then
  816. AddErr "tags may contain at most 32 entries."
  817. Exit Function
  818. End If
  819. out = ""
  820. For i = 0 To UBound(arr)
  821. t = Trim(arr(i))
  822. If Len(t) = 0 Or Len(t) > 64 Then
  823. AddErr "each tag must be 1 to 64 characters."
  824. Exit Function
  825. End If
  826. If i > 0 Then out = out & ","
  827. out = out & JsonLite_Quote(t)
  828. Next
  829. TagsJson = "[" & out & "]"
  830. End Function
  831. ' attributes: optional JSON object, stored as its raw text (max 16 KB) or Null
  832. Private Function AttributesJson(input)
  833. Dim raw
  834. AttributesJson = Null
  835. If Not input.HasRaw("attributes") Then
  836. If input.Exists("attributes") Then
  837. If Not IsNull(input.Item("attributes")) Then AddErr "attributes must be a JSON object."
  838. End If
  839. Exit Function
  840. End If
  841. raw = input.Raw("attributes")
  842. If Left(raw, 1) <> "{" Then
  843. AddErr "attributes must be a JSON object."
  844. Exit Function
  845. End If
  846. If Len(raw) > 16384 Then
  847. AddErr "attributes must be at most 16 KB."
  848. Exit Function
  849. End If
  850. AttributesJson = raw
  851. End Function
  852. ' G3DB allows at most 8 parameters per statement, so a revision is written in two steps (same transaction).
  853. Private Sub InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts)
  854. DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _
  855. "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts)
  856. DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _
  857. Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId)
  858. End Sub
  859. ' summary detail: replace the (omitted) body with the stored summary, or the first 240 characters of the content
  860. Private Function SummaryOnly(json, rs)
  861. Dim sm
  862. If IsNull(rs(12)) Then
  863. sm = "" & rs(13)
  864. If Len(sm) > 240 Then sm = Left(sm, 240) & "..."
  865. Else
  866. sm = "" & rs(12)
  867. End If
  868. SummaryOnly = Left(json, Len(json) - 1) & ",""snippet"":" & JsonLite_Quote(sm) & "}"
  869. End Function
  870. ' "'a','b'" for an optional array of memory type codes (letters only); "" when absent
  871. Private Function TypeListSql(input, name)
  872. Dim arr, i, out, c, j, t
  873. TypeListSql = ""
  874. If Not input.HasRaw(name) Then
  875. If input.Exists(name) Then
  876. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of type codes."
  877. End If
  878. Exit Function
  879. End If
  880. arr = JsonLite_ParseStringArray(input.Raw(name))
  881. If IsNull(arr) Then
  882. AddErr name & " must be an array of type codes."
  883. Exit Function
  884. End If
  885. out = ""
  886. For i = 0 To UBound(arr)
  887. t = LCase(Trim(arr(i)))
  888. If Len(t) = 0 Or Len(t) > 40 Then
  889. AddErr name & " contains an invalid type."
  890. Exit Function
  891. End If
  892. For j = 1 To Len(t)
  893. c = Mid(t, j, 1)
  894. If c < "a" Or c > "z" Then
  895. AddErr name & " contains an invalid type."
  896. Exit Function
  897. End If
  898. Next
  899. If Len(out) > 0 Then out = out & ","
  900. out = out & "'" & t & "'"
  901. Next
  902. TypeListSql = out
  903. End Function
  904. Private Function IdListSql(input, name)
  905. Dim arr, i, out
  906. IdListSql = ""
  907. If Not input.HasRaw(name) Then
  908. If input.Exists(name) Then
  909. If Not IsNull(input.Item(name)) Then AddErr name & " must be an array of ids."
  910. End If
  911. Exit Function
  912. End If
  913. arr = JsonLite_ParseStringArray(input.Raw(name))
  914. If IsNull(arr) Then
  915. AddErr name & " must be an array of ids."
  916. Exit Function
  917. End If
  918. out = ""
  919. For i = 0 To UBound(arr)
  920. If Not Api_IsId(arr(i)) Then
  921. AddErr name & " must contain valid ids."
  922. Exit Function
  923. End If
  924. If Len(out) > 0 Then out = out & ","
  925. out = out & "'" & arr(i) & "'"
  926. Next
  927. If Len(out) = 0 Then AddErr name & " must not be empty when given."
  928. IdListSql = out
  929. End Function
  930. Private Function IntersectIds(allowed, requested)
  931. Dim a, i, out
  932. a = Split(allowed, ",")
  933. out = ""
  934. For i = 0 To UBound(a)
  935. If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
  936. If Len(out) > 0 Then out = out & ","
  937. out = out & a(i)
  938. End If
  939. Next
  940. IntersectIds = out
  941. End Function
  942. Private Sub StoreIdem(idemKey, reqHash, status, resp)
  943. Api_IdempotencyStore idemKey, reqHash, status, resp
  944. End Sub
  945. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  946. Public Sub Invoke(actionName, args)
  947. Select Case LCase(actionName)
  948. Case "remember" : Remember
  949. Case "recent" : Recent
  950. Case "fetch" : Fetch args(0)
  951. Case "correct" : Correct args(0)
  952. Case "forget" : Forget args(0)
  953. Case "retire" : Retire args(0)
  954. Case "versions" : Versions args(0)
  955. Case "verify" : Verify args(0)
  956. Case "recall" : Recall
  957. Case Else
  958. Err.Raise 438, "ApiMemoriesController_Class", "Action '" & actionName & "' not found"
  959. End Select
  960. End Sub
  961. End Class
  962. Dim ApiMemoriesController_Class__Singleton
  963. Function ApiMemoriesController()
  964. If IsEmpty(ApiMemoriesController_Class__Singleton) Then
  965. Set ApiMemoriesController_Class__Singleton = New ApiMemoriesController_Class
  966. End If
  967. Set ApiMemoriesController = ApiMemoriesController_Class__Singleton
  968. End Function
  969. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  970. Sub ApiMemoriesController_Invoke(actionName, args)
  971. ApiMemoriesController().Invoke actionName, args
  972. End Sub
  973. %>

Powered by TurnKey Linux.