<% ' ApiLearningController: experiences, learning candidates and review, evidence, feedback (spec FR-012, FR-013, ' FR-014, FR-020, section 12, AC-08, AC-16, AC-18). Stateless JSON API, no layout. ' Helpers: core/lib.Api.asp (auth, errors), core/lib.Learning.asp (evidence, memory writes, telemetry). ' ' POST /api/v1/sessions/:id/events RecordEvent {"task","outcome":"success|failure|partial|unknown","problem","action","result","environment":{}} ' GET /api/v1/sessions/:id/events Events experiences of the session, oldest first ' POST /api/v1/learn Learn {"namespace_id","type","title","content","summary","tags","confidence", ' "target_memory_id","base_revision","evidence":[{"kind","id","role","excerpt"}]} ' GET /api/v1/candidates Candidates ?namespace_id= &state=proposed|accepted|rejected &limit= ' GET /api/v1/candidates/:id Candidate with its evidence ' POST /api/v1/candidates/:id/review Review {"decision":"accept|reject","notes","verify":true|false} ' GET /api/v1/memories/:id/sources Sources evidence and verifications of a revision (?revision=, default current) ' POST /api/v1/feedback Feedback {"query_id","result_id","usefulness":"useful|not_useful|incorrect|harmful","comment"} ' POST /api/v1/consolidations Consolidate {"namespace_id","since","min_size":2,"similarity":0.35,"max_experiences":300,"propose":false} ' groups similar experiences (core/lib.Consolidation.asp) with a draft each; ' "propose": true files each group with at least min_size experiences not yet ' cited by any candidate as a proposed candidate (tag "consolidated") ' ' Permissions on the namespace: write (RecordEvent, Learn, Consolidate with propose), read (Consolidate, Candidates, Candidate, Sources, Feedback), ' verify (Review). Reviewing your own candidate needs admin: a proposer cannot approve itself. Accepting creates a ' memory (or a new revision of target_memory_id, if it is still at base_revision) with the candidate's evidence; it ' stays unverified unless "verify": true, which records a verification by the reviewer. Without permission: 404. Class ApiLearningController_Class Private m_errs Public Property Get useLayout() useLayout = False End Property Public Property Let useLayout(v) End Property Public Property Get Title() Title = "Learning API" End Property '--------------------------------------------------------------- ' POST /api/v1/sessions/:id/events '--------------------------------------------------------------- Public Sub RecordEvent(id) Dim body, input, idemKey, reqHash, rs, nsId, status, task, outcome, problem, action, result, envRaw, expId, ts, resp, k If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) idemKey = Api_Header("Idempotency-Key") If Len(idemKey) > 200 Then Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." Exit Sub End If reqHash = Api_Sha256("events|" & id & "|" & body) If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_Error 404, "session_not_found", "Session not found." Exit Sub End If nsId = "" & rs(0) status = "" & rs(1) rs.Close If Not Api_CanAccessNamespace(nsId, "write") Then Api_Error 404, "session_not_found", "Session not found." Exit Sub End If m_errs = "" task = ReqString(input, "task", 2000) outcome = LCase("" & ReqString(input, "outcome", 20)) problem = OptString(input, "problem", 4000) action = OptString(input, "action", 4000) result = OptString(input, "result", 4000) envRaw = ObjectJson(input, "environment") If Len(m_errs) = 0 Then If outcome <> "success" And outcome <> "failure" And outcome <> "partial" And outcome <> "unknown" Then AddErr "outcome must be success, failure, partial or unknown." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If status <> "active" Then Api_Error 409, "session_not_active", "The session is " & status & "; experiences can only be recorded in an active session." Exit Sub End If expId = Api_NewId() ts = Api_Now() resp = "{""id"":" & JsonLite_Quote(expId) & ",""session_id"":" & JsonLite_Quote(id) & ",""outcome"":" & JsonLite_Quote(outcome) & ",""created_at"":" & JsonLite_Quote(ts) & "}" On Error Resume Next DAL().BeginTransaction DAL().Execute "INSERT INTO experiences (id, tenant_id, namespace_id, session_id, principal_id, task, outcome, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ Array(expId, Api_TenantId, nsId, id, Api_PrincipalId, task, outcome, ts) DAL().Execute "UPDATE experiences SET problem = ?, action = ?, result = ?, environment = ? WHERE id = ?", Array(problem, action, result, envRaw, expId) Api_IdempotencyStore idemKey, reqHash, 201, resp If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction On Error GoTo 0 Api_Audit "session.event", "experience", expId, "ok" Api_Send 201, resp End Sub '--------------------------------------------------------------- ' GET /api/v1/sessions/:id/events '--------------------------------------------------------------- Public Sub Events(id) Dim rs, nsId, out, n If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT namespace_id FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_Error 404, "session_not_found", "Session not found." Exit Sub End If nsId = "" & rs(0) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_Error 404, "session_not_found", "Session not found." Exit Sub End If Set rs = DAL().Query("SELECT id, task, problem, action, result, outcome, environment, principal_id, created_at FROM experiences " & _ "WHERE session_id = ? AND tenant_id = ? ORDER BY created_at, id LIMIT 200", Array(id, Api_TenantId)) out = "" n = 0 Do While Not rs.EOF If n > 0 Then out = out & "," End If out = out & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""task"":" & JsonLite_Quote("" & rs(1)) & ",""problem"":" & JStr(rs(2)) & _ ",""action"":" & JStr(rs(3)) & ",""result"":" & JStr(rs(4)) & ",""outcome"":" & JsonLite_Quote("" & rs(5)) & _ ",""environment"":" & JRaw(rs(6), "null") & ",""recorded_by"":" & JsonLite_Quote("" & rs(7)) & ",""created_at"":" & JsonLite_Quote("" & rs(8)) & "}" n = n + 1 rs.MoveNext Loop rs.Close Api_Send 200, "{""session_id"":" & JsonLite_Quote(id) & ",""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' POST /api/v1/learn '--------------------------------------------------------------- Public Sub Learn() Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, confidence, targetId, baseRev Dim ev, msg, rs, candId, ts, resp, k If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) idemKey = Api_Header("Idempotency-Key") If Len(idemKey) > 200 Then Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." Exit Sub End If reqHash = Api_Sha256("learn|" & body) If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub m_errs = "" nsId = ReqString(input, "namespace_id", 64) memType = LCase("" & ReqString(input, "type", 40)) title = ReqString(input, "title", 200) content = ReqString(input, "content", 100000) summary = OptString(input, "summary", 2000) tagsRaw = TagsJson(input) confidence = OptUnit(input, "confidence") targetId = OptString(input, "target_memory_id", 64) baseRev = Null If Not IsNull(targetId) Then If Not Api_IsId(targetId) Then AddErr "target_memory_id must be a valid id." End If If Not input.Exists("base_revision") Then AddErr "base_revision is required with target_memory_id." ElseIf VarType(input.Item("base_revision")) <> vbDouble Then AddErr "base_revision must be a number." Else baseRev = CLng(input.Item("base_revision")) End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If Not Api_CanAccessNamespace(nsId, "write") Then Api_Audit "candidate.learn", "namespace", nsId, "denied" Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType) If rs.EOF Then rs.Close Api_Invalid Array("type '" & memType & "' is not a known memory type.") Exit Sub End If rs.Close If Not IsNull(targetId) Then ' A revision proposal must target a memory of the same namespace and type that the caller can read. Set rs = DAL().Query("SELECT 1 FROM memories WHERE id = ? AND tenant_id = ? AND namespace_id = ? AND type = ?", Array(targetId, Api_TenantId, nsId, memType)) If rs.EOF Then rs.Close Api_Invalid Array("target_memory_id was not found in this namespace with this type.") Exit Sub End If rs.Close End If Set ev = New Evidence_Class msg = ev.Load(input, "evidence") If Len(msg) > 0 Then Api_Invalid Array(msg) Exit Sub End If candId = Api_NewId() ts = Api_Now() resp = "{""id"":" & JsonLite_Quote(candId) & ",""state"":""proposed"",""namespace_id"":" & JsonLite_Quote(nsId) & ",""type"":" & JsonLite_Quote(memType) & _ ",""evidence_count"":" & ev.Count & "}" On Error Resume Next DAL().BeginTransaction DAL().Execute "INSERT INTO learning_candidates (id, tenant_id, namespace_id, type, title, content, author_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ Array(candId, Api_TenantId, nsId, memType, title, content, Api_PrincipalId, ts) DAL().Execute "UPDATE learning_candidates SET summary = ?, tags = ?, confidence = ?, target_memory_id = ?, base_revision = ? WHERE id = ?", _ Array(summary, tagsRaw, confidence, targetId, baseRev, candId) ev.Save "candidate", candId, Null Api_IdempotencyStore idemKey, reqHash, 201, resp If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction On Error GoTo 0 Api_Audit "candidate.learn", "candidate", candId, "ok" Response.AddHeader "Location", "/api/v1/candidates/" & candId Api_Send 201, resp End Sub '--------------------------------------------------------------- ' POST /api/v1/consolidations '--------------------------------------------------------------- Public Sub Consolidate() Dim body, input, nsId, since, minSize, sim, maxRows, propose, perm, c, groups, g, members, i, k, idList, rs, cited Dim out, oc, terms, termsJson, idsJson, draftType, draftTitle, draftContent, candId, created, ts, evN, cj If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" nsId = ReqString(input, "namespace_id", 64) since = OptString(input, "since", 19) If IsNull(since) Then since = "0000-00-00 00:00:00" Else Dim reTs Set reTs = New RegExp reTs.Pattern = "^[0-9]{4}-[0-9]{2}-[0-9]{2}( [0-9]{2}:[0-9]{2}:[0-9]{2})?$" If Not reTs.Test(since) Then AddErr "since must be a UTC time like 2026-12-01 or 2026-12-01 08:00:00." End If End If minSize = OptNumber(input, "min_size", 2, 2, 50) sim = OptNumber(input, "similarity", 0.35, 0.1, 0.95) maxRows = OptNumber(input, "max_experiences", 300, 10, 500) propose = False If input.Exists("propose") Then If VarType(input.Item("propose")) = vbBoolean Then propose = input.Item("propose") Else AddErr "propose must be true or false." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If perm = "read" If propose Then perm = "write" End If If Not Api_CanAccessNamespace(nsId, perm) Then Api_Audit "candidate.consolidate", "namespace", nsId, "denied" Api_Error 404, "namespace_not_found", "Namespace not found." Exit Sub End If Set c = New Consolidator_Class c.Load Api_TenantId, nsId, since, CLng(maxRows) c.Cluster CDbl(sim) groups = c.Groups(CLng(minSize)) out = "" created = 0 ts = Api_Now() If propose Then On Error Resume Next DAL().BeginTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 End If For g = 0 To UBound(groups) members = Split(groups(g), ",") idList = "" idsJson = "" For i = 0 To UBound(members) If i > 0 Then idList = idList & "," idsJson = idsJson & "," End If idList = idList & "'" & c.Id(CLng(members(i))) & "'" idsJson = idsJson & JsonLite_Quote(c.Id(CLng(members(i)))) Next ' Experiences already cited by any candidate (proposed, accepted or rejected) count as handled. Set rs = DAL().Query("SELECT COUNT(DISTINCT e.target_id) FROM evidence_links e WHERE e.tenant_id = ? AND e.owner_kind = 'candidate' " & _ "AND e.target_kind = 'experience' AND e.target_id IN (" & idList & ")", Api_TenantId) cited = CLng(rs(0)) rs.Close oc = Split(c.OutcomeCounts(groups(g)), ",") terms = Split(c.TopTerms(groups(g), 5), ",") termsJson = "" For i = 0 To UBound(terms) If i > 0 Then termsJson = termsJson & "," End If termsJson = termsJson & JsonLite_Quote(terms(i)) Next draftType = c.DraftType(groups(g)) draftTitle = c.DraftTitle(groups(g)) draftContent = c.DraftContent(groups(g)) candId = Null If propose And (UBound(members) + 1 - cited) >= CLng(minSize) Then candId = Api_NewId() On Error Resume Next DAL().Execute "INSERT INTO learning_candidates (id, tenant_id, namespace_id, type, title, content, author_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ Array(candId, Api_TenantId, nsId, draftType, draftTitle, draftContent, Api_PrincipalId, ts) DAL().Execute "UPDATE learning_candidates SET tags = ? WHERE id = ?", Array("[""consolidated""]", candId) ' Evidence: the most recent members (rows are newest first), up to EVIDENCE_MAX. evN = UBound(members) If evN > EVIDENCE_MAX - 1 Then evN = EVIDENCE_MAX - 1 End If For i = 0 To evN k = CLng(members(i)) 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', ?, ?)", _ Array(Api_NewId(), Api_TenantId, candId, c.Id(k), Api_PrincipalId, ts) Next If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Err.Clear DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 created = created + 1 End If If Len(out) > 0 Then out = out & "," End If If IsNull(candId) Then cj = "null" Else cj = JsonLite_Quote(candId) End If out = out & "{""size"":" & (UBound(members) + 1) & ",""sessions"":" & c.SessionCount(groups(g)) & _ ",""outcomes"":{""success"":" & oc(0) & ",""failure"":" & oc(1) & ",""partial"":" & oc(2) & ",""unknown"":" & oc(3) & "}" & _ ",""first_seen"":" & JsonLite_Quote(c.Created(CLng(members(UBound(members))))) & ",""last_seen"":" & JsonLite_Quote(c.Created(CLng(members(0)))) & _ ",""terms"":[" & termsJson & "],""experience_ids"":[" & idsJson & "],""already_cited"":" & cited & _ ",""draft"":{""type"":" & JsonLite_Quote(draftType) & ",""title"":" & JsonLite_Quote(draftTitle) & ",""content"":" & JsonLite_Quote(draftContent) & "}" & _ ",""candidate_id"":" & cj & "}" Next If propose Then On Error Resume Next DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 End If If propose Then Api_Audit "candidate.consolidate", "namespace", nsId, created & " proposed" End If Api_Send 200, "{""namespace_id"":" & JsonLite_Quote(nsId) & ",""experiences_considered"":" & c.Count & _ ",""similarity"":" & JsonLite_Num(sim) & ",""min_size"":" & CLng(minSize) & ",""candidates_created"":" & created & _ ",""groups"":[" & out & "]}" End Sub ' Optional JSON number within [lo, hi]; dflt when absent. Adds an error when out of range or not a number. Private Function OptNumber(input, name, dflt, lo, hi) Dim v OptNumber = dflt If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbDouble Then AddErr name & " must be a number." Exit Function End If If v < lo Or v > hi Then AddErr name & " must be between " & lo & " and " & hi & "." Exit Function End If OptNumber = v End Function '--------------------------------------------------------------- ' GET /api/v1/candidates '--------------------------------------------------------------- Public Sub Candidates() Dim allowed, nsFilter, state, limit, sql, rs, out, n If Not Api_Authenticate() Then Exit Sub nsFilter = Trim("" & Request.QueryString("namespace_id")) state = LCase(Trim("" & Request.QueryString("state"))) limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200) If Len(state) > 0 Then If state <> "proposed" And state <> "accepted" And state <> "rejected" Then Api_Invalid Array("state must be proposed, accepted or rejected.") Exit Sub End If End If If Len(nsFilter) > 0 Then If Not Api_IsId(nsFilter) Then Api_Invalid Array("namespace_id must be a valid id.") Exit Sub End If End If allowed = Api_AllowedNamespaceIds("read") out = "" n = 0 If Len(allowed) > 0 Then sql = CandidateSelect() & " WHERE tenant_id = ? AND namespace_id IN (" & allowed & ")" If Len(nsFilter) > 0 Then sql = sql & " AND namespace_id = '" & nsFilter & "'" End If If Len(state) > 0 Then sql = sql & " AND state = '" & state & "'" End If Set rs = DAL().Query(sql & " ORDER BY created_at DESC, id LIMIT " & limit, Api_TenantId) Do While Not rs.EOF If n > 0 Then out = out & "," End If out = out & CandidateJson(rs, True) n = n + 1 rs.MoveNext Loop rs.Close End If Api_Send 200, "{""data"":[" & out & "]}" End Sub '--------------------------------------------------------------- ' GET /api/v1/candidates/:id '--------------------------------------------------------------- Public Sub Candidate(id) Dim rs, json, nsId If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query(CandidateSelect() & " WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(1) json = CandidateJson(rs, False) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If json = Left(json, Len(json) - 1) & ",""evidence"":" & EvidenceJson("candidate", id, Null) & "}" Api_Send 200, "{""data"":" & json & "}" End Sub '--------------------------------------------------------------- ' POST /api/v1/candidates/:id/review '--------------------------------------------------------------- Public Sub Review(id) Dim body, input, rs, nsId, state, author, memType, title, summary, content, tagsRaw, confidence, targetId, baseRev Dim decision, notes, doVerify, ts, k, memId, rev, dup, tNs, tType, tRev, tStatus, verStatus, hash If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) Set rs = DAL().Query("SELECT namespace_id, state, author_principal_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision " & _ "FROM learning_candidates WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) state = "" & rs(1) author = "" & rs(2) memType = "" & rs(3) title = "" & rs(4) summary = rs(5) content = "" & rs(6) tagsRaw = rs(7) confidence = rs(8) targetId = rs(9) baseRev = rs(10) rs.Close If Not Api_CanAccessNamespace(nsId, "verify") Then Api_Audit "candidate.review", "candidate", id, "denied" Api_NotFound Exit Sub End If m_errs = "" decision = LCase("" & ReqString(input, "decision", 20)) notes = OptString(input, "notes", 2000) doVerify = False If input.Exists("verify") Then If VarType(input.Item("verify")) = vbBoolean Then doVerify = input.Item("verify") ElseIf Not IsNull(input.Item("verify")) Then AddErr "verify must be true or false." End If End If If Len(m_errs) = 0 Then If decision <> "accept" And decision <> "reject" Then AddErr "decision must be accept or reject." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If If state <> "proposed" Then Api_Error 409, "candidate_already_reviewed", "The candidate was already " & state & "." Exit Sub End If If author = Api_PrincipalId Then If Not Api_CanAccessNamespace(nsId, "admin") Then Api_Audit "candidate.review", "candidate", id, "self_review_denied" Api_Error 403, "self_review_not_allowed", "A candidate cannot be reviewed by its author without admin permission on the namespace." Exit Sub End If End If ts = Api_Now() If decision = "reject" Then On Error Resume Next DAL().Execute "UPDATE learning_candidates SET state = 'rejected', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ? WHERE id = ? AND state = 'proposed'", _ Array(Api_PrincipalId, notes, ts, id) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "candidate.review", "candidate", id, "rejected" Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""rejected""}" Exit Sub End If ' accept: check the target (revision proposals) or look for an identical active memory (new memories) dup = False memId = "" rev = 0 If Not IsNull(targetId) Then Set rs = DAL().Query("SELECT namespace_id, type, current_revision, lifecycle_status FROM memories WHERE id = ? AND tenant_id = ?", Array("" & targetId, Api_TenantId)) If rs.EOF Then rs.Close Api_Error 409, "target_memory_missing", "The memory this candidate revises no longer exists." Exit Sub End If tNs = "" & rs(0) tType = "" & rs(1) tRev = CLng(rs(2)) tStatus = "" & rs(3) rs.Close If tStatus <> "active" Then Api_Error 409, "target_memory_not_active", "The memory this candidate revises is " & tStatus & "." Exit Sub End If If tRev <> CLng(baseRev) Then Api_Error 409, "stale_candidate", "The memory changed since the candidate was proposed (base revision " & baseRev & ", current " & tRev & ")." Exit Sub End If Else hash = Mem_Hash(nsId, memType, title, content) 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 " & _ "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)) If Not rs.EOF Then dup = True memId = "" & rs(0) rev = CLng(rs(1)) End If rs.Close End If On Error Resume Next DAL().BeginTransaction If Not IsNull(targetId) Then memId = "" & targetId rev = Mem_Revise(memId, nsId, memType, tRev, title, summary, content, tagsRaw, confidence, "accepted candidate " & id) ElseIf Not dup Then memId = Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, "accepted candidate " & id) rev = 1 End If Evidence_CopyCandidate id, memId, rev If doVerify Then Mem_Verify memId, rev, "candidate_review", notes End If DAL().Execute "UPDATE learning_candidates SET state = 'accepted', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ?, resulting_memory_id = ?, resulting_revision = ? " & _ "WHERE id = ? AND state = 'proposed'", Array(Api_PrincipalId, notes, ts, memId, rev, id) If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError DAL().RollbackTransaction Api_DbFailed k, "" Exit Sub End If DAL().CommitTransaction If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Set rs = DAL().Query("SELECT verification_status FROM memory_revisions WHERE memory_id = ? AND revision = ?", Array(memId, rev)) verStatus = "unverified" If Not rs.EOF Then verStatus = "" & rs(0) End If rs.Close Emb_AfterWrite Api_TenantId, 8 Api_Audit "candidate.review", "candidate", id, "accepted" Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""accepted"",""resulting_memory_id"":" & JsonLite_Quote(memId) & _ ",""resulting_revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(verStatus) & ",""duplicate"":" & LCase(CStr(dup)) & "}" End Sub '--------------------------------------------------------------- ' GET /api/v1/memories/:id/sources '--------------------------------------------------------------- Public Sub Sources(id) Dim rs, nsId, curRev, rev, q, ver, n, cand If Not Api_Authenticate() Then Exit Sub If Not Api_IsId(id) Then Api_NotFound Exit Sub End If Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) If rs.EOF Then rs.Close Api_NotFound Exit Sub End If nsId = "" & rs(0) curRev = CLng(rs(1)) rs.Close If Not Api_CanAccessNamespace(nsId, "read") Then Api_NotFound Exit Sub End If rev = curRev q = Trim("" & Request.QueryString("revision")) If Len(q) > 0 Then ' Api_ToInt clamps, so check the range on the raw value rev = -1 If Len(q) <= 9 Then If IsNumeric(q) Then If InStr(q, ".") = 0 Then rev = CLng(q) End If End If End If If rev < 1 Or rev > curRev Then Api_Invalid Array("revision must be a whole number between 1 and " & curRev & ".") Exit Sub End If End If 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)) ver = "" n = 0 Do While Not rs.EOF If n > 0 Then ver = ver & "," End If ver = ver & "{""method"":" & JsonLite_Quote("" & rs(0)) & ",""result"":" & JsonLite_Quote("" & rs(1)) & ",""notes"":" & JStr(rs(2)) & _ ",""reviewer"":" & JsonLite_Quote("" & rs(3)) & ",""created_at"":" & JsonLite_Quote("" & rs(4)) & "}" n = n + 1 rs.MoveNext Loop rs.Close Set rs = DAL().Query("SELECT id FROM learning_candidates WHERE resulting_memory_id = ? AND resulting_revision = ? AND tenant_id = ?", Array(id, rev, Api_TenantId)) cand = "null" If Not rs.EOF Then cand = JsonLite_Quote("" & rs(0)) End If rs.Close Api_Send 200, "{""memory_id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""current_revision"":" & curRev & _ ",""from_candidate"":" & cand & ",""evidence"":" & EvidenceJson("memory", id, rev) & ",""verifications"":[" & ver & "]}" End Sub '--------------------------------------------------------------- ' POST /api/v1/feedback '--------------------------------------------------------------- Public Sub Feedback() Dim body, input, queryId, resultId, usefulness, comment, rs, kind, rev, nsId, ts, fbId, k, existing If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub Set input = JsonLite_Parse(body) m_errs = "" queryId = ReqString(input, "query_id", 80) resultId = ReqString(input, "result_id", 64) usefulness = LCase("" & ReqString(input, "usefulness", 20)) comment = OptString(input, "comment", 2000) If Len(m_errs) = 0 Then If usefulness <> "useful" And usefulness <> "not_useful" And usefulness <> "incorrect" And usefulness <> "harmful" Then AddErr "usefulness must be useful, not_useful, incorrect or harmful." End If If Left(queryId, 4) <> "qry-" Or Not Api_IsId(Mid(queryId, 5)) Then AddErr "query_id must be a query id returned by recall, search or context." End If If Not Api_IsId(resultId) Then AddErr "result_id must be a valid id." End If End If If Len(m_errs) > 0 Then Api_Invalid Split(m_errs, Chr(30)) Exit Sub End If ' The result must belong to that query, in this tenant, and still be readable by the caller. 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 " & _ "WHERE r.query_id = ? AND r.target_id = ? AND q.tenant_id = ?", Array(queryId, resultId, Api_TenantId)) If rs.EOF Then rs.Close Api_Error 404, "result_not_found", "That result was not returned by that query." Exit Sub End If kind = "" & rs(0) rev = CLng(rs(1)) rs.Close nsId = "" If kind = "memory" Then Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(resultId, Api_TenantId)) Else 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)) End If If Not rs.EOF Then nsId = "" & rs(0) End If rs.Close If Len(nsId) = 0 Then Api_Error 404, "result_not_found", "That result was not returned by that query." Exit Sub End If If Not Api_CanAccessNamespace(nsId, "read") Then Api_Error 404, "result_not_found", "That result was not returned by that query." Exit Sub End If ' One rating per principal, query and result; a new submission replaces the earlier one. 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)) existing = "" If Not rs.EOF Then existing = "" & rs(0) End If rs.Close ts = Api_Now() On Error Resume Next If Len(existing) > 0 Then fbId = existing DAL().Execute "UPDATE feedback SET usefulness = ?, comment = ?, updated_at = ? WHERE id = ?", Array(usefulness, comment, ts, fbId) Else fbId = Api_NewId() ' 8-parameter limit: the server-generated timestamp is inlined (ISO text from Api_Now, no user input) DAL().Execute "INSERT INTO feedback (id, tenant_id, query_id, target_kind, target_id, target_revision, principal_id, usefulness, created_at, updated_at) " & _ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & ts & "', '" & ts & "')", Array(fbId, Api_TenantId, queryId, kind, resultId, rev, Api_PrincipalId, usefulness) DAL().Execute "UPDATE feedback SET comment = ? WHERE id = ?", Array(comment, fbId) End If If Err.Number <> 0 Then k = Err.Number : Api_NoteDbError Api_DbFailed k, "" Exit Sub End If On Error GoTo 0 Api_Audit "retrieval.feedback", kind, resultId, usefulness If Len(existing) > 0 Then Api_Send 200, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness) Else Api_Send 201, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness) End If End Sub '=============================================================== ' Helpers '=============================================================== Private Function FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness) FeedbackJson = "{""id"":" & JsonLite_Quote(fbId) & ",""query_id"":" & JsonLite_Quote(queryId) & ",""target_kind"":" & JsonLite_Quote(kind) & _ ",""target_id"":" & JsonLite_Quote(resultId) & ",""target_revision"":" & rev & ",""usefulness"":" & JsonLite_Quote(usefulness) & "}" End Function ' 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, ' 10 state, 11 author, 12 reviewer, 13 review_notes, 14 resulting_memory_id, 15 resulting_revision, 16 created_at, 17 reviewed_at Private Function CandidateSelect() CandidateSelect = "SELECT id, namespace_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision, state, " & _ "author_principal_id, reviewer_principal_id, review_notes, resulting_memory_id, resulting_revision, created_at, reviewed_at FROM learning_candidates" End Function Private Function CandidateJson(rs, brief) Dim s s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _ ",""title"":" & JsonLite_Quote("" & rs(3)) & ",""summary"":" & JStr(rs(4)) If Not brief Then s = s & ",""content"":" & JsonLite_Quote("" & rs(5)) End If s = s & ",""tags"":" & JRaw(rs(6), "[]") & ",""confidence"":" & JNum(rs(7)) & ",""target_memory_id"":" & JStr(rs(8)) & ",""base_revision"":" & JNum(rs(9)) & _ ",""state"":" & JsonLite_Quote("" & rs(10)) & ",""author"":" & JsonLite_Quote("" & rs(11)) & ",""reviewer"":" & JStr(rs(12)) & _ ",""review_notes"":" & JStr(rs(13)) & ",""resulting_memory_id"":" & JStr(rs(14)) & ",""resulting_revision"":" & JNum(rs(15)) & _ ",""created_at"":" & JsonLite_Quote("" & rs(16)) & ",""reviewed_at"":" & JStr(rs(17)) & ",""content_trust"":""proposed_knowledge""}" CandidateJson = s End Function ' Evidence of an owner as a JSON array. A target the caller cannot read (or that is gone) is shown without its id. Private Function EvidenceJson(ownerKind, ownerId, ownerRev) Dim rs, rows, i, out, kind, tid, ns, avail, r2 If IsNull(ownerRev) Then 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", _ Array(ownerKind, ownerId, Api_TenantId)) Else 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", _ Array(ownerKind, ownerId, CLng(ownerRev), Api_TenantId)) End If rows = Empty If Not rs.EOF Then rows = rs.GetRows() End If rs.Close out = "" If Not IsEmpty(rows) Then For i = 0 To UBound(rows, 2) kind = "" & rows(0, i) tid = "" & rows(1, i) ns = TargetNamespace(kind, tid) avail = False If Len(ns) > 0 Then avail = Api_CanAccessNamespace(ns, "read") End If If i > 0 Then out = out & "," End If out = out & "{""kind"":" & JsonLite_Quote(kind) If avail Then out = out & ",""id"":" & JsonLite_Quote(tid) & ",""revision"":" & JNum(rows(2, i)) End If out = out & ",""available"":" & LCase(CStr(avail)) & ",""role"":" & JsonLite_Quote("" & rows(3, i)) If avail Then out = out & ",""excerpt"":" & JStr(rows(4, i)) End If out = out & ",""content_trust"":""" If kind = "chunk" Or kind = "document" Then out = out & "untrusted_reference" Else out = out & "evidence" End If out = out & """}" Next End If EvidenceJson = "[" & out & "]" End Function Private Function TargetNamespace(kind, tid) Dim rs TargetNamespace = "" Select Case kind Case "experience" Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId)) Case "chunk" 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)) Case "memory" Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId)) Case Else Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId)) End Select If Not rs.EOF Then TargetNamespace = "" & rs(0) End If rs.Close End Function Private Function JStr(v) If IsNull(v) Then JStr = "null" Else JStr = JsonLite_Quote("" & v) End If End Function Private Function JNum(v) If IsNull(v) Then JNum = "null" ElseIf Len("" & v) = 0 Then JNum = "null" Else JNum = JsonLite_Num(v) End If End Function Private Function JRaw(v, dflt) If IsNull(v) Then JRaw = dflt ElseIf Len("" & v) = 0 Then JRaw = dflt Else JRaw = "" & v End If End Function Private Sub AddErr(msg) If Len(m_errs) > 0 Then m_errs = m_errs & Chr(30) End If m_errs = m_errs & msg End Sub Private Function ReqString(input, name, maxLen) Dim v ReqString = "" If Not input.Exists(name) Then AddErr name & " is required." Exit Function End If v = input.Item(name) If IsNull(v) Then AddErr name & " is required." Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If v = Trim(v) If Len(v) = 0 Then AddErr name & " must not be empty." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If ReqString = v End Function Private Function OptString(input, name, maxLen) Dim v OptString = Null If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbString Then AddErr name & " must be a string." Exit Function End If If Len(v) > maxLen Then AddErr name & " must be at most " & maxLen & " characters." Exit Function End If OptString = v End Function Private Function OptUnit(input, name) Dim v OptUnit = Null If Not input.Exists(name) Then Exit Function End If v = input.Item(name) If IsNull(v) Then Exit Function End If If VarType(v) <> vbDouble Then AddErr name & " must be a number between 0 and 1." Exit Function End If If v < 0 Or v > 1 Then AddErr name & " must be between 0 and 1." Exit Function End If OptUnit = v End Function Private Function TagsJson(input) Dim arr, i, out, t TagsJson = Null If Not input.HasRaw("tags") Then If input.Exists("tags") Then If Not IsNull(input.Item("tags")) Then AddErr "tags must be an array of strings." End If End If Exit Function End If arr = JsonLite_ParseStringArray(input.Raw("tags")) If IsNull(arr) Then AddErr "tags must be an array of strings." Exit Function End If If UBound(arr) > 31 Then AddErr "tags may contain at most 32 entries." Exit Function End If out = "" For i = 0 To UBound(arr) t = Trim(arr(i)) If Len(t) = 0 Or Len(t) > 64 Then AddErr "each tag must be 1 to 64 characters." Exit Function End If If i > 0 Then out = out & "," End If out = out & JsonLite_Quote(t) Next TagsJson = "[" & out & "]" End Function ' Optional JSON object stored as raw text (max 16 KB), or Null Private Function ObjectJson(input, name) Dim raw ObjectJson = Null If Not input.HasRaw(name) Then If input.Exists(name) Then If Not IsNull(input.Item(name)) Then AddErr name & " must be a JSON object." End If End If Exit Function End If raw = input.Raw(name) If Left(raw, 1) <> "{" Then AddErr name & " must be a JSON object." Exit Function End If If Len(raw) > 16384 Then AddErr name & " must be at most 16 KB." Exit Function End If ObjectJson = raw End Function ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) Public Sub Invoke(actionName, args) Select Case LCase(actionName) Case "recordevent" : RecordEvent args(0) Case "events" : Events args(0) Case "learn" : Learn Case "candidates" : Candidates Case "candidate" : Candidate args(0) Case "review" : Review args(0) Case "sources" : Sources args(0) Case "feedback" : Feedback Case "consolidate" : Consolidate Case Else Err.Raise 438, "ApiLearningController_Class", "Action '" & actionName & "' not found" End Select End Sub End Class Dim ApiLearningController_Class__Singleton Function ApiLearningController() If IsEmpty(ApiLearningController_Class__Singleton) Then Set ApiLearningController_Class__Singleton = New ApiLearningController_Class End If Set ApiLearningController = ApiLearningController_Class__Singleton End Function ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) Sub ApiLearningController_Invoke(actionName, args) ApiLearningController().Invoke actionName, args End Sub %>