|
- <%
- ' ApiPortabilityController: canonical export and import (spec FR-018, NFR-007, NFR-009, AC-06, AC-14).
- '
- ' POST /api/v1/exports Export {"namespace_ids":[...]} (optional; default: every namespace the caller can read)
- ' POST /api/v1/imports Import the document returned by /exports, unchanged (max 8 MiB)
- '
- ' Export document (schema_version 1):
- ' {"format":"agent-memory-export","schema_version":1,"exported_at":"...","data":{...},"counts":{...},
- ' "integrity":{"algorithm":"sha256","digest":"<sha256 of the exact text of data>"}}
- ' data.namespaces [{path}], data.memories [{id, namespace, type, lifecycle_status, valid_from, valid_until, created_by,
- ' created_at, updated_at, current_revision, revisions[...], verifications[...]}], data.documents [{id, namespace,
- ' source_uri, format, title, current_revision, created_by, created_at, updated_at, revisions[{..., chunks[...]}]}],
- ' data.evidence_links [{id, owner_kind:"memory", owner_id, owner_revision, target_kind, target_id, target_revision,
- ' role, excerpt, created_by, created_at}].
- ' Canonical records keep their ids, revision numbers, timestamps and principal ids (provenance). Derived data
- ' (lexical and semantic indexes, content hashes) is rebuilt on import. Not exported in version 1: sessions,
- ' experiences, learning candidates, feedback, retrieval telemetry, audit events. Evidence whose target the caller
- ' cannot read is left out (counted in counts.evidence_links_omitted).
- '
- ' Import needs admin on every target namespace (matched by path in the caller's tenant; they must exist). Any id that
- ' already exists makes the whole import fail (409); any invalid item fails it with 422; nothing is written then.
- Const PORT_FORMAT = "agent-memory-export"
- Const PORT_SCHEMA = 1
- Const PORT_MAX_IMPORT = 8388608
-
- ' List of strings joined with a separator, on the native G3STRINGBUILDER (string concatenation in a loop is
- ' quadratic). The export runs all its queries before building, so no builder is held across G3DB calls.
- Class Port_Buf
- Private m_sb, m_n, m_sep
-
- Private Sub Class_Initialize()
- Set m_sb = Server.CreateObject("G3STRINGBUILDER")
- m_n = 0
- m_sep = ","
- End Sub
-
- Private Sub Class_Terminate()
- Set m_sb = Nothing
- End Sub
-
- ' Separator put between items (default ",")
- Public Property Let Sep(v)
- m_sep = v
- End Property
-
- Public Sub Add(s)
- If m_n > 0 Then
- If Len(m_sep) > 0 Then
- m_sb.Append m_sep
- End If
- End If
- m_sb.Append s
- m_n = m_n + 1
- End Sub
-
- Public Property Get Count()
- Count = m_n
- End Property
-
- Public Function Text()
- Text = m_sb.ToString()
- End Function
- End Class
-
- Class ApiPortabilityController_Class
- ' import state
- Private m_err, m_nsPaths(), m_nsIds(), m_nsN, m_types, m_memIds, m_cnt(), m_placeholders
-
- Public Property Get useLayout()
- useLayout = False
- End Property
-
- Public Property Let useLayout(v)
- End Property
-
- Public Property Get Title()
- Title = "Portability API"
- End Property
-
- '---------------------------------------------------------------
- ' POST /api/v1/exports
- '---------------------------------------------------------------
- Public Sub Export()
- Dim body, input, allowed, requested, arr, i, ok, rs, nsRows, memRows, revRows, verRows, docRows, drRows, chRows, evRows
- Dim data, tq, nsList, m, p, v, d, dr, ch, item, sub1, sub2, nMem, nRev, nVer, nDoc, nDr, nCh, nEv, nEvAll, digest, out, ts
-
- If Not Api_Authenticate() Then Exit Sub
- body = Api_ReadBody()
- If IsEmpty(body) Then Exit Sub
- Set input = JsonLite_Parse(body)
-
- allowed = Api_AllowedNamespaceIds("read")
- If input.HasRaw("namespace_ids") Then
- arr = JsonLite_ParseStringArray(input.Raw("namespace_ids"))
- If IsNull(arr) Then
- Api_Invalid Array("namespace_ids must be an array of namespace ids.")
- Exit Sub
- End If
- requested = ""
- For i = 0 To UBound(arr)
- If Not Api_IsId(arr(i)) Then
- Api_Invalid Array("namespace_ids must be an array of namespace ids.")
- Exit Sub
- End If
- ' only ids the caller can read; others are silently left out (no existence disclosure)
- If InStr("," & allowed & ",", ",'" & LCase(arr(i)) & "',") > 0 Then
- If Len(requested) > 0 Then
- requested = requested & ","
- End If
- requested = requested & "'" & LCase(arr(i)) & "'"
- End If
- Next
- allowed = requested
- ElseIf input.Exists("namespace_ids") Then
- If Not IsNull(input.Item("namespace_ids")) Then
- Api_Invalid Array("namespace_ids must be an array of namespace ids.")
- Exit Sub
- End If
- End If
-
- ts = Api_Now()
- Set data = New Port_Buf
- data.Sep = "" ' items below carry their own commas
- nMem = 0 : nRev = 0 : nVer = 0 : nDoc = 0 : nDr = 0 : nCh = 0 : nEv = 0 : nEvAll = 0
- nsRows = Empty : memRows = Empty : revRows = Empty : verRows = Empty : docRows = Empty : drRows = Empty : chRows = Empty : evRows = Empty
- If Len(allowed) > 0 Then
- tq = "'" & Api_TenantId & "'" ' authenticated tenant id (a UUID), safe to inline
- nsRows = Rows("SELECT id, path FROM namespaces WHERE tenant_id = " & tq & " AND id IN (" & allowed & ") ORDER BY path")
- memRows = Rows("SELECT id, namespace_id, type, lifecycle_status, valid_from, valid_until, creator_principal_id, created_at, updated_at, current_revision " & _
- "FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ") ORDER BY id")
- revRows = Rows("SELECT r.memory_id, r.id, r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.change_reason, " & _
- "r.verification_status, r.created_by, r.created_at FROM memory_revisions r JOIN memories m ON m.id = r.memory_id " & _
- "WHERE m.tenant_id = " & tq & " AND m.namespace_id IN (" & allowed & ") ORDER BY r.memory_id, r.revision")
- verRows = Rows("SELECT v.memory_id, v.id, v.revision, v.method, v.result, v.notes, v.reviewer_principal_id, v.created_at FROM verifications v " & _
- "JOIN memories m ON m.id = v.memory_id WHERE m.tenant_id = " & tq & " AND m.namespace_id IN (" & allowed & ") ORDER BY v.memory_id, v.created_at, v.id")
- docRows = Rows("SELECT id, namespace_id, source_uri, format, title, current_revision, created_by, created_at, updated_at FROM documents " & _
- "WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ") ORDER BY id")
- drRows = Rows("SELECT r.document_id, r.id, r.revision, r.content, r.char_count, r.chunk_count, r.created_by, r.created_at FROM document_revisions r " & _
- "JOIN documents d ON d.id = r.document_id WHERE d.tenant_id = " & tq & " AND d.namespace_id IN (" & allowed & ") ORDER BY r.document_id, r.revision")
- chRows = Rows("SELECT c.document_id, c.document_revision, c.id, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, c.token_estimate, c.created_at " & _
- "FROM chunks c JOIN documents d ON d.id = c.document_id WHERE d.tenant_id = " & tq & " AND d.namespace_id IN (" & allowed & ") " & _
- "ORDER BY c.document_id, c.document_revision, c.ordinal")
- ' evidence of exported memories whose target the caller can read
- evRows = Rows("SELECT id, owner_id, owner_revision, target_kind, target_id, target_revision, role, excerpt, created_by, created_at FROM evidence_links e " & _
- "WHERE e.tenant_id = " & tq & " AND e.owner_kind = 'memory' AND e.owner_id IN (SELECT id FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ")) AND (" & _
- "(e.target_kind = 'memory' AND e.target_id IN (SELECT id FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & "))) OR " & _
- "(e.target_kind = 'document' AND e.target_id IN (SELECT id FROM documents WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & "))) OR " & _
- "(e.target_kind = 'chunk' AND e.target_id IN (SELECT c.id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE d.tenant_id = " & tq & " AND d.namespace_id IN (" & allowed & "))) OR " & _
- "(e.target_kind = 'experience' AND e.target_id IN (SELECT id FROM experiences WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ")))) ORDER BY e.created_at, e.id")
- Set rs = DAL().Query("SELECT COUNT(*) FROM evidence_links WHERE tenant_id = " & tq & " AND owner_kind = 'memory' AND owner_id IN (SELECT id FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & "))", Empty)
- nEvAll = CLng(rs(0))
- rs.Close
- End If
-
- ' namespaces
- Set nsList = New Port_Buf
- If Not IsEmpty(nsRows) Then
- For i = 0 To UBound(nsRows, 2)
- nsList.Add "{""path"":" & JsonLite_Quote("" & nsRows(1, i)) & "}"
- Next
- End If
- data.Add "{""namespaces"":[" & nsList.Text() & "],""memories"":["
-
- ' memories with revisions and verifications (all three ordered by memory id: merge in one pass)
- p = 0
- v = 0
- If Not IsEmpty(memRows) Then
- For m = 0 To UBound(memRows, 2)
- Set sub1 = New Port_Buf
- Do While p <= RowsMax(revRows)
- If "" & revRows(0, p) <> "" & memRows(0, m) Then
- Exit Do
- End If
- sub1.Add "{""id"":" & JsonLite_Quote("" & revRows(1, p)) & ",""revision"":" & CLng(revRows(2, p)) & ",""title"":" & JsonLite_Quote("" & revRows(3, p)) & _
- ",""summary"":" & JStr(revRows(4, p)) & ",""content"":" & JsonLite_Quote("" & revRows(5, p)) & ",""attributes"":" & JRaw(revRows(6, p)) & _
- ",""tags"":" & JRaw(revRows(7, p)) & ",""confidence"":" & JNum(revRows(8, p)) & ",""importance"":" & JNum(revRows(9, p)) & _
- ",""change_reason"":" & JStr(revRows(10, p)) & ",""verification_status"":" & JsonLite_Quote("" & revRows(11, p)) & _
- ",""created_by"":" & JsonLite_Quote("" & revRows(12, p)) & ",""created_at"":" & JsonLite_Quote("" & revRows(13, p)) & "}"
- nRev = nRev + 1
- p = p + 1
- Loop
- Set sub2 = New Port_Buf
- Do While v <= RowsMax(verRows)
- If "" & verRows(0, v) <> "" & memRows(0, m) Then
- Exit Do
- End If
- sub2.Add "{""id"":" & JsonLite_Quote("" & verRows(1, v)) & ",""revision"":" & CLng(verRows(2, v)) & ",""method"":" & JsonLite_Quote("" & verRows(3, v)) & _
- ",""result"":" & JsonLite_Quote("" & verRows(4, v)) & ",""notes"":" & JStr(verRows(5, v)) & ",""reviewer"":" & JsonLite_Quote("" & verRows(6, v)) & _
- ",""created_at"":" & JsonLite_Quote("" & verRows(7, v)) & "}"
- nVer = nVer + 1
- v = v + 1
- Loop
- item = "{""id"":" & JsonLite_Quote("" & memRows(0, m)) & ",""namespace"":" & JsonLite_Quote(NsPath(nsRows, "" & memRows(1, m))) & _
- ",""type"":" & JsonLite_Quote("" & memRows(2, m)) & ",""lifecycle_status"":" & JsonLite_Quote("" & memRows(3, m)) & _
- ",""valid_from"":" & JStr(memRows(4, m)) & ",""valid_until"":" & JStr(memRows(5, m)) & ",""created_by"":" & JsonLite_Quote("" & memRows(6, m)) & _
- ",""created_at"":" & JsonLite_Quote("" & memRows(7, m)) & ",""updated_at"":" & JsonLite_Quote("" & memRows(8, m)) & _
- ",""current_revision"":" & CLng(memRows(9, m)) & ",""revisions"":[" & sub1.Text() & "],""verifications"":[" & sub2.Text() & "]}"
- If m > 0 Then
- item = "," & item
- End If
- data.Add item
- nMem = nMem + 1
- Next
- End If
- data.Add "],""documents"":["
-
- ' documents with revisions and their chunks
- dr = 0
- ch = 0
- If Not IsEmpty(docRows) Then
- For d = 0 To UBound(docRows, 2)
- Set sub1 = New Port_Buf
- Do While dr <= RowsMax(drRows)
- If "" & drRows(0, dr) <> "" & docRows(0, d) Then
- Exit Do
- End If
- Set sub2 = New Port_Buf
- Do While ch <= RowsMax(chRows)
- If "" & chRows(0, ch) <> "" & docRows(0, d) Then
- Exit Do
- End If
- If CLng(chRows(1, ch)) <> CLng(drRows(2, dr)) Then
- Exit Do
- End If
- sub2.Add "{""id"":" & JsonLite_Quote("" & chRows(2, ch)) & ",""ordinal"":" & CLng(chRows(3, ch)) & ",""content"":" & JsonLite_Quote("" & chRows(4, ch)) & _
- ",""heading_path"":" & JStr(chRows(5, ch)) & ",""start_offset"":" & CLng(chRows(6, ch)) & ",""end_offset"":" & CLng(chRows(7, ch)) & _
- ",""token_estimate"":" & CLng(chRows(8, ch)) & ",""created_at"":" & JsonLite_Quote("" & chRows(9, ch)) & "}"
- nCh = nCh + 1
- ch = ch + 1
- Loop
- sub1.Add "{""id"":" & JsonLite_Quote("" & drRows(1, dr)) & ",""revision"":" & CLng(drRows(2, dr)) & ",""content"":" & JsonLite_Quote("" & drRows(3, dr)) & _
- ",""created_by"":" & JsonLite_Quote("" & drRows(6, dr)) & ",""created_at"":" & JsonLite_Quote("" & drRows(7, dr)) & ",""chunks"":[" & sub2.Text() & "]}"
- nDr = nDr + 1
- dr = dr + 1
- Loop
- item = "{""id"":" & JsonLite_Quote("" & docRows(0, d)) & ",""namespace"":" & JsonLite_Quote(NsPath(nsRows, "" & docRows(1, d))) & _
- ",""source_uri"":" & JStr(docRows(2, d)) & ",""format"":" & JsonLite_Quote("" & docRows(3, d)) & ",""title"":" & JsonLite_Quote("" & docRows(4, d)) & _
- ",""current_revision"":" & CLng(docRows(5, d)) & ",""created_by"":" & JsonLite_Quote("" & docRows(6, d)) & ",""created_at"":" & JsonLite_Quote("" & docRows(7, d)) & _
- ",""updated_at"":" & JsonLite_Quote("" & docRows(8, d)) & ",""revisions"":[" & sub1.Text() & "]}"
- If d > 0 Then
- item = "," & item
- End If
- data.Add item
- nDoc = nDoc + 1
- Next
- End If
- data.Add "],""evidence_links"":["
- If Not IsEmpty(evRows) Then
- For i = 0 To UBound(evRows, 2)
- item = "{""id"":" & JsonLite_Quote("" & evRows(0, i)) & ",""owner_kind"":""memory"",""owner_id"":" & JsonLite_Quote("" & evRows(1, i)) & _
- ",""owner_revision"":" & JNum(evRows(2, i)) & ",""target_kind"":" & JsonLite_Quote("" & evRows(3, i)) & ",""target_id"":" & JsonLite_Quote("" & evRows(4, i)) & _
- ",""target_revision"":" & JNum(evRows(5, i)) & ",""role"":" & JsonLite_Quote("" & evRows(6, i)) & ",""excerpt"":" & JStr(evRows(7, i)) & _
- ",""created_by"":" & JsonLite_Quote("" & evRows(8, i)) & ",""created_at"":" & JsonLite_Quote("" & evRows(9, i)) & "}"
- If i > 0 Then
- item = "," & item
- End If
- data.Add item
- nEv = nEv + 1
- Next
- End If
- data.Add "]}"
-
- out = data.Text()
- digest = Api_Sha256(out)
- Api_Audit "export.create", "export", "", "ok"
- Response.AddHeader "Content-Disposition", "attachment; filename=""agent-memory-export.json"""
- Api_Send 200, "{""format"":""" & PORT_FORMAT & """,""schema_version"":" & PORT_SCHEMA & ",""exported_at"":" & JsonLite_Quote(ts) & _
- ",""data"":" & out & ",""counts"":{""namespaces"":" & (RowsMax(nsRows) + 1) & ",""memories"":" & nMem & ",""memory_revisions"":" & nRev & _
- ",""verifications"":" & nVer & ",""documents"":" & nDoc & ",""document_revisions"":" & nDr & ",""chunks"":" & nCh & ",""evidence_links"":" & nEv & _
- ",""evidence_links_omitted"":" & (nEvAll - nEv) & "},""integrity"":{""algorithm"":""sha256"",""digest"":""" & digest & """}}"
- End Sub
-
- '---------------------------------------------------------------
- ' POST /api/v1/imports
- '---------------------------------------------------------------
- Public Sub Import()
- Dim body, input, dataRaw, integ, data, items, i, k, rs
-
- If Not Api_Authenticate() Then Exit Sub
- body = Api_ReadBodyMax(PORT_MAX_IMPORT)
- If IsEmpty(body) Then Exit Sub
- Set input = JsonLite_Parse(body)
-
- ' envelope and integrity
- If "" & input.Item("format") <> PORT_FORMAT Then
- Api_Invalid Array("format must be """ & PORT_FORMAT & """ (a document produced by POST /exports).")
- Exit Sub
- End If
- If VarType(input.Item("schema_version")) <> vbDouble Then
- Api_Invalid Array("schema_version is required.")
- Exit Sub
- End If
- If input.Item("schema_version") <> PORT_SCHEMA Then
- Api_Error 422, "unsupported_schema_version", "schema_version " & input.Item("schema_version") & " is not supported; this server reads version " & PORT_SCHEMA & "."
- Exit Sub
- End If
- If Not input.HasRaw("data") Then
- Api_Invalid Array("data is required.")
- Exit Sub
- End If
- dataRaw = input.Raw("data")
- If Not input.HasRaw("integrity") Then
- Api_Invalid Array("integrity is required.")
- Exit Sub
- End If
- Set integ = JsonLite_Parse(input.Raw("integrity"))
- If integ Is Nothing Then
- Api_Invalid Array("integrity must be an object.")
- Exit Sub
- End If
- If LCase("" & integ.Item("algorithm")) <> "sha256" Then
- Api_Invalid Array("integrity.algorithm must be sha256.")
- Exit Sub
- End If
- If LCase("" & integ.Item("digest")) <> Api_Sha256(dataRaw) Then
- Api_Error 422, "integrity_mismatch", "The sha256 digest of data does not match integrity.digest. The export was changed or reformatted after it was produced."
- Exit Sub
- End If
- Set data = JsonLite_Parse(dataRaw)
- If data Is Nothing Then
- Api_Invalid Array("data must be an object.")
- Exit Sub
- End If
-
- ReDim m_cnt(7)
- For i = 0 To 7
- m_cnt(i) = 0
- Next
- m_err = ""
- m_placeholders = 0
- m_memIds = ","
- m_nsN = 0
- ReDim m_nsPaths(15)
- ReDim m_nsIds(15)
- m_types = ","
- Set rs = DAL().Query("SELECT code FROM memory_types", Empty)
- Do While Not rs.EOF
- m_types = m_types & LCase("" & rs(0)) & ","
- rs.MoveNext
- Loop
- rs.Close
-
- ' namespaces: every path must exist in the caller's tenant with admin permission
- items = ArrayOf(data, "namespaces")
- If Len(m_err) = 0 Then
- For i = 0 To UBound(items)
- ResolveNamespace items(i)
- If Len(m_err) > 0 Then
- Exit For
- End If
- Next
- End If
- If Len(m_err) > 0 Then
- Api_Invalid Array(m_err)
- Exit Sub
- End If
-
- 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
-
- items = ArrayOf(data, "memories")
- If Len(m_err) = 0 Then
- For i = 0 To UBound(items)
- ImportMemory items(i), i
- If Len(m_err) > 0 Then
- Exit For
- End If
- Next
- End If
- If Len(m_err) = 0 Then
- items = ArrayOf(data, "documents")
- End If
- If Len(m_err) = 0 Then
- For i = 0 To UBound(items)
- ImportDocument items(i), i
- If Len(m_err) > 0 Then
- Exit For
- End If
- Next
- End If
- If Len(m_err) = 0 Then
- items = ArrayOf(data, "evidence_links")
- End If
- If Len(m_err) = 0 Then
- For i = 0 To UBound(items)
- ImportEvidence items(i), i
- If Len(m_err) > 0 Then
- Exit For
- End If
- Next
- End If
-
- ' Author ids from another installation get placeholder principals (no keys, cannot sign in) so references
- ' stay valid; the ids themselves are kept as provenance.
- If Len(m_err) = 0 Then
- On Error Resume Next
- m_placeholders = Api_EnsureReferencedPrincipals(Api_TenantId)
- If Err.Number <> 0 Then
- m_err = "db:" & Err.Description
- Err.Clear
- End If
- On Error GoTo 0
- End If
-
- If Len(m_err) > 0 Then
- On Error Resume Next
- DAL().RollbackTransaction
- On Error GoTo 0
- If Left(m_err, 9) = "conflict:" Then
- Api_Error 409, "import_conflict", Mid(m_err, 11) & " Nothing was imported."
- ElseIf Left(m_err, 3) = "db:" Then
- Api_Error 500, "internal_error", "Import failed while writing (" & Mid(m_err, 4) & "). Nothing was imported."
- Else
- Api_Invalid Array(m_err & " Nothing was imported.")
- End If
- Api_Audit "import.apply", "import", "", "failed"
- Exit Sub
- End If
-
- 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
-
- Emb_AfterWrite Api_TenantId, 8
- Api_Audit "import.apply", "import", "", "ok"
- Api_Send 201, "{""imported"":{""namespaces"":" & m_nsN & ",""memories"":" & m_cnt(0) & ",""memory_revisions"":" & m_cnt(1) & ",""verifications"":" & m_cnt(2) & _
- ",""documents"":" & m_cnt(3) & ",""document_revisions"":" & m_cnt(4) & ",""chunks"":" & m_cnt(5) & ",""evidence_links"":" & m_cnt(6) & ",""placeholder_principals"":" & m_placeholders & "}" & _
- ",""indexing"":{""lexical"":""indexed"",""semantic"":""pending""}}"
- End Sub
-
- '===============================================================
- ' Import helpers. Each sets m_err ("" = fine; "conflict: ..." = 409; "db: ..." = 500; else 422) and returns.
- '===============================================================
- Private Sub ResolveNamespace(objText)
- Dim o, path, rs, id
- Set o = JsonLite_Parse(objText)
- path = ""
- If Not o Is Nothing Then
- path = Trim("" & o.Item("path"))
- End If
- If Len(path) = 0 Or Left(path, 1) <> "/" Then
- m_err = "data.namespaces: each entry needs a path starting with /."
- Exit Sub
- End If
- Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, path))
- id = ""
- If Not rs.EOF Then
- id = "" & rs(0)
- End If
- rs.Close
- If Len(id) = 0 Then
- m_err = "namespace " & path & " does not exist or you lack admin permission on it (create it and grant admin first)."
- Exit Sub
- End If
- If Not Api_CanAccessNamespace(id, "admin") Then
- m_err = "namespace " & path & " does not exist or you lack admin permission on it (create it and grant admin first)."
- Exit Sub
- End If
- If m_nsN > UBound(m_nsPaths) Then
- ReDim Preserve m_nsPaths(m_nsN * 2)
- ReDim Preserve m_nsIds(m_nsN * 2)
- End If
- m_nsPaths(m_nsN) = path
- m_nsIds(m_nsN) = id
- m_nsN = m_nsN + 1
- End Sub
-
- Private Function NsIdOf(path)
- Dim i
- NsIdOf = ""
- For i = 0 To m_nsN - 1
- If m_nsPaths(i) = path Then
- NsIdOf = m_nsIds(i)
- Exit Function
- End If
- Next
- End Function
-
- Private Sub ImportMemory(objText, idx)
- Dim o, at, id, nsId, memType, life, curRev, revs, vers, i, r, rv, rid, title, content, tagsRaw, attrRaw, vs, curTitle, curContent, curTags, revSeen, ver
-
- at = "data.memories[" & idx & "]"
- Set o = JsonLite_Parse(objText)
- If o Is Nothing Then
- m_err = at & " must be an object."
- Exit Sub
- End If
- id = NeedId(o, "id", at)
- nsId = NeedNs(o, at)
- memType = LCase(NeedStr(o, "type", at, 40))
- life = NeedEnum(o, "lifecycle_status", at, ",active,retired,superseded,")
- curRev = NeedInt(o, "current_revision", at, 1, 100000)
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If InStr(m_types, "," & memType & ",") = 0 Then
- m_err = at & ".type '" & memType & "' is not a known memory type."
- Exit Sub
- End If
- If IdTaken("SELECT 1 FROM memories WHERE id = ?", id) Then
- m_err = "conflict: memory " & id & " already exists."
- Exit Sub
- End If
-
- revs = ArrayOf(o, "revisions")
- If Len(m_err) > 0 Then
- m_err = at & ": " & m_err
- Exit Sub
- End If
- If UBound(revs) + 1 <> curRev Then
- m_err = at & ".revisions must hold revisions 1.." & curRev & " (current_revision)."
- Exit Sub
- End If
- On Error Resume Next
- DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) VALUES (?, ?, ?, ?, " & curRev & ", ?, ?, ?, ?)", _
- Array(id, Api_TenantId, nsId, memType, life, NeedId(o, "created_by", at), NeedTs(o, "created_at", at), NeedTs(o, "updated_at", at))
- DAL().Execute "UPDATE memories SET valid_from = ?, valid_until = ? WHERE id = ?", Array(OptStr(o, "valid_from", at, 40), OptStr(o, "valid_until", at, 40), id)
- If Err.Number <> 0 Then
- m_err = "db: memory " & id & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- m_cnt(0) = m_cnt(0) + 1
- m_memIds = m_memIds & id & ","
-
- revSeen = ","
- For i = 0 To UBound(revs)
- Set r = JsonLite_Parse(revs(i))
- rv = at & ".revisions[" & i & "]"
- If r Is Nothing Then
- m_err = rv & " must be an object."
- Exit Sub
- End If
- rid = NeedId(r, "id", rv)
- ver = NeedInt(r, "revision", rv, 1, curRev)
- title = NeedStr(r, "title", rv, 200)
- content = NeedStr(r, "content", rv, 100000)
- vs = NeedEnum(r, "verification_status", rv, ",unverified,verified,disputed,rejected,")
- tagsRaw = OptRaw(r, "tags", rv, "[")
- attrRaw = OptRaw(r, "attributes", rv, "{")
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If InStr(revSeen, "," & ver & ",") > 0 Then
- m_err = rv & ".revision " & ver & " appears twice."
- Exit Sub
- End If
- revSeen = revSeen & ver & ","
- If IdTaken("SELECT 1 FROM memory_revisions WHERE id = ?", rid) Then
- m_err = "conflict: memory revision " & rid & " already exists."
- Exit Sub
- End If
- On Error Resume Next
- DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) VALUES (?, ?, " & ver & ", ?, ?, ?, ?, ?)", _
- Array(rid, id, title, content, Mem_Hash(nsId, memType, title, content), NeedId(r, "created_by", rv), NeedTs(r, "created_at", rv))
- DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ?, verification_status = ? WHERE id = ?", _
- Array(OptStr(r, "summary", rv, 2000), attrRaw, tagsRaw, OptUnit(r, "confidence", rv), OptUnit(r, "importance", rv), OptStr(r, "change_reason", rv, 2000), vs, rid)
- If Err.Number <> 0 Then
- m_err = "db: memory revision " & rid & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- m_cnt(1) = m_cnt(1) + 1
- If ver = curRev Then
- curTitle = title
- curContent = content
- curTags = tagsRaw
- End If
- Next
-
- vers = ArrayOf(o, "verifications")
- If Len(m_err) > 0 Then
- m_err = at & ": " & m_err
- Exit Sub
- End If
- For i = 0 To UBound(vers)
- Set r = JsonLite_Parse(vers(i))
- rv = at & ".verifications[" & i & "]"
- If r Is Nothing Then
- m_err = rv & " must be an object."
- Exit Sub
- End If
- rid = NeedId(r, "id", rv)
- ver = NeedInt(r, "revision", rv, 1, curRev)
- vs = NeedEnum(r, "result", rv, ",verified,disputed,rejected,")
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If IdTaken("SELECT 1 FROM verifications WHERE id = ?", rid) Then
- m_err = "conflict: verification " & rid & " already exists."
- Exit Sub
- End If
- On Error Resume Next
- DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, " & ver & ", ?, ?, ?, ?, ?)", _
- Array(rid, id, NeedStr(r, "method", rv, 100), vs, OptStr(r, "notes", rv, 2000), NeedId(r, "reviewer", rv), NeedTs(r, "created_at", rv))
- If Err.Number <> 0 Then
- m_err = "db: verification " & rid & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- m_cnt(2) = m_cnt(2) + 1
- Next
-
- ' derived data: lexical index now, semantic index after commit
- On Error Resume Next
- Search_IndexMemory id, curRev, Api_TenantId, nsId, curTitle, curContent, curTags
- Emb_MarkPending "memory", id, Api_TenantId, nsId, curRev
- If Err.Number <> 0 Then
- m_err = "db: indexing memory " & id & ": " & Err.Description
- Err.Clear
- End If
- On Error GoTo 0
- End Sub
-
- Private Sub ImportDocument(objText, idx)
- Dim o, at, id, nsId, fmt, curRev, revs, i, j, r, rv, rid, ver, content, chunks, c, cv, cid, revSeen, nCh
-
- at = "data.documents[" & idx & "]"
- Set o = JsonLite_Parse(objText)
- If o Is Nothing Then
- m_err = at & " must be an object."
- Exit Sub
- End If
- id = NeedId(o, "id", at)
- nsId = NeedNs(o, at)
- fmt = NeedEnum(o, "format", at, ",text,markdown,")
- curRev = NeedInt(o, "current_revision", at, 1, 100000)
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If IdTaken("SELECT 1 FROM documents WHERE id = ?", id) Then
- m_err = "conflict: document " & id & " already exists."
- Exit Sub
- End If
- revs = ArrayOf(o, "revisions")
- If Len(m_err) > 0 Then
- m_err = at & ": " & m_err
- Exit Sub
- End If
- If UBound(revs) + 1 <> curRev Then
- m_err = at & ".revisions must hold revisions 1.." & curRev & " (current_revision)."
- Exit Sub
- End If
- On Error Resume Next
- DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, current_revision, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, " & curRev & ", ?, ?, ?)", _
- Array(id, Api_TenantId, nsId, fmt, NeedStr(o, "title", at, 500), NeedId(o, "created_by", at), NeedTs(o, "created_at", at), NeedTs(o, "updated_at", at))
- DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(OptStr(o, "source_uri", at, 2000), id)
- If Err.Number <> 0 Then
- m_err = "db: document " & id & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- m_cnt(3) = m_cnt(3) + 1
-
- revSeen = ","
- For i = 0 To UBound(revs)
- Set r = JsonLite_Parse(revs(i))
- rv = at & ".revisions[" & i & "]"
- If r Is Nothing Then
- m_err = rv & " must be an object."
- Exit Sub
- End If
- rid = NeedId(r, "id", rv)
- ver = NeedInt(r, "revision", rv, 1, curRev)
- content = NeedStr(r, "content", rv, 1048576)
- chunks = ArrayOf(r, "chunks")
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If InStr(revSeen, "," & ver & ",") > 0 Then
- m_err = rv & ".revision " & ver & " appears twice."
- Exit Sub
- End If
- revSeen = revSeen & ver & ","
- If IdTaken("SELECT 1 FROM document_revisions WHERE id = ?", rid) Then
- m_err = "conflict: document revision " & rid & " already exists."
- Exit Sub
- End If
- nCh = UBound(chunks) + 1
- On Error Resume Next
- DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & ver & ", ?, ?, " & Len(content) & ", " & nCh & ", ?, ?)", _
- Array(rid, id, Api_Sha256(content), content, NeedId(r, "created_by", rv), NeedTs(r, "created_at", rv))
- If Err.Number <> 0 Then
- m_err = "db: document revision " & rid & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- m_cnt(4) = m_cnt(4) + 1
-
- For j = 0 To UBound(chunks)
- Set c = JsonLite_Parse(chunks(j))
- cv = rv & ".chunks[" & j & "]"
- If c Is Nothing Then
- m_err = cv & " must be an object."
- Exit Sub
- End If
- cid = NeedId(c, "id", cv)
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If IdTaken("SELECT 1 FROM chunks WHERE id = ?", cid) Then
- m_err = "conflict: chunk " & cid & " already exists."
- Exit Sub
- End If
- On Error Resume Next
- DAL().Execute "INSERT INTO chunks (id, document_id, document_revision, ordinal, content, heading_path, start_offset, end_offset, token_estimate, created_at) VALUES (?, ?, " & ver & ", " & _
- NeedInt(c, "ordinal", cv, 0, 1000000) & ", ?, ?, " & NeedInt(c, "start_offset", cv, 0, 100000000) & ", " & NeedInt(c, "end_offset", cv, 0, 100000000) & ", " & _
- NeedInt(c, "token_estimate", cv, 0, 100000000) & ", ?)", Array(cid, id, NeedStr(c, "content", cv, 1048576), OptStr(c, "heading_path", cv, 2000), NeedTs(c, "created_at", cv))
- If Err.Number <> 0 Then
- m_err = "db: chunk " & cid & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- ' the current revision is searchable: lexical index now, semantic index after commit
- If ver = curRev Then
- DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", Array("" & c.Item("content"), cid, Api_TenantId, nsId)
- Emb_MarkPending "chunk", cid, Api_TenantId, nsId, ver
- End If
- If Err.Number <> 0 Then
- m_err = "db: indexing chunk " & cid & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- m_cnt(5) = m_cnt(5) + 1
- Next
- Next
- End Sub
-
- Private Sub ImportEvidence(objText, idx)
- Dim o, at, id, ownerId, kind
- at = "data.evidence_links[" & idx & "]"
- Set o = JsonLite_Parse(objText)
- If o Is Nothing Then
- m_err = at & " must be an object."
- Exit Sub
- End If
- id = NeedId(o, "id", at)
- ownerId = NeedId(o, "owner_id", at)
- kind = NeedEnum(o, "target_kind", at, ",experience,chunk,memory,document,")
- NeedEnum o, "owner_kind", at, ",memory,"
- If Len(m_err) > 0 Then
- Exit Sub
- End If
- If InStr(m_memIds, "," & ownerId & ",") = 0 Then
- m_err = at & ".owner_id must be a memory of this export."
- Exit Sub
- End If
- If IdTaken("SELECT 1 FROM evidence_links WHERE id = ?", id) Then
- m_err = "conflict: evidence link " & id & " already exists."
- Exit Sub
- End If
- On Error Resume Next
- DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, 'memory', ?, ?, ?, ?, ?)", _
- Array(id, Api_TenantId, ownerId, kind, NeedId(o, "target_id", at), NeedId(o, "created_by", at), NeedTs(o, "created_at", at))
- DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _
- Array(OptInt(o, "owner_revision", at), OptInt(o, "target_revision", at), NeedEnum(o, "role", at, ",supports,contradicts,context,"), OptStr(o, "excerpt", at, 2000), id)
- If Err.Number <> 0 Then
- m_err = "db: evidence link " & id & ": " & Err.Description
- Err.Clear
- Exit Sub
- End If
- On Error GoTo 0
- If Len(m_err) = 0 Then
- m_cnt(6) = m_cnt(6) + 1
- End If
- End Sub
-
- ' ---- field readers (first error wins; they return a harmless value after an error) ----
- Private Sub Fail(msg)
- If Len(m_err) = 0 Then
- m_err = msg
- End If
- End Sub
-
- Private Function ArrayOf(o, k)
- Dim a
- ArrayOf = Array()
- If Not o.HasRaw(k) Then
- If o.Exists(k) Then
- If Not IsNull(o.Item(k)) Then
- Fail k & " must be an array of objects."
- End If
- End If
- Exit Function
- End If
- a = JsonLite_SplitObjectArray(o.Raw(k))
- If IsNull(a) Then
- Fail k & " must be an array of objects."
- Exit Function
- End If
- ArrayOf = a
- End Function
-
- Private Function NeedStr(o, k, at, maxLen)
- Dim v
- NeedStr = ""
- v = o.Item(k)
- If VarType(v) <> vbString Then
- Fail at & "." & k & " is required (string)."
- Exit Function
- End If
- If Len(v) = 0 Or Len(v) > maxLen Then
- Fail at & "." & k & " must be 1 to " & maxLen & " characters."
- Exit Function
- End If
- NeedStr = v
- End Function
-
- Private Function OptStr(o, k, at, maxLen)
- Dim v
- OptStr = Null
- v = o.Item(k)
- If IsNull(v) Then
- Exit Function
- End If
- If VarType(v) <> vbString Then
- Fail at & "." & k & " must be a string or null."
- Exit Function
- End If
- If Len(v) > maxLen Then
- Fail at & "." & k & " must be at most " & maxLen & " characters."
- Exit Function
- End If
- OptStr = v
- End Function
-
- Private Function NeedId(o, k, at)
- Dim v
- v = NeedStr(o, k, at, 64)
- If Len(v) > 0 Then
- If Not Api_IsId(v) Then
- Fail at & "." & k & " must be a UUID."
- End If
- End If
- NeedId = LCase(v)
- End Function
-
- Private Function NeedTs(o, k, at)
- NeedTs = NeedStr(o, k, at, 40)
- End Function
-
- Private Function NeedEnum(o, k, at, allowedList)
- Dim v
- v = LCase(NeedStr(o, k, at, 40))
- If Len(v) > 0 Then
- If InStr(allowedList, "," & v & ",") = 0 Then
- Fail at & "." & k & " must be one of " & Mid(allowedList, 2, Len(allowedList) - 2) & "."
- End If
- End If
- NeedEnum = v
- End Function
-
- Private Function NeedInt(o, k, at, lo, hi)
- Dim v
- NeedInt = lo
- v = o.Item(k)
- If VarType(v) <> vbDouble Then
- Fail at & "." & k & " is required (integer)."
- Exit Function
- End If
- If v <> Int(v) Or v < lo Or v > hi Then
- Fail at & "." & k & " must be an integer between " & lo & " and " & hi & "."
- Exit Function
- End If
- NeedInt = CLng(v)
- End Function
-
- Private Function OptInt(o, k, at)
- Dim v
- OptInt = Null
- v = o.Item(k)
- If IsNull(v) Then
- Exit Function
- End If
- OptInt = NeedInt(o, k, at, 0, 100000000)
- End Function
-
- Private Function OptUnit(o, k, at)
- Dim v
- OptUnit = Null
- v = o.Item(k)
- If IsNull(v) Then
- Exit Function
- End If
- If VarType(v) <> vbDouble Then
- Fail at & "." & k & " must be a number between 0 and 1."
- Exit Function
- End If
- If v < 0 Or v > 1 Then
- Fail at & "." & k & " must be a number between 0 and 1."
- Exit Function
- End If
- OptUnit = v
- End Function
-
- ' Raw JSON array/object text (first character `first`), or Null
- Private Function OptRaw(o, k, at, first)
- Dim raw
- OptRaw = Null
- If Not o.HasRaw(k) Then
- If o.Exists(k) Then
- If Not IsNull(o.Item(k)) Then
- Fail at & "." & k & " has the wrong type."
- End If
- End If
- Exit Function
- End If
- raw = o.Raw(k)
- If Left(raw, 1) <> first Then
- Fail at & "." & k & " has the wrong type."
- Exit Function
- End If
- OptRaw = raw
- End Function
-
- Private Function NeedNs(o, at)
- Dim path, id
- path = NeedStr(o, "namespace", at, 500)
- NeedNs = ""
- If Len(path) = 0 Then
- Exit Function
- End If
- id = NsIdOf(path)
- If Len(id) = 0 Then
- Fail at & ".namespace " & path & " is not listed in data.namespaces."
- Exit Function
- End If
- NeedNs = id
- End Function
-
- Private Function IdTaken(sql, id)
- Dim rs
- Set rs = DAL().Query(sql, id)
- IdTaken = Not rs.EOF
- rs.Close
- End Function
-
- ' ---- export helpers ----
- Private Function Rows(sql)
- Dim rs
- Rows = Empty
- Set rs = DAL().Query(sql, Empty)
- If Not rs.EOF Then
- Rows = rs.GetRows()
- End If
- rs.Close
- End Function
-
- Private Function RowsMax(r)
- If IsEmpty(r) Then
- RowsMax = -1
- Else
- RowsMax = UBound(r, 2)
- End If
- End Function
-
- Private Function NsPath(nsRows, nsId)
- Dim i
- NsPath = ""
- For i = 0 To RowsMax(nsRows)
- If "" & nsRows(0, i) = nsId Then
- NsPath = "" & nsRows(1, i)
- Exit Function
- End If
- Next
- 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)
- If IsNull(v) Then
- JRaw = "null"
- ElseIf Len("" & v) = 0 Then
- JRaw = "null"
- Else
- JRaw = "" & v
- End If
- 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 "export" : Export
- Case "import" : Import
- Case Else
- Err.Raise 438, "ApiPortabilityController_Class", "Action '" & actionName & "' not found"
- End Select
- End Sub
-
- End Class
-
- Dim ApiPortabilityController_Class__Singleton
- Function ApiPortabilityController()
- If IsEmpty(ApiPortabilityController_Class__Singleton) Then
- Set ApiPortabilityController_Class__Singleton = New ApiPortabilityController_Class
- End If
- Set ApiPortabilityController = ApiPortabilityController_Class__Singleton
- End Function
-
- ' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
- Sub ApiPortabilityController_Invoke(actionName, args)
- ApiPortabilityController().Invoke actionName, args
- End Sub
- %>
|