<% '======================================================================================================================= ' Search support: lexical (SQLite FTS5) indexing for memories and document chunks, and the document chunker. ' ' FTS rows carry tenant/namespace ids as UNINDEXED columns. A search always filters by tenant in SQL and then by the ' caller's readable namespaces (and current revision / lifecycle) against the canonical tables, so an index row never ' discloses anything on its own. Global functions only; module-level arrays hold the chunker output. '======================================================================================================================= ' --------------------------------------------------------------------------------------------------------------------- ' FTS query building ' --------------------------------------------------------------------------------------------------------------------- ' Turns free text into a safe FTS5 expression: up to 16 word tokens, each double-quoted, joined with OR so bm25 ranks ' partial matches. Returns "" when the text has no usable word. Letters/digits of any script are kept. ' Common English stopwords are left out (with OR they would match nearly everything, which matters for natural-language ' tasks in /context), unless the text has nothing else. Const SEARCH_STOPWORDS = " a an and are as at be but by can do does for from how i if in into is it its me my no not of on or our so than that the their them then there these they this to us was we were what when where which who why will with would you your " Function Search_FtsQuery(text) Dim t, i, c, n, tok, out, count, code, outAll, countAll t = "" & text n = Len(t) tok = "" out = "" count = 0 outAll = "" countAll = 0 For i = 1 To n + 1 If i <= n Then c = Mid(t, i, 1) code = AscW(c) Else c = " " code = 32 End If ' AscW is negative for U+8000..U+FFFF, which are word characters too If (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (c >= "0" And c <= "9") Or c = "_" Or code > 127 Or code < 0 Then tok = tok & c Else If Len(tok) > 0 Then If countAll < 16 Then If Len(outAll) > 0 Then outAll = outAll & " OR " End If outAll = outAll & """" & Left(tok, 64) & """" countAll = countAll + 1 End If If count < 16 Then If InStr(SEARCH_STOPWORDS, " " & LCase(tok) & " ") = 0 Then If Len(out) > 0 Then out = out & " OR " End If out = out & """" & Left(tok, 64) & """" count = count + 1 End If End If tok = "" End If End If Next If Len(out) = 0 Then out = outAll End If Search_FtsQuery = out End Function ' --------------------------------------------------------------------------------------------------------------------- ' Memory index (one row per memory: its current revision) ' --------------------------------------------------------------------------------------------------------------------- Sub Search_UnindexMemory(memoryId) DAL().Execute "DELETE FROM memories_fts WHERE memory_id = ?", memoryId End Sub ' tagsRaw is the stored JSON array text (or Null); the tag words are indexed as plain text. Sub Search_IndexMemory(memoryId, revision, tenantId, namespaceId, title, content, tagsRaw) Dim tagText Search_UnindexMemory memoryId tagText = "" If Not IsNull(tagsRaw) Then tagText = Replace(Replace(Replace(Replace("" & tagsRaw, "[", " "), "]", " "), """", " "), ",", " ") End If DAL().Execute "INSERT INTO memories_fts (title, content, tags, memory_id, revision, tenant_id, namespace_id) VALUES (?, ?, ?, ?, ?, ?, ?)", _ Array(title, content, tagText, memoryId, CLng(revision), tenantId, namespaceId) End Sub ' --------------------------------------------------------------------------------------------------------------------- ' Chunker. State lives in a class instance because ReDim of module-level arrays from inside a Sub does not reach the ' global array under AxonASP. Output (valid until the next Chunk_Run call), through global accessor functions: ' Chunk_Count, Chunk_Text(i), Chunk_Heading(i), Chunk_Start(i), Chunk_End(i) (i = 0..Count-1) ' Offsets are 0-based character offsets into the NORMALIZED text (Chunk_Normalize); Chunk_Text(i) is exactly ' Mid(normalized, Chunk_Start(i) + 1, Chunk_End(i) - Chunk_Start(i)), so a locator always reproduces the passage. ' --------------------------------------------------------------------------------------------------------------------- Const CHUNK_MAX_CHARS = 1200 Class Chunker_Class Public Count Private cText(), cHead(), cStart(), cEnd() Private bS(), bE(), bH(), bIsHead(), bN Private src Private Sub Class_Initialize() Count = 0 bN = 0 ReDim cText(15) ReDim cHead(15) ReDim cStart(15) ReDim cEnd(15) ReDim bS(31) ReDim bE(31) ReDim bH(31) ReDim bIsHead(31) End Sub Public Function TextAt(i) TextAt = cText(i) End Function Public Function HeadAt(i) HeadAt = cHead(i) End Function Public Function StartAt(i) StartAt = cStart(i) End Function Public Function EndAt(i) EndAt = cEnd(i) End Function Private Sub AddChunk(txt, heading, startOff, endOff) If Count > UBound(cText) Then ReDim Preserve cText(Count * 2) ReDim Preserve cHead(Count * 2) ReDim Preserve cStart(Count * 2) ReDim Preserve cEnd(Count * 2) End If cText(Count) = txt cHead(Count) = heading cStart(Count) = startOff cEnd(Count) = endOff Count = Count + 1 End Sub Private Sub PushBlock(s, e, headingPath, isHeading) If bN > UBound(bS) Then ReDim Preserve bS(bN * 2) ReDim Preserve bE(bN * 2) ReDim Preserve bH(bN * 2) ReDim Preserve bIsHead(bN * 2) End If bS(bN) = s bE(bN) = e bH(bN) = headingPath bIsHead(bN) = isHeading bN = bN + 1 End Sub ' Appends a paragraph; one longer than the limit is cut at whitespace into several blocks. Private Sub AddPara(startOff, endOff, headingPath) Dim s, e, cut, j, ch s = startOff e = endOff Do While (e - s) > CHUNK_MAX_CHARS cut = s + CHUNK_MAX_CHARS For j = cut To cut - 200 Step -1 If j <= s Then Exit For End If ch = Mid(src, j + 1, 1) If ch = " " Or ch = vbLf Then cut = j Exit For End If Next PushBlock s, cut, headingPath, False s = cut Do While s < e ch = Mid(src, s + 1, 1) If ch = " " Or ch = vbLf Then s = s + 1 Else Exit Do End If Loop Loop If e > s Then PushBlock s, e, headingPath, False End If End Sub ' Level (1-6) of an ATX heading line ("## Title"), else 0 Private Function HeadingLevel(ln) Dim n, c HeadingLevel = 0 n = 0 Do While n < Len(ln) And n < 7 If Mid(ln, n + 1, 1) = "#" Then n = n + 1 Else Exit Do End If Loop If n >= 1 And n <= 6 Then If Len(ln) > n Then c = Mid(ln, n + 1, 1) If c = " " Or c = vbTab Then If Len(Trim(Mid(ln, n + 1))) > 0 Then HeadingLevel = n End If End If End If End If End Function ' Splits normalized text into passages of about CHUNK_MAX_CHARS. A markdown heading always starts a new chunk and ' becomes part of the heading path of the chunks below it; blank lines separate paragraphs, grouped greedily. Public Sub Split(norm, isMarkdown) Dim lines, i, ln, pos, lineStart, level, title, path, k, g Dim paraStart, paraEnd, inPara Dim hstack(5) Dim gStart, gEnd, gHead, have, bs0, be0 src = norm Count = 0 bN = 0 For k = 0 To 5 hstack(k) = "" Next path = "" lines = Split_(norm) pos = 0 inPara = False paraStart = 0 paraEnd = 0 For i = 0 To UBound(lines) ln = lines(i) lineStart = pos pos = pos + Len(ln) + 1 level = 0 If isMarkdown Then level = HeadingLevel(ln) End If If level > 0 Then If inPara Then AddPara paraStart, paraEnd, path inPara = False End If title = Trim(Mid(ln, level + 1)) hstack(level - 1) = title For k = level To 5 hstack(k) = "" Next path = "" For k = 0 To 5 If Len(hstack(k)) > 0 Then If Len(path) > 0 Then path = path & " > " End If path = path & hstack(k) End If Next PushBlock lineStart, lineStart + Len(ln), path, True ElseIf Len(Trim(ln)) = 0 Then If inPara Then AddPara paraStart, paraEnd, path inPara = False End If Else If Not inPara Then inPara = True paraStart = lineStart End If paraEnd = lineStart + Len(ln) End If Next If inPara Then AddPara paraStart, paraEnd, path End If have = False gStart = 0 gEnd = 0 gHead = "" For g = 0 To bN - 1 bs0 = bS(g) be0 = bE(g) If have Then If bIsHead(g) Or (be0 - gStart) > CHUNK_MAX_CHARS Then AddChunk Mid(norm, gStart + 1, gEnd - gStart), gHead, gStart, gEnd have = False End If End If If Not have Then gStart = bs0 gHead = bH(g) have = True End If gEnd = be0 Next If have Then AddChunk Mid(norm, gStart + 1, gEnd - gStart), gHead, gStart, gEnd End If End Sub Private Function Split_(t) Split_ = VBScript_Split(t) End Function End Class Function VBScript_Split(t) VBScript_Split = Split(t, vbLf) End Function Dim Chunk_State Set Chunk_State = New Chunker_Class Function Chunk_Normalize(text) Dim t t = Replace("" & text, vbCrLf, vbLf) t = Replace(t, vbCr, vbLf) Chunk_Normalize = t End Function Function Chunk_Count() Chunk_Count = Chunk_State.Count End Function Function Chunk_Text(i) Chunk_Text = Chunk_State.TextAt(i) End Function Function Chunk_Heading(i) Chunk_Heading = Chunk_State.HeadAt(i) End Function Function Chunk_Start(i) Chunk_Start = Chunk_State.StartAt(i) End Function Function Chunk_End(i) Chunk_End = Chunk_State.EndAt(i) End Function ' Entry point: normalizes, splits and returns the normalized text (store this, not the raw input) Function Chunk_Run(text, isMarkdown) Dim norm norm = Chunk_Normalize(text) Set Chunk_State = New Chunker_Class Chunk_State.Split norm, isMarkdown Chunk_Run = norm End Function %>