No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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

Powered by TurnKey Linux.