Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

1131 wiersze
48KB

  1. <%
  2. ' ApiLearningController: experiences, learning candidates and review, evidence, feedback (spec FR-012, FR-013,
  3. ' FR-014, FR-020, section 12, AC-08, AC-16, AC-18). Stateless JSON API, no layout.
  4. ' Helpers: core/lib.Api.asp (auth, errors), core/lib.Learning.asp (evidence, memory writes, telemetry).
  5. '
  6. ' POST /api/v1/sessions/:id/events RecordEvent {"task","outcome":"success|failure|partial|unknown","problem","action","result","environment":{}}
  7. ' GET /api/v1/sessions/:id/events Events experiences of the session, oldest first
  8. ' POST /api/v1/learn Learn {"namespace_id","type","title","content","summary","tags","confidence",
  9. ' "target_memory_id","base_revision","evidence":[{"kind","id","role","excerpt"}]}
  10. ' GET /api/v1/candidates Candidates ?namespace_id= &state=proposed|accepted|rejected &limit=
  11. ' GET /api/v1/candidates/:id Candidate with its evidence
  12. ' POST /api/v1/candidates/:id/review Review {"decision":"accept|reject","notes","verify":true|false}
  13. ' GET /api/v1/memories/:id/sources Sources evidence and verifications of a revision (?revision=, default current)
  14. ' POST /api/v1/feedback Feedback {"query_id","result_id","usefulness":"useful|not_useful|incorrect|harmful","comment"}
  15. ' POST /api/v1/consolidations Consolidate {"namespace_id","since","min_size":2,"similarity":0.35,"max_experiences":300,"propose":false}
  16. ' groups similar experiences (core/lib.Consolidation.asp) with a draft each;
  17. ' "propose": true files each group with at least min_size experiences not yet
  18. ' cited by any candidate as a proposed candidate (tag "consolidated")
  19. '
  20. ' Permissions on the namespace: write (RecordEvent, Learn, Consolidate with propose), read (Consolidate, Candidates, Candidate, Sources, Feedback),
  21. ' verify (Review). Reviewing your own candidate needs admin: a proposer cannot approve itself. Accepting creates a
  22. ' memory (or a new revision of target_memory_id, if it is still at base_revision) with the candidate's evidence; it
  23. ' stays unverified unless "verify": true, which records a verification by the reviewer. Without permission: 404.
  24. Class ApiLearningController_Class
  25. Private m_errs
  26. Public Property Get useLayout()
  27. useLayout = False
  28. End Property
  29. Public Property Let useLayout(v)
  30. End Property
  31. Public Property Get Title()
  32. Title = "Learning API"
  33. End Property
  34. '---------------------------------------------------------------
  35. ' POST /api/v1/sessions/:id/events
  36. '---------------------------------------------------------------
  37. Public Sub RecordEvent(id)
  38. Dim body, input, idemKey, reqHash, rs, nsId, status, task, outcome, problem, action, result, envRaw, expId, ts, resp, k
  39. If Not Api_Authenticate() Then Exit Sub
  40. If Not Api_IsId(id) Then
  41. Api_NotFound
  42. Exit Sub
  43. End If
  44. body = Api_ReadBody()
  45. If IsEmpty(body) Then Exit Sub
  46. Set input = JsonLite_Parse(body)
  47. idemKey = Api_Header("Idempotency-Key")
  48. If Len(idemKey) > 200 Then
  49. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  50. Exit Sub
  51. End If
  52. reqHash = Api_Sha256("events|" & id & "|" & body)
  53. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  54. Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  55. If rs.EOF Then
  56. rs.Close
  57. Api_Error 404, "session_not_found", "Session not found."
  58. Exit Sub
  59. End If
  60. nsId = "" & rs(0)
  61. status = "" & rs(1)
  62. rs.Close
  63. If Not Api_CanAccessNamespace(nsId, "write") Then
  64. Api_Error 404, "session_not_found", "Session not found."
  65. Exit Sub
  66. End If
  67. m_errs = ""
  68. task = ReqString(input, "task", 2000)
  69. outcome = LCase("" & ReqString(input, "outcome", 20))
  70. problem = OptString(input, "problem", 4000)
  71. action = OptString(input, "action", 4000)
  72. result = OptString(input, "result", 4000)
  73. envRaw = ObjectJson(input, "environment")
  74. If Len(m_errs) = 0 Then
  75. If outcome <> "success" And outcome <> "failure" And outcome <> "partial" And outcome <> "unknown" Then
  76. AddErr "outcome must be success, failure, partial or unknown."
  77. End If
  78. End If
  79. If Len(m_errs) > 0 Then
  80. Api_Invalid Split(m_errs, Chr(30))
  81. Exit Sub
  82. End If
  83. If status <> "active" Then
  84. Api_Error 409, "session_not_active", "The session is " & status & "; experiences can only be recorded in an active session."
  85. Exit Sub
  86. End If
  87. expId = Api_NewId()
  88. ts = Api_Now()
  89. resp = "{""id"":" & JsonLite_Quote(expId) & ",""session_id"":" & JsonLite_Quote(id) & ",""outcome"":" & JsonLite_Quote(outcome) & ",""created_at"":" & JsonLite_Quote(ts) & "}"
  90. On Error Resume Next
  91. DAL().BeginTransaction
  92. DAL().Execute "INSERT INTO experiences (id, tenant_id, namespace_id, session_id, principal_id, task, outcome, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  93. Array(expId, Api_TenantId, nsId, id, Api_PrincipalId, task, outcome, ts)
  94. DAL().Execute "UPDATE experiences SET problem = ?, action = ?, result = ?, environment = ? WHERE id = ?", Array(problem, action, result, envRaw, expId)
  95. Api_IdempotencyStore 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. On Error GoTo 0
  104. Api_Audit "session.event", "experience", expId, "ok"
  105. Api_Send 201, resp
  106. End Sub
  107. '---------------------------------------------------------------
  108. ' GET /api/v1/sessions/:id/events
  109. '---------------------------------------------------------------
  110. Public Sub Events(id)
  111. Dim rs, nsId, out, n
  112. If Not Api_Authenticate() Then Exit Sub
  113. If Not Api_IsId(id) Then
  114. Api_NotFound
  115. Exit Sub
  116. End If
  117. Set rs = DAL().Query("SELECT namespace_id FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  118. If rs.EOF Then
  119. rs.Close
  120. Api_Error 404, "session_not_found", "Session not found."
  121. Exit Sub
  122. End If
  123. nsId = "" & rs(0)
  124. rs.Close
  125. If Not Api_CanAccessNamespace(nsId, "read") Then
  126. Api_Error 404, "session_not_found", "Session not found."
  127. Exit Sub
  128. End If
  129. Set rs = DAL().Query("SELECT id, task, problem, action, result, outcome, environment, principal_id, created_at FROM experiences " & _
  130. "WHERE session_id = ? AND tenant_id = ? ORDER BY created_at, id LIMIT 200", Array(id, Api_TenantId))
  131. out = ""
  132. n = 0
  133. Do While Not rs.EOF
  134. If n > 0 Then
  135. out = out & ","
  136. End If
  137. out = out & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""task"":" & JsonLite_Quote("" & rs(1)) & ",""problem"":" & JStr(rs(2)) & _
  138. ",""action"":" & JStr(rs(3)) & ",""result"":" & JStr(rs(4)) & ",""outcome"":" & JsonLite_Quote("" & rs(5)) & _
  139. ",""environment"":" & JRaw(rs(6), "null") & ",""recorded_by"":" & JsonLite_Quote("" & rs(7)) & ",""created_at"":" & JsonLite_Quote("" & rs(8)) & "}"
  140. n = n + 1
  141. rs.MoveNext
  142. Loop
  143. rs.Close
  144. Api_Send 200, "{""session_id"":" & JsonLite_Quote(id) & ",""data"":[" & out & "]}"
  145. End Sub
  146. '---------------------------------------------------------------
  147. ' POST /api/v1/learn
  148. '---------------------------------------------------------------
  149. Public Sub Learn()
  150. Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, confidence, targetId, baseRev
  151. Dim ev, msg, rs, candId, ts, resp, k
  152. If Not Api_Authenticate() Then Exit Sub
  153. body = Api_ReadBody()
  154. If IsEmpty(body) Then Exit Sub
  155. Set input = JsonLite_Parse(body)
  156. idemKey = Api_Header("Idempotency-Key")
  157. If Len(idemKey) > 200 Then
  158. Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters."
  159. Exit Sub
  160. End If
  161. reqHash = Api_Sha256("learn|" & body)
  162. If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub
  163. m_errs = ""
  164. nsId = ReqString(input, "namespace_id", 64)
  165. memType = LCase("" & ReqString(input, "type", 40))
  166. title = ReqString(input, "title", 200)
  167. content = ReqString(input, "content", 100000)
  168. summary = OptString(input, "summary", 2000)
  169. tagsRaw = TagsJson(input)
  170. confidence = OptUnit(input, "confidence")
  171. targetId = OptString(input, "target_memory_id", 64)
  172. baseRev = Null
  173. If Not IsNull(targetId) Then
  174. If Not Api_IsId(targetId) Then
  175. AddErr "target_memory_id must be a valid id."
  176. End If
  177. If Not input.Exists("base_revision") Then
  178. AddErr "base_revision is required with target_memory_id."
  179. ElseIf VarType(input.Item("base_revision")) <> vbDouble Then
  180. AddErr "base_revision must be a number."
  181. Else
  182. baseRev = CLng(input.Item("base_revision"))
  183. End If
  184. End If
  185. If Len(m_errs) > 0 Then
  186. Api_Invalid Split(m_errs, Chr(30))
  187. Exit Sub
  188. End If
  189. If Not Api_CanAccessNamespace(nsId, "write") Then
  190. Api_Audit "candidate.learn", "namespace", nsId, "denied"
  191. Api_Error 404, "namespace_not_found", "Namespace not found."
  192. Exit Sub
  193. End If
  194. Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType)
  195. If rs.EOF Then
  196. rs.Close
  197. Api_Invalid Array("type '" & memType & "' is not a known memory type.")
  198. Exit Sub
  199. End If
  200. rs.Close
  201. If Not IsNull(targetId) Then
  202. ' A revision proposal must target a memory of the same namespace and type that the caller can read.
  203. Set rs = DAL().Query("SELECT 1 FROM memories WHERE id = ? AND tenant_id = ? AND namespace_id = ? AND type = ?", Array(targetId, Api_TenantId, nsId, memType))
  204. If rs.EOF Then
  205. rs.Close
  206. Api_Invalid Array("target_memory_id was not found in this namespace with this type.")
  207. Exit Sub
  208. End If
  209. rs.Close
  210. End If
  211. Set ev = New Evidence_Class
  212. msg = ev.Load(input, "evidence")
  213. If Len(msg) > 0 Then
  214. Api_Invalid Array(msg)
  215. Exit Sub
  216. End If
  217. candId = Api_NewId()
  218. ts = Api_Now()
  219. resp = "{""id"":" & JsonLite_Quote(candId) & ",""state"":""proposed"",""namespace_id"":" & JsonLite_Quote(nsId) & ",""type"":" & JsonLite_Quote(memType) & _
  220. ",""evidence_count"":" & ev.Count & "}"
  221. On Error Resume Next
  222. DAL().BeginTransaction
  223. DAL().Execute "INSERT INTO learning_candidates (id, tenant_id, namespace_id, type, title, content, author_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  224. Array(candId, Api_TenantId, nsId, memType, title, content, Api_PrincipalId, ts)
  225. DAL().Execute "UPDATE learning_candidates SET summary = ?, tags = ?, confidence = ?, target_memory_id = ?, base_revision = ? WHERE id = ?", _
  226. Array(summary, tagsRaw, confidence, targetId, baseRev, candId)
  227. ev.Save "candidate", candId, Null
  228. Api_IdempotencyStore idemKey, reqHash, 201, resp
  229. If Err.Number <> 0 Then
  230. k = Err.Number : Api_NoteDbError
  231. DAL().RollbackTransaction
  232. Api_DbFailed k, ""
  233. Exit Sub
  234. End If
  235. DAL().CommitTransaction
  236. On Error GoTo 0
  237. Api_Audit "candidate.learn", "candidate", candId, "ok"
  238. Response.AddHeader "Location", "/api/v1/candidates/" & candId
  239. Api_Send 201, resp
  240. End Sub
  241. '---------------------------------------------------------------
  242. ' POST /api/v1/consolidations
  243. '---------------------------------------------------------------
  244. Public Sub Consolidate()
  245. Dim body, input, nsId, since, minSize, sim, maxRows, propose, perm, c, groups, g, members, i, k, idList, rs, cited
  246. Dim out, oc, terms, termsJson, idsJson, draftType, draftTitle, draftContent, candId, created, ts, evN, cj
  247. If Not Api_Authenticate() Then Exit Sub
  248. body = Api_ReadBody()
  249. If IsEmpty(body) Then Exit Sub
  250. Set input = JsonLite_Parse(body)
  251. m_errs = ""
  252. nsId = ReqString(input, "namespace_id", 64)
  253. since = OptString(input, "since", 19)
  254. If IsNull(since) Then
  255. since = "0000-00-00 00:00:00"
  256. Else
  257. Dim reTs
  258. Set reTs = New RegExp
  259. reTs.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}( [0-9]{2}:[0-9]{2}:[0-9]{2})?$"
  260. If Not reTs.Test(since) Then
  261. AddErr "since must be a UTC time like 2026-12-01 or 2026-12-01 08:00:00."
  262. End If
  263. End If
  264. minSize = OptNumber(input, "min_size", 2, 2, 50)
  265. sim = OptNumber(input, "similarity", 0.35, 0.1, 0.95)
  266. maxRows = OptNumber(input, "max_experiences", 300, 10, 500)
  267. propose = False
  268. If input.Exists("propose") Then
  269. If VarType(input.Item("propose")) = vbBoolean Then
  270. propose = input.Item("propose")
  271. Else
  272. AddErr "propose must be true or false."
  273. End If
  274. End If
  275. If Len(m_errs) > 0 Then
  276. Api_Invalid Split(m_errs, Chr(30))
  277. Exit Sub
  278. End If
  279. perm = "read"
  280. If propose Then
  281. perm = "write"
  282. End If
  283. If Not Api_CanAccessNamespace(nsId, perm) Then
  284. Api_Audit "candidate.consolidate", "namespace", nsId, "denied"
  285. Api_Error 404, "namespace_not_found", "Namespace not found."
  286. Exit Sub
  287. End If
  288. Set c = New Consolidator_Class
  289. c.Load Api_TenantId, nsId, since, CLng(maxRows)
  290. c.Cluster CDbl(sim)
  291. groups = c.Groups(CLng(minSize))
  292. out = ""
  293. created = 0
  294. ts = Api_Now()
  295. If propose Then
  296. On Error Resume Next
  297. DAL().BeginTransaction
  298. If Err.Number <> 0 Then
  299. k = Err.Number : Api_NoteDbError
  300. Api_DbFailed k, ""
  301. Exit Sub
  302. End If
  303. On Error GoTo 0
  304. End If
  305. For g = 0 To UBound(groups)
  306. members = Split(groups(g), ",")
  307. idList = ""
  308. idsJson = ""
  309. For i = 0 To UBound(members)
  310. If i > 0 Then
  311. idList = idList & ","
  312. idsJson = idsJson & ","
  313. End If
  314. idList = idList & "'" & c.Id(CLng(members(i))) & "'"
  315. idsJson = idsJson & JsonLite_Quote(c.Id(CLng(members(i))))
  316. Next
  317. ' Experiences already cited by any candidate (proposed, accepted or rejected) count as handled.
  318. Set rs = DAL().Query("SELECT COUNT(DISTINCT e.target_id) FROM evidence_links e WHERE e.tenant_id = ? AND e.owner_kind = 'candidate' " & _
  319. "AND e.target_kind = 'experience' AND e.target_id IN (" & idList & ")", Api_TenantId)
  320. cited = CLng(rs(0))
  321. rs.Close
  322. oc = Split(c.OutcomeCounts(groups(g)), ",")
  323. terms = Split(c.TopTerms(groups(g), 5), ",")
  324. termsJson = ""
  325. For i = 0 To UBound(terms)
  326. If i > 0 Then
  327. termsJson = termsJson & ","
  328. End If
  329. termsJson = termsJson & JsonLite_Quote(terms(i))
  330. Next
  331. draftType = c.DraftType(groups(g))
  332. draftTitle = c.DraftTitle(groups(g))
  333. draftContent = c.DraftContent(groups(g))
  334. candId = Null
  335. If propose And (UBound(members) + 1 - cited) >= CLng(minSize) Then
  336. candId = Api_NewId()
  337. On Error Resume Next
  338. DAL().Execute "INSERT INTO learning_candidates (id, tenant_id, namespace_id, type, title, content, author_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _
  339. Array(candId, Api_TenantId, nsId, draftType, draftTitle, draftContent, Api_PrincipalId, ts)
  340. DAL().Execute "UPDATE learning_candidates SET tags = ? WHERE id = ?", Array("[""consolidated""]", candId)
  341. ' Evidence: the most recent members (rows are newest first), up to EVIDENCE_MAX.
  342. evN = UBound(members)
  343. If evN > EVIDENCE_MAX - 1 Then
  344. evN = EVIDENCE_MAX - 1
  345. End If
  346. For i = 0 To evN
  347. k = CLng(members(i))
  348. DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, role, created_by, created_at) VALUES (?, ?, 'candidate', ?, 'experience', ?, 'supports', ?, ?)", _
  349. Array(Api_NewId(), Api_TenantId, candId, c.Id(k), Api_PrincipalId, ts)
  350. Next
  351. If Err.Number <> 0 Then
  352. k = Err.Number : Api_NoteDbError
  353. Err.Clear
  354. DAL().RollbackTransaction
  355. Api_DbFailed k, ""
  356. Exit Sub
  357. End If
  358. On Error GoTo 0
  359. created = created + 1
  360. End If
  361. If Len(out) > 0 Then
  362. out = out & ","
  363. End If
  364. If IsNull(candId) Then
  365. cj = "null"
  366. Else
  367. cj = JsonLite_Quote(candId)
  368. End If
  369. out = out & "{""size"":" & (UBound(members) + 1) & ",""sessions"":" & c.SessionCount(groups(g)) & _
  370. ",""outcomes"":{""success"":" & oc(0) & ",""failure"":" & oc(1) & ",""partial"":" & oc(2) & ",""unknown"":" & oc(3) & "}" & _
  371. ",""first_seen"":" & JsonLite_Quote(c.Created(CLng(members(UBound(members))))) & ",""last_seen"":" & JsonLite_Quote(c.Created(CLng(members(0)))) & _
  372. ",""terms"":[" & termsJson & "],""experience_ids"":[" & idsJson & "],""already_cited"":" & cited & _
  373. ",""draft"":{""type"":" & JsonLite_Quote(draftType) & ",""title"":" & JsonLite_Quote(draftTitle) & ",""content"":" & JsonLite_Quote(draftContent) & "}" & _
  374. ",""candidate_id"":" & cj & "}"
  375. Next
  376. If propose Then
  377. On Error Resume Next
  378. DAL().CommitTransaction
  379. If Err.Number <> 0 Then
  380. k = Err.Number : Api_NoteDbError
  381. Api_DbFailed k, ""
  382. Exit Sub
  383. End If
  384. On Error GoTo 0
  385. End If
  386. If propose Then
  387. Api_Audit "candidate.consolidate", "namespace", nsId, created & " proposed"
  388. End If
  389. Api_Send 200, "{""namespace_id"":" & JsonLite_Quote(nsId) & ",""experiences_considered"":" & c.Count & _
  390. ",""similarity"":" & JsonLite_Num(sim) & ",""min_size"":" & CLng(minSize) & ",""candidates_created"":" & created & _
  391. ",""groups"":[" & out & "]}"
  392. End Sub
  393. ' Optional JSON number within [lo, hi]; dflt when absent. Adds an error when out of range or not a number.
  394. Private Function OptNumber(input, name, dflt, lo, hi)
  395. Dim v
  396. OptNumber = dflt
  397. If Not input.Exists(name) Then
  398. Exit Function
  399. End If
  400. v = input.Item(name)
  401. If IsNull(v) Then
  402. Exit Function
  403. End If
  404. If VarType(v) <> vbDouble Then
  405. AddErr name & " must be a number."
  406. Exit Function
  407. End If
  408. If v < lo Or v > hi Then
  409. AddErr name & " must be between " & lo & " and " & hi & "."
  410. Exit Function
  411. End If
  412. OptNumber = v
  413. End Function
  414. '---------------------------------------------------------------
  415. ' GET /api/v1/candidates
  416. '---------------------------------------------------------------
  417. Public Sub Candidates()
  418. Dim allowed, nsFilter, state, limit, sql, rs, out, n
  419. If Not Api_Authenticate() Then Exit Sub
  420. nsFilter = Trim("" & Request.QueryString("namespace_id"))
  421. state = LCase(Trim("" & Request.QueryString("state")))
  422. limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200)
  423. If Len(state) > 0 Then
  424. If state <> "proposed" And state <> "accepted" And state <> "rejected" Then
  425. Api_Invalid Array("state must be proposed, accepted or rejected.")
  426. Exit Sub
  427. End If
  428. End If
  429. If Len(nsFilter) > 0 Then
  430. If Not Api_IsId(nsFilter) Then
  431. Api_Invalid Array("namespace_id must be a valid id.")
  432. Exit Sub
  433. End If
  434. End If
  435. allowed = Api_AllowedNamespaceIds("read")
  436. out = ""
  437. n = 0
  438. If Len(allowed) > 0 Then
  439. sql = CandidateSelect() & " WHERE tenant_id = ? AND namespace_id IN (" & allowed & ")"
  440. If Len(nsFilter) > 0 Then
  441. sql = sql & " AND namespace_id = '" & nsFilter & "'"
  442. End If
  443. If Len(state) > 0 Then
  444. sql = sql & " AND state = '" & state & "'"
  445. End If
  446. Set rs = DAL().Query(sql & " ORDER BY created_at DESC, id LIMIT " & limit, Api_TenantId)
  447. Do While Not rs.EOF
  448. If n > 0 Then
  449. out = out & ","
  450. End If
  451. out = out & CandidateJson(rs, True)
  452. n = n + 1
  453. rs.MoveNext
  454. Loop
  455. rs.Close
  456. End If
  457. Api_Send 200, "{""data"":[" & out & "]}"
  458. End Sub
  459. '---------------------------------------------------------------
  460. ' GET /api/v1/candidates/:id
  461. '---------------------------------------------------------------
  462. Public Sub Candidate(id)
  463. Dim rs, json, nsId
  464. If Not Api_Authenticate() Then Exit Sub
  465. If Not Api_IsId(id) Then
  466. Api_NotFound
  467. Exit Sub
  468. End If
  469. Set rs = DAL().Query(CandidateSelect() & " WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  470. If rs.EOF Then
  471. rs.Close
  472. Api_NotFound
  473. Exit Sub
  474. End If
  475. nsId = "" & rs(1)
  476. json = CandidateJson(rs, False)
  477. rs.Close
  478. If Not Api_CanAccessNamespace(nsId, "read") Then
  479. Api_NotFound
  480. Exit Sub
  481. End If
  482. json = Left(json, Len(json) - 1) & ",""evidence"":" & EvidenceJson("candidate", id, Null) & "}"
  483. Api_Send 200, "{""data"":" & json & "}"
  484. End Sub
  485. '---------------------------------------------------------------
  486. ' POST /api/v1/candidates/:id/review
  487. '---------------------------------------------------------------
  488. Public Sub Review(id)
  489. Dim body, input, rs, nsId, state, author, memType, title, summary, content, tagsRaw, confidence, targetId, baseRev
  490. Dim decision, notes, doVerify, ts, k, memId, rev, dup, tNs, tType, tRev, tStatus, verStatus, hash
  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, state, author_principal_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision " & _
  500. "FROM learning_candidates WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  501. If rs.EOF Then
  502. rs.Close
  503. Api_NotFound
  504. Exit Sub
  505. End If
  506. nsId = "" & rs(0)
  507. state = "" & rs(1)
  508. author = "" & rs(2)
  509. memType = "" & rs(3)
  510. title = "" & rs(4)
  511. summary = rs(5)
  512. content = "" & rs(6)
  513. tagsRaw = rs(7)
  514. confidence = rs(8)
  515. targetId = rs(9)
  516. baseRev = rs(10)
  517. rs.Close
  518. If Not Api_CanAccessNamespace(nsId, "verify") Then
  519. Api_Audit "candidate.review", "candidate", id, "denied"
  520. Api_NotFound
  521. Exit Sub
  522. End If
  523. m_errs = ""
  524. decision = LCase("" & ReqString(input, "decision", 20))
  525. notes = OptString(input, "notes", 2000)
  526. doVerify = False
  527. If input.Exists("verify") Then
  528. If VarType(input.Item("verify")) = vbBoolean Then
  529. doVerify = input.Item("verify")
  530. ElseIf Not IsNull(input.Item("verify")) Then
  531. AddErr "verify must be true or false."
  532. End If
  533. End If
  534. If Len(m_errs) = 0 Then
  535. If decision <> "accept" And decision <> "reject" Then
  536. AddErr "decision must be accept or reject."
  537. End If
  538. End If
  539. If Len(m_errs) > 0 Then
  540. Api_Invalid Split(m_errs, Chr(30))
  541. Exit Sub
  542. End If
  543. If state <> "proposed" Then
  544. Api_Error 409, "candidate_already_reviewed", "The candidate was already " & state & "."
  545. Exit Sub
  546. End If
  547. If author = Api_PrincipalId Then
  548. If Not Api_CanAccessNamespace(nsId, "admin") Then
  549. Api_Audit "candidate.review", "candidate", id, "self_review_denied"
  550. Api_Error 403, "self_review_not_allowed", "A candidate cannot be reviewed by its author without admin permission on the namespace."
  551. Exit Sub
  552. End If
  553. End If
  554. ts = Api_Now()
  555. If decision = "reject" Then
  556. On Error Resume Next
  557. DAL().Execute "UPDATE learning_candidates SET state = 'rejected', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ? WHERE id = ? AND state = 'proposed'", _
  558. Array(Api_PrincipalId, notes, ts, id)
  559. If Err.Number <> 0 Then
  560. k = Err.Number : Api_NoteDbError
  561. Api_DbFailed k, ""
  562. Exit Sub
  563. End If
  564. On Error GoTo 0
  565. Api_Audit "candidate.review", "candidate", id, "rejected"
  566. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""rejected""}"
  567. Exit Sub
  568. End If
  569. ' accept: check the target (revision proposals) or look for an identical active memory (new memories)
  570. dup = False
  571. memId = ""
  572. rev = 0
  573. If Not IsNull(targetId) Then
  574. Set rs = DAL().Query("SELECT namespace_id, type, current_revision, lifecycle_status FROM memories WHERE id = ? AND tenant_id = ?", Array("" & targetId, Api_TenantId))
  575. If rs.EOF Then
  576. rs.Close
  577. Api_Error 409, "target_memory_missing", "The memory this candidate revises no longer exists."
  578. Exit Sub
  579. End If
  580. tNs = "" & rs(0)
  581. tType = "" & rs(1)
  582. tRev = CLng(rs(2))
  583. tStatus = "" & rs(3)
  584. rs.Close
  585. If tStatus <> "active" Then
  586. Api_Error 409, "target_memory_not_active", "The memory this candidate revises is " & tStatus & "."
  587. Exit Sub
  588. End If
  589. If tRev <> CLng(baseRev) Then
  590. Api_Error 409, "stale_candidate", "The memory changed since the candidate was proposed (base revision " & baseRev & ", current " & tRev & ")."
  591. Exit Sub
  592. End If
  593. Else
  594. hash = Mem_Hash(nsId, memType, title, content)
  595. Set rs = DAL().Query("SELECT m.id, m.current_revision FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _
  596. "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", Array(Api_TenantId, nsId, memType, hash))
  597. If Not rs.EOF Then
  598. dup = True
  599. memId = "" & rs(0)
  600. rev = CLng(rs(1))
  601. End If
  602. rs.Close
  603. End If
  604. On Error Resume Next
  605. DAL().BeginTransaction
  606. If Not IsNull(targetId) Then
  607. memId = "" & targetId
  608. rev = Mem_Revise(memId, nsId, memType, tRev, title, summary, content, tagsRaw, confidence, "accepted candidate " & id)
  609. ElseIf Not dup Then
  610. memId = Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, "accepted candidate " & id)
  611. rev = 1
  612. End If
  613. Evidence_CopyCandidate id, memId, rev
  614. If doVerify Then
  615. Mem_Verify memId, rev, "candidate_review", notes
  616. End If
  617. DAL().Execute "UPDATE learning_candidates SET state = 'accepted', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ?, resulting_memory_id = ?, resulting_revision = ? " & _
  618. "WHERE id = ? AND state = 'proposed'", Array(Api_PrincipalId, notes, ts, memId, rev, id)
  619. If Err.Number <> 0 Then
  620. k = Err.Number : Api_NoteDbError
  621. DAL().RollbackTransaction
  622. Api_DbFailed k, ""
  623. Exit Sub
  624. End If
  625. DAL().CommitTransaction
  626. If Err.Number <> 0 Then
  627. k = Err.Number : Api_NoteDbError
  628. Api_DbFailed k, ""
  629. Exit Sub
  630. End If
  631. On Error GoTo 0
  632. Set rs = DAL().Query("SELECT verification_status FROM memory_revisions WHERE memory_id = ? AND revision = ?", Array(memId, rev))
  633. verStatus = "unverified"
  634. If Not rs.EOF Then
  635. verStatus = "" & rs(0)
  636. End If
  637. rs.Close
  638. Emb_AfterWrite Api_TenantId, 8
  639. Api_Audit "candidate.review", "candidate", id, "accepted"
  640. Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""accepted"",""resulting_memory_id"":" & JsonLite_Quote(memId) & _
  641. ",""resulting_revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(verStatus) & ",""duplicate"":" & LCase(CStr(dup)) & "}"
  642. End Sub
  643. '---------------------------------------------------------------
  644. ' GET /api/v1/memories/:id/sources
  645. '---------------------------------------------------------------
  646. Public Sub Sources(id)
  647. Dim rs, nsId, curRev, rev, q, ver, n, cand
  648. If Not Api_Authenticate() Then Exit Sub
  649. If Not Api_IsId(id) Then
  650. Api_NotFound
  651. Exit Sub
  652. End If
  653. Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId))
  654. If rs.EOF Then
  655. rs.Close
  656. Api_NotFound
  657. Exit Sub
  658. End If
  659. nsId = "" & rs(0)
  660. curRev = CLng(rs(1))
  661. rs.Close
  662. If Not Api_CanAccessNamespace(nsId, "read") Then
  663. Api_NotFound
  664. Exit Sub
  665. End If
  666. rev = curRev
  667. q = Trim("" & Request.QueryString("revision"))
  668. If Len(q) > 0 Then
  669. ' Api_ToInt clamps, so check the range on the raw value
  670. rev = -1
  671. If Len(q) <= 9 Then
  672. If IsNumeric(q) Then
  673. If InStr(q, ".") = 0 Then
  674. rev = CLng(q)
  675. End If
  676. End If
  677. End If
  678. If rev < 1 Or rev > curRev Then
  679. Api_Invalid Array("revision must be a whole number between 1 and " & curRev & ".")
  680. Exit Sub
  681. End If
  682. End If
  683. Set rs = DAL().Query("SELECT method, result, notes, reviewer_principal_id, created_at FROM verifications WHERE memory_id = ? AND revision = ? ORDER BY created_at", Array(id, rev))
  684. ver = ""
  685. n = 0
  686. Do While Not rs.EOF
  687. If n > 0 Then
  688. ver = ver & ","
  689. End If
  690. ver = ver & "{""method"":" & JsonLite_Quote("" & rs(0)) & ",""result"":" & JsonLite_Quote("" & rs(1)) & ",""notes"":" & JStr(rs(2)) & _
  691. ",""reviewer"":" & JsonLite_Quote("" & rs(3)) & ",""created_at"":" & JsonLite_Quote("" & rs(4)) & "}"
  692. n = n + 1
  693. rs.MoveNext
  694. Loop
  695. rs.Close
  696. Set rs = DAL().Query("SELECT id FROM learning_candidates WHERE resulting_memory_id = ? AND resulting_revision = ? AND tenant_id = ?", Array(id, rev, Api_TenantId))
  697. cand = "null"
  698. If Not rs.EOF Then
  699. cand = JsonLite_Quote("" & rs(0))
  700. End If
  701. rs.Close
  702. Api_Send 200, "{""memory_id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""current_revision"":" & curRev & _
  703. ",""from_candidate"":" & cand & ",""evidence"":" & EvidenceJson("memory", id, rev) & ",""verifications"":[" & ver & "]}"
  704. End Sub
  705. '---------------------------------------------------------------
  706. ' POST /api/v1/feedback
  707. '---------------------------------------------------------------
  708. Public Sub Feedback()
  709. Dim body, input, queryId, resultId, usefulness, comment, rs, kind, rev, nsId, ts, fbId, k, existing
  710. If Not Api_Authenticate() Then Exit Sub
  711. body = Api_ReadBody()
  712. If IsEmpty(body) Then Exit Sub
  713. Set input = JsonLite_Parse(body)
  714. m_errs = ""
  715. queryId = ReqString(input, "query_id", 80)
  716. resultId = ReqString(input, "result_id", 64)
  717. usefulness = LCase("" & ReqString(input, "usefulness", 20))
  718. comment = OptString(input, "comment", 2000)
  719. If Len(m_errs) = 0 Then
  720. If usefulness <> "useful" And usefulness <> "not_useful" And usefulness <> "incorrect" And usefulness <> "harmful" Then
  721. AddErr "usefulness must be useful, not_useful, incorrect or harmful."
  722. End If
  723. If Left(queryId, 4) <> "qry-" Or Not Api_IsId(Mid(queryId, 5)) Then
  724. AddErr "query_id must be a query id returned by recall, search or context."
  725. End If
  726. If Not Api_IsId(resultId) Then
  727. AddErr "result_id must be a valid id."
  728. End If
  729. End If
  730. If Len(m_errs) > 0 Then
  731. Api_Invalid Split(m_errs, Chr(30))
  732. Exit Sub
  733. End If
  734. ' The result must belong to that query, in this tenant, and still be readable by the caller.
  735. Set rs = DAL().Query("SELECT r.target_kind, r.target_revision FROM retrieval_results r JOIN retrieval_queries q ON q.id = r.query_id " & _
  736. "WHERE r.query_id = ? AND r.target_id = ? AND q.tenant_id = ?", Array(queryId, resultId, Api_TenantId))
  737. If rs.EOF Then
  738. rs.Close
  739. Api_Error 404, "result_not_found", "That result was not returned by that query."
  740. Exit Sub
  741. End If
  742. kind = "" & rs(0)
  743. rev = CLng(rs(1))
  744. rs.Close
  745. nsId = ""
  746. If kind = "memory" Then
  747. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(resultId, Api_TenantId))
  748. Else
  749. Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(resultId, Api_TenantId))
  750. End If
  751. If Not rs.EOF Then
  752. nsId = "" & rs(0)
  753. End If
  754. rs.Close
  755. If Len(nsId) = 0 Then
  756. Api_Error 404, "result_not_found", "That result was not returned by that query."
  757. Exit Sub
  758. End If
  759. If Not Api_CanAccessNamespace(nsId, "read") Then
  760. Api_Error 404, "result_not_found", "That result was not returned by that query."
  761. Exit Sub
  762. End If
  763. ' One rating per principal, query and result; a new submission replaces the earlier one.
  764. Set rs = DAL().Query("SELECT id FROM feedback WHERE query_id = ? AND target_kind = ? AND target_id = ? AND principal_id = ?", Array(queryId, kind, resultId, Api_PrincipalId))
  765. existing = ""
  766. If Not rs.EOF Then
  767. existing = "" & rs(0)
  768. End If
  769. rs.Close
  770. ts = Api_Now()
  771. On Error Resume Next
  772. If Len(existing) > 0 Then
  773. fbId = existing
  774. DAL().Execute "UPDATE feedback SET usefulness = ?, comment = ?, updated_at = ? WHERE id = ?", Array(usefulness, comment, ts, fbId)
  775. Else
  776. fbId = Api_NewId()
  777. ' 8-parameter limit: the server-generated timestamp is inlined (ISO text from Api_Now, no user input)
  778. DAL().Execute "INSERT INTO feedback (id, tenant_id, query_id, target_kind, target_id, target_revision, principal_id, usefulness, created_at, updated_at) " & _
  779. "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & ts & "', '" & ts & "')", Array(fbId, Api_TenantId, queryId, kind, resultId, rev, Api_PrincipalId, usefulness)
  780. DAL().Execute "UPDATE feedback SET comment = ? WHERE id = ?", Array(comment, fbId)
  781. End If
  782. If Err.Number <> 0 Then
  783. k = Err.Number : Api_NoteDbError
  784. Api_DbFailed k, ""
  785. Exit Sub
  786. End If
  787. On Error GoTo 0
  788. Api_Audit "retrieval.feedback", kind, resultId, usefulness
  789. If Len(existing) > 0 Then
  790. Api_Send 200, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness)
  791. Else
  792. Api_Send 201, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness)
  793. End If
  794. End Sub
  795. '===============================================================
  796. ' Helpers
  797. '===============================================================
  798. Private Function FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness)
  799. FeedbackJson = "{""id"":" & JsonLite_Quote(fbId) & ",""query_id"":" & JsonLite_Quote(queryId) & ",""target_kind"":" & JsonLite_Quote(kind) & _
  800. ",""target_id"":" & JsonLite_Quote(resultId) & ",""target_revision"":" & rev & ",""usefulness"":" & JsonLite_Quote(usefulness) & "}"
  801. End Function
  802. ' Columns: 0 id, 1 namespace_id, 2 type, 3 title, 4 summary, 5 content, 6 tags, 7 confidence, 8 target_memory_id, 9 base_revision,
  803. ' 10 state, 11 author, 12 reviewer, 13 review_notes, 14 resulting_memory_id, 15 resulting_revision, 16 created_at, 17 reviewed_at
  804. Private Function CandidateSelect()
  805. CandidateSelect = "SELECT id, namespace_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision, state, " & _
  806. "author_principal_id, reviewer_principal_id, review_notes, resulting_memory_id, resulting_revision, created_at, reviewed_at FROM learning_candidates"
  807. End Function
  808. Private Function CandidateJson(rs, brief)
  809. Dim s
  810. s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _
  811. ",""title"":" & JsonLite_Quote("" & rs(3)) & ",""summary"":" & JStr(rs(4))
  812. If Not brief Then
  813. s = s & ",""content"":" & JsonLite_Quote("" & rs(5))
  814. End If
  815. s = s & ",""tags"":" & JRaw(rs(6), "[]") & ",""confidence"":" & JNum(rs(7)) & ",""target_memory_id"":" & JStr(rs(8)) & ",""base_revision"":" & JNum(rs(9)) & _
  816. ",""state"":" & JsonLite_Quote("" & rs(10)) & ",""author"":" & JsonLite_Quote("" & rs(11)) & ",""reviewer"":" & JStr(rs(12)) & _
  817. ",""review_notes"":" & JStr(rs(13)) & ",""resulting_memory_id"":" & JStr(rs(14)) & ",""resulting_revision"":" & JNum(rs(15)) & _
  818. ",""created_at"":" & JsonLite_Quote("" & rs(16)) & ",""reviewed_at"":" & JStr(rs(17)) & ",""content_trust"":""proposed_knowledge""}"
  819. CandidateJson = s
  820. End Function
  821. ' Evidence of an owner as a JSON array. A target the caller cannot read (or that is gone) is shown without its id.
  822. Private Function EvidenceJson(ownerKind, ownerId, ownerRev)
  823. Dim rs, rows, i, out, kind, tid, ns, avail, r2
  824. If IsNull(ownerRev) Then
  825. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND tenant_id = ? ORDER BY created_at, id", _
  826. Array(ownerKind, ownerId, Api_TenantId))
  827. Else
  828. Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND owner_revision = ? AND tenant_id = ? ORDER BY created_at, id", _
  829. Array(ownerKind, ownerId, CLng(ownerRev), Api_TenantId))
  830. End If
  831. rows = Empty
  832. If Not rs.EOF Then
  833. rows = rs.GetRows()
  834. End If
  835. rs.Close
  836. out = ""
  837. If Not IsEmpty(rows) Then
  838. For i = 0 To UBound(rows, 2)
  839. kind = "" & rows(0, i)
  840. tid = "" & rows(1, i)
  841. ns = TargetNamespace(kind, tid)
  842. avail = False
  843. If Len(ns) > 0 Then
  844. avail = Api_CanAccessNamespace(ns, "read")
  845. End If
  846. If i > 0 Then
  847. out = out & ","
  848. End If
  849. out = out & "{""kind"":" & JsonLite_Quote(kind)
  850. If avail Then
  851. out = out & ",""id"":" & JsonLite_Quote(tid) & ",""revision"":" & JNum(rows(2, i))
  852. End If
  853. out = out & ",""available"":" & LCase(CStr(avail)) & ",""role"":" & JsonLite_Quote("" & rows(3, i))
  854. If avail Then
  855. out = out & ",""excerpt"":" & JStr(rows(4, i))
  856. End If
  857. out = out & ",""content_trust"":"""
  858. If kind = "chunk" Or kind = "document" Then
  859. out = out & "untrusted_reference"
  860. Else
  861. out = out & "evidence"
  862. End If
  863. out = out & """}"
  864. Next
  865. End If
  866. EvidenceJson = "[" & out & "]"
  867. End Function
  868. Private Function TargetNamespace(kind, tid)
  869. Dim rs
  870. TargetNamespace = ""
  871. Select Case kind
  872. Case "experience"
  873. Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  874. Case "chunk"
  875. Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(tid, Api_TenantId))
  876. Case "memory"
  877. Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  878. Case Else
  879. Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId))
  880. End Select
  881. If Not rs.EOF Then
  882. TargetNamespace = "" & rs(0)
  883. End If
  884. rs.Close
  885. End Function
  886. Private Function JStr(v)
  887. If IsNull(v) Then
  888. JStr = "null"
  889. Else
  890. JStr = JsonLite_Quote("" & v)
  891. End If
  892. End Function
  893. Private Function JNum(v)
  894. If IsNull(v) Then
  895. JNum = "null"
  896. ElseIf Len("" & v) = 0 Then
  897. JNum = "null"
  898. Else
  899. JNum = JsonLite_Num(v)
  900. End If
  901. End Function
  902. Private Function JRaw(v, dflt)
  903. If IsNull(v) Then
  904. JRaw = dflt
  905. ElseIf Len("" & v) = 0 Then
  906. JRaw = dflt
  907. Else
  908. JRaw = "" & v
  909. End If
  910. End Function
  911. Private Sub AddErr(msg)
  912. If Len(m_errs) > 0 Then
  913. m_errs = m_errs & Chr(30)
  914. End If
  915. m_errs = m_errs & msg
  916. End Sub
  917. Private Function ReqString(input, name, maxLen)
  918. Dim v
  919. ReqString = ""
  920. If Not input.Exists(name) Then
  921. AddErr name & " is required."
  922. Exit Function
  923. End If
  924. v = input.Item(name)
  925. If IsNull(v) Then
  926. AddErr name & " is required."
  927. Exit Function
  928. End If
  929. If VarType(v) <> vbString Then
  930. AddErr name & " must be a string."
  931. Exit Function
  932. End If
  933. v = Trim(v)
  934. If Len(v) = 0 Then
  935. AddErr name & " must not be empty."
  936. Exit Function
  937. End If
  938. If Len(v) > maxLen Then
  939. AddErr name & " must be at most " & maxLen & " characters."
  940. Exit Function
  941. End If
  942. ReqString = v
  943. End Function
  944. Private Function OptString(input, name, maxLen)
  945. Dim v
  946. OptString = Null
  947. If Not input.Exists(name) Then
  948. Exit Function
  949. End If
  950. v = input.Item(name)
  951. If IsNull(v) Then
  952. Exit Function
  953. End If
  954. If VarType(v) <> vbString Then
  955. AddErr name & " must be a string."
  956. Exit Function
  957. End If
  958. If Len(v) > maxLen Then
  959. AddErr name & " must be at most " & maxLen & " characters."
  960. Exit Function
  961. End If
  962. OptString = v
  963. End Function
  964. Private Function OptUnit(input, name)
  965. Dim v
  966. OptUnit = Null
  967. If Not input.Exists(name) Then
  968. Exit Function
  969. End If
  970. v = input.Item(name)
  971. If IsNull(v) Then
  972. Exit Function
  973. End If
  974. If VarType(v) <> vbDouble Then
  975. AddErr name & " must be a number between 0 and 1."
  976. Exit Function
  977. End If
  978. If v < 0 Or v > 1 Then
  979. AddErr name & " must be between 0 and 1."
  980. Exit Function
  981. End If
  982. OptUnit = v
  983. End Function
  984. Private Function TagsJson(input)
  985. Dim arr, i, out, t
  986. TagsJson = Null
  987. If Not input.HasRaw("tags") Then
  988. If input.Exists("tags") Then
  989. If Not IsNull(input.Item("tags")) Then
  990. AddErr "tags must be an array of strings."
  991. End If
  992. End If
  993. Exit Function
  994. End If
  995. arr = JsonLite_ParseStringArray(input.Raw("tags"))
  996. If IsNull(arr) Then
  997. AddErr "tags must be an array of strings."
  998. Exit Function
  999. End If
  1000. If UBound(arr) > 31 Then
  1001. AddErr "tags may contain at most 32 entries."
  1002. Exit Function
  1003. End If
  1004. out = ""
  1005. For i = 0 To UBound(arr)
  1006. t = Trim(arr(i))
  1007. If Len(t) = 0 Or Len(t) > 64 Then
  1008. AddErr "each tag must be 1 to 64 characters."
  1009. Exit Function
  1010. End If
  1011. If i > 0 Then
  1012. out = out & ","
  1013. End If
  1014. out = out & JsonLite_Quote(t)
  1015. Next
  1016. TagsJson = "[" & out & "]"
  1017. End Function
  1018. ' Optional JSON object stored as raw text (max 16 KB), or Null
  1019. Private Function ObjectJson(input, name)
  1020. Dim raw
  1021. ObjectJson = Null
  1022. If Not input.HasRaw(name) Then
  1023. If input.Exists(name) Then
  1024. If Not IsNull(input.Item(name)) Then
  1025. AddErr name & " must be a JSON object."
  1026. End If
  1027. End If
  1028. Exit Function
  1029. End If
  1030. raw = input.Raw(name)
  1031. If Left(raw, 1) <> "{" Then
  1032. AddErr name & " must be a JSON object."
  1033. Exit Function
  1034. End If
  1035. If Len(raw) > 16384 Then
  1036. AddErr name & " must be at most 16 KB."
  1037. Exit Function
  1038. End If
  1039. ObjectJson = raw
  1040. End Function
  1041. ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites)
  1042. Public Sub Invoke(actionName, args)
  1043. Select Case LCase(actionName)
  1044. Case "recordevent" : RecordEvent args(0)
  1045. Case "events" : Events args(0)
  1046. Case "learn" : Learn
  1047. Case "candidates" : Candidates
  1048. Case "candidate" : Candidate args(0)
  1049. Case "review" : Review args(0)
  1050. Case "sources" : Sources args(0)
  1051. Case "feedback" : Feedback
  1052. Case "consolidate" : Consolidate
  1053. Case Else
  1054. Err.Raise 438, "ApiLearningController_Class", "Action '" & actionName & "' not found"
  1055. End Select
  1056. End Sub
  1057. End Class
  1058. Dim ApiLearningController_Class__Singleton
  1059. Function ApiLearningController()
  1060. If IsEmpty(ApiLearningController_Class__Singleton) Then
  1061. Set ApiLearningController_Class__Singleton = New ApiLearningController_Class
  1062. End If
  1063. Set ApiLearningController = ApiLearningController_Class__Singleton
  1064. End Function
  1065. ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
  1066. Sub ApiLearningController_Invoke(actionName, args)
  1067. ApiLearningController().Invoke actionName, args
  1068. End Sub
  1069. %>

Powered by TurnKey Linux.