- docker-compose: ollama (nomic-embed-text) and qdrant services. - core/lib.Embeddings.asp: Ollama and Qdrant clients, embedding_index bookkeeping (pending/indexed/failed/delete with model, dimensions and revision), Ranker_Class with reciprocal rank fusion of lexical and vector ranks. Falls back to lexical with a warning when the provider is off/down. - Write paths mark rows inside their transaction and index after commit without failing the write; forget, purge and new document revisions remove points. scripts\embed.cmd status|run|reindex catches up or rebuilds. - /recall, /search and /context use the shared ranker and report strategy. - Lexical queries drop common English stopwords; fix AscW sign so characters U+8000..U+FFFF are kept as word characters. - Migration create_embedding_index_table; tests/phase3-semantic.sh (30 checks); OpenAPI, README and AGENTS.md updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>pull/1/head
| @@ -36,6 +36,7 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w | |||||
| - Regression suite: `bash tests/phase1-api.sh` (needs the container running; creates and purges its own tenants; ends with a container restart). | - Regression suite: `bash tests/phase1-api.sh` (needs the container running; creates and purges its own tenants; ends with a container restart). | ||||
| - Phase 2 (documents): `ApiDocumentsController` (ingestion/jobs, jobs, documents, chunks, search) plus `POST /recall` and `POST /memories/:id/verifications` in `ApiMemoriesController`; chunker and FTS5 indexing live in `core/lib.Search.asp`. Regression suite: `bash tests/phase2-api.sh`. OpenAPI: `public/api/memory-v1.openapi.json`. A caller without the needed namespace permission gets 404, never 403. | - Phase 2 (documents): `ApiDocumentsController` (ingestion/jobs, jobs, documents, chunks, search) plus `POST /recall` and `POST /memories/:id/verifications` in `ApiMemoriesController`; chunker and FTS5 indexing live in `core/lib.Search.asp`. Regression suite: `bash tests/phase2-api.sh`. OpenAPI: `public/api/memory-v1.openapi.json`. A caller without the needed namespace permission gets 404, never 403. | ||||
| - Phase 3 (context): `ApiContextController` (`POST /context`) assembles a budgeted briefing. Constraints are loaded by scope (not similarity) and are required: if they do not fit `max_context_tokens` the answer is 422 `context_budget_exceeded`. Regression suite: `bash tests/phase3-context.sh`. | - Phase 3 (context): `ApiContextController` (`POST /context`) assembles a budgeted briefing. Constraints are loaded by scope (not similarity) and are required: if they do not fit `max_context_tokens` the answer is 422 `context_budget_exceeded`. Regression suite: `bash tests/phase3-context.sh`. | ||||
| - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. | |||||
| - The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all three suites. | - The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all three suites. | ||||
| ### Adding a table end to end (the workflow that was verified) | ### Adding a table end to end (the workflow that was verified) | ||||
| @@ -167,6 +168,9 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o | |||||
| - **Close a result set before running another statement.** Running a query inside a loop over an open G3DB result set hung the request (script timeout), and a write executed while a result set was still open was silently lost (the `provision key` action created no key). Copy the values you need, `rs.Close`, then query/write. | - **Close a result set before running another statement.** Running a query inside a loop over an open G3DB result set hung the request (script timeout), and a write executed while a result set was still open was silently lost (the `provision key` action created no key). Copy the values you need, `rs.Close`, then query/write. | ||||
| - **G3DB takes at most 8 parameters per statement** ("Too many parameters (12); the maximum is 8"). Split wide INSERTs into an INSERT plus an UPDATE inside one transaction (see `InsertRevision` in `ApiMemoriesController.asp`). | - **G3DB takes at most 8 parameters per statement** ("Too many parameters (12); the maximum is 8"). Split wide INSERTs into an INSERT plus an UPDATE inside one transaction (see `InsertRevision` in `ApiMemoriesController.asp`). | ||||
| - **Characters above U+FFFF (emoji) cannot be held** on the pinned build (CLI v2.3.42): `ChrW(128512)` raises "Invalid procedure call" (older builds returned one character), and `ChrW(55357) & ChrW(56832)` is written out as CESU-8 (`ED A0 BD ...`), which is invalid UTF-8. `Api_Utf8Decode` and JsonLite therefore flag such code points (raw 4-byte UTF-8 or escaped surrogate pairs) and `Api_ReadBody` answers 422 `unsupported_character`; the generator template does the same. Do not store them as U+FFFD silently. | - **Characters above U+FFFF (emoji) cannot be held** on the pinned build (CLI v2.3.42): `ChrW(128512)` raises "Invalid procedure call" (older builds returned one character), and `ChrW(55357) & ChrW(56832)` is written out as CESU-8 (`ED A0 BD ...`), which is invalid UTF-8. `Api_Utf8Decode` and JsonLite therefore flag such code points (raw 4-byte UTF-8 or escaped surrogate pairs) and `Api_ReadBody` answers 422 `unsupported_character`; the generator template does the same. Do not store them as U+FFFD silently. | ||||
| - **Calling HTTP services from a request works alongside G3DB** (verified with `MSXML2.ServerXMLHTTP` to Ollama and Qdrant, reads and writes before and after, cold first request). Set `SetTimeouts` so a dead service cannot hang the request, never let an HTTP failure fail a database write, and keep large JSON (vectors) as text: slice it with `InStr`/`Split` instead of parsing it with JsonLite. | |||||
| - **Embedding similarity thresholds are model-specific.** With `nomic-embed-text` (and its `search_query: `/`search_document: ` prefixes) relevant pairs scored 0.61-0.67 and unrelated ones up to 0.58, hence `EmbeddingMinScore` 0.6. Re-measure before changing the model, and remember the memory title is part of the embedded (and FTS-indexed) text. | |||||
| - **`AscW` is signed:** characters U+8000..U+FFFF give negative values, so `AscW(c) > 127` misses them (fixed in `Search_FtsQuery`). The same applies to `CLng("&H" & hex)` for 4-digit hex. | |||||
| - **`content_hash` is not a content hash.** `memory_revisions.content_hash` is SHA-256 of `namespace|type|title|content` (used for duplicate detection in one namespace). To dedupe the same text across namespaces compare the content itself (as `ApiContextController` does). | - **`content_hash` is not a content hash.** `memory_revisions.content_hash` is SHA-256 of `namespace|type|title|content` (used for duplicate detection in one namespace). To dedupe the same text across namespaces compare the content itself (as `ApiContextController` does). | ||||
| - **Agent tooling can rewrite escape sequences.** In this repo's sessions, `\uXXXX` written in a tool command or file edit was sometimes decoded to the real character before bash/curl ran (curl then sent `??`), which looked like a server bug. Produce backslashes at run time in tests (`printf '%su00fc' '\'`, Python `chr(92)`), check test files for unintended non-ASCII bytes, and confirm what curl sends with `--trace-ascii -` before blaming the runtime. | - **Agent tooling can rewrite escape sequences.** In this repo's sessions, `\uXXXX` written in a tool command or file edit was sometimes decoded to the real character before bash/curl ran (curl then sent `??`), which looked like a server bug. Produce backslashes at run time in tests (`printf '%su00fc' '\'`, Python `chr(92)`), check test files for unintended non-ASCII bytes, and confirm what curl sends with `--trace-ascii -` before blaming the runtime. | ||||
| - **Run CLI tools as the server user.** The HTTP server runs as `axonasp`; a database file first created by a root `docker exec` was read-only to it ("attempt to write a readonly database"). `gen.cmd`, `migrate.cmd` and `provision.cmd` use `docker exec -u axonasp`. | - **Run CLI tools as the server user.** The HTTP server runs as `axonasp`; a database file first created by a root `docker exec` was read-only to it ("attempt to write a readonly database"). `gen.cmd`, `migrate.cmd` and `provision.cmd` use `docker exec -u axonasp`. | ||||
| @@ -56,7 +56,8 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec | |||||
| **Done** | **Done** | ||||
| - Phase 1: tenants, principals, hashed API keys, namespaces, grants (read/write/delete/verify/admin); memories with revisions, correction (If-Match), retire/forget, idempotency keys, duplicate detection, audit events; sessions with checkpoints; health. | - Phase 1: tenants, principals, hashed API keys, namespaces, grants (read/write/delete/verify/admin); memories with revisions, correction (If-Match), retire/forget, idempotency keys, duplicate detection, audit events; sessions with checkpoints; health. | ||||
| - Phase 2: Markdown/text ingestion with chunking and source locators (`core/lib.Search.asp`), documents/chunks/jobs, lexical search over chunks (FTS5), `POST /recall` over memories, verification (`POST /memories/:id/verifications`), `content_trust` labelling. | - Phase 2: Markdown/text ingestion with chunking and source locators (`core/lib.Search.asp`), documents/chunks/jobs, lexical search over chunks (FTS5), `POST /recall` over memories, verification (`POST /memories/:id/verifications`), `content_trust` labelling. | ||||
| - Phase 3 (part): `POST /context` assembles a task briefing under a token budget: constraints loaded by scope (required; 422 `context_budget_exceeded` when they do not fit), working state from a session checkpoint, preferences, disputed items as conflicts, decisions/lessons/knowledge and reference passages by lexical match, optional unverified items; deduplicated and trust-labelled. | |||||
| - Phase 3 (part): `POST /context` assembles a task briefing under a token budget: constraints loaded by scope (required; 422 `context_budget_exceeded` when they do not fit), working state from a session checkpoint, preferences, disputed items as conflicts, decisions/lessons/knowledge and reference passages by hybrid match, optional unverified items; deduplicated and trust-labelled. | |||||
| - Phase 3 (part): semantic retrieval. Embeddings from a local Ollama model (`nomic-embed-text`), vectors in Qdrant, both as containers in `docker-compose.yml`. `/recall`, `/search` and `/context` fuse lexical and vector ranks (reciprocal rank fusion) and fall back to lexical with a warning when the provider is off or down. SQLite stays the source of truth: `embedding_index` tracks model, dimensions, revision and status per memory/chunk, writes index after commit (never failing the write), and `scripts\embed.cmd status|run|reindex` catches up or rebuilds. Common English stopwords are dropped from lexical queries. | |||||
| **Known limitation** | **Known limitation** | ||||
| - Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8). | - Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8). | ||||
| @@ -64,16 +65,17 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec | |||||
| **Tooling** | **Tooling** | ||||
| - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. | - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. | ||||
| - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). | - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). | ||||
| - Tests (container must be running): `bash tests/phase1-api.sh` (74 checks), `bash tests/phase2-api.sh` (45 checks), `bash tests/phase3-context.sh` (60 checks). Each creates and purges its own tenants. | |||||
| - `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model). | |||||
| - Tests (containers must be running): `bash tests/phase1-api.sh` (74 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once). Each creates and purges its own tenants. | |||||
| **Next (not started)** | **Next (not started)** | ||||
| 1. Embeddings and hybrid retrieval. Decided: local Ollama container for embeddings and a vector store container (Qdrant) next to SQLite, behind a replaceable provider interface; lexical retrieval stays the fallback with a degradation warning. | |||||
| 2. Experiences, candidates and review; feedback (AC-18). | |||||
| 3. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). | |||||
| 1. Experiences, candidates and review; feedback (AC-18). | |||||
| 2. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). | |||||
| ## Configuration | ## Configuration | ||||
| - `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings. | |||||
| - `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings, and the `Embedding*` / `VectorStoreUrl` settings (`EmbeddingProvider` `none` turns semantic retrieval off). Settings are cached per process: `docker restart axonasp` after editing. | |||||
| - First start of the semantic stack: `docker compose up -d`, then `docker exec ollama ollama pull nomic-embed-text` once (the model lives in the `ollama-models` volume). The ollama image is about 6 GB. | |||||
| - `/opt/axonasp/config/axonasp.toml` (inside the container): server settings; any key can be overridden with an environment variable (see `docker-compose.yml`). | - `/opt/axonasp/config/axonasp.toml` (inside the container): server settings; any key can be overridden with an environment variable (see `docker-compose.yml`). | ||||
| ## Rules for developers and AI agents | ## Rules for developers and AI agents | ||||
| @@ -8,14 +8,15 @@ | |||||
| ' "detail_level":"full|summary", "max_context_tokens":100..32000, "max_items":1..50, "max_references":0..20, | ' "detail_level":"full|summary", "max_context_tokens":100..32000, "max_items":1..50, "max_references":0..20, | ||||
| ' "format":"structured"} | ' "format":"structured"} | ||||
| ' | ' | ||||
| ' Matching is hybrid (lexical fused with vector similarity, core/lib.Embeddings.asp) when configured, else lexical. | |||||
| ' Assembly (all filtered to active, currently valid memories in namespaces the caller can read): | ' Assembly (all filtered to active, currently valid memories in namespaces the caller can read): | ||||
| ' constraints every constraint memory in scope, by importance: loaded by scope, not by similarity, and required. | ' constraints every constraint memory in scope, by importance: loaded by scope, not by similarity, and required. | ||||
| ' If they do not fit the budget the request fails with 422 context_budget_exceeded. | ' If they do not fit the budget the request fails with 422 context_budget_exceeded. | ||||
| ' working_state latest checkpoint of session_id (404 when the session is not visible) | ' working_state latest checkpoint of session_id (404 when the session is not visible) | ||||
| ' preferences every preference memory in scope, by importance | ' preferences every preference memory in scope, by importance | ||||
| ' conflicts disputed memories among the above and the task matches (always reported, labelled) | ' conflicts disputed memories among the above and the task matches (always reported, labelled) | ||||
| ' decisions / lessons / knowledge lexical (FTS5/bm25) matches of the task, by type | |||||
| ' references lexical matches over current document chunks (untrusted reference content) | |||||
| ' decisions / lessons / knowledge matches of the task (hybrid or lexical), by type | |||||
| ' references matches over current document chunks (untrusted reference content) | |||||
| ' unverified unverified matches, only with verification_filter include_unverified | ' unverified unverified matches, only with verification_filter include_unverified | ||||
| ' The budget is filled in that order; an item that does not fit is skipped and counted. Memories with identical | ' The budget is filled in that order; an item that does not fit is skipped and counted. Memories with identical | ||||
| ' content (same text, ignoring case and outer whitespace) appear once. Token counts are estimates (characters / 4) of the included text, not of | ' content (same text, ignoring case and outer whitespace) appear once. Token counts are estimates (characters / 4) of the included text, not of | ||||
| @@ -35,7 +36,7 @@ Class ApiContextController_Class | |||||
| Private m_errs | Private m_errs | ||||
| ' candidates, in rank order within each section | ' candidates, in rank order within each section | ||||
| Private m_cSec(), m_cJson(), m_cTok(), m_cN | Private m_cSec(), m_cJson(), m_cTok(), m_cN | ||||
| Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok | |||||
| Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok, m_strategy, m_rankWarning | |||||
| Public Property Get useLayout() | Public Property Get useLayout() | ||||
| useLayout = False | useLayout = False | ||||
| @@ -57,7 +58,7 @@ Class ApiContextController_Class | |||||
| Dim rs, sql, now_, i, j, n, ids(), scores(), idList, sec, json, warnings, complete | Dim rs, sql, now_, i, j, n, ids(), scores(), idList, sec, json, warnings, complete | ||||
| Dim stateJson, stateTok, sessNs, sessStatus, sessObjective, curRev, savedAt | Dim stateJson, stateTok, sessNs, sessStatus, sessObjective, curRev, savedAt | ||||
| Dim used, requiredTok, policyCount, truncated, omittedBudget, omittedLimit, cap | Dim used, requiredTok, policyCount, truncated, omittedBudget, omittedLimit, cap | ||||
| Dim outSec(), cnt(), out, refSeen, txt, policiesCapped | |||||
| Dim outSec(), cnt(), out, refSeen, txt, policiesCapped, ranker | |||||
| If Not Api_Authenticate() Then Exit Sub | If Not Api_Authenticate() Then Exit Sub | ||||
| body = Api_ReadBody() | body = Api_ReadBody() | ||||
| @@ -200,6 +201,8 @@ Class ApiContextController_Class | |||||
| ReDim m_cJson(31) | ReDim m_cJson(31) | ||||
| ReDim m_cTok(31) | ReDim m_cTok(31) | ||||
| m_seen = Chr(31) | m_seen = Chr(31) | ||||
| m_strategy = "lexical" | |||||
| m_rankWarning = "" | |||||
| m_dupes = 0 | m_dupes = 0 | ||||
| m_unverifiedExcluded = 0 | m_unverifiedExcluded = 0 | ||||
| policiesCapped = False | policiesCapped = False | ||||
| @@ -228,26 +231,23 @@ Class ApiContextController_Class | |||||
| Loop | Loop | ||||
| rs.Close | rs.Close | ||||
| '--- 2. lexical memory matches --------------------------------------------- | |||||
| '--- 2. memory matches (lexical, fused with semantic when configured) ---------- | |||||
| If incDecisions Or incLessons Or incKnowledge Then | If incDecisions Or incLessons Or incKnowledge Then | ||||
| Set rs = DAL().Query("SELECT memory_id, bm25(memories_fts) FROM memories_fts WHERE memories_fts MATCH ? AND tenant_id = ? ORDER BY bm25(memories_fts) LIMIT 300", Array(fts, Api_TenantId)) | |||||
| n = 0 | |||||
| ReDim ids(63) | |||||
| ReDim scores(63) | |||||
| Do While Not rs.EOF | |||||
| If n > UBound(ids) Then | |||||
| ReDim Preserve ids(n * 2) | |||||
| ReDim Preserve scores(n * 2) | |||||
| End If | |||||
| ids(n) = "" & rs(0) | |||||
| scores(n) = rs(1) | |||||
| n = n + 1 | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| Set ranker = New Ranker_Class | |||||
| ranker.Run "memory", fts, task, Api_TenantId, allowed | |||||
| NoteRanker ranker | |||||
| n = ranker.Count | |||||
| If n > 0 Then | |||||
| ReDim ids(n - 1) | |||||
| ReDim scores(n - 1) | |||||
| For i = 0 To n - 1 | |||||
| ids(i) = ranker.IdAt(i) | |||||
| scores(i) = -ranker.ScoreAt(i) | |||||
| Next | |||||
| End If | |||||
| idList = IdSqlList(ids, n) | idList = IdSqlList(ids, n) | ||||
| If Len(idList) > 0 Then | If Len(idList) > 0 Then | ||||
| ' Read the canonical rows (closing the result set), then add them in bm25 order. | |||||
| ' Read the canonical rows (closing the result set), then add them in rank order. | |||||
| sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ | sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ | ||||
| "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _ | "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _ | ||||
| "AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')" | "AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')" | ||||
| @@ -284,21 +284,18 @@ Class ApiContextController_Class | |||||
| '--- 3. reference passages ------------------------------------------------ | '--- 3. reference passages ------------------------------------------------ | ||||
| If incRefs And maxRefs > 0 Then | If incRefs And maxRefs > 0 Then | ||||
| Set rs = DAL().Query("SELECT chunk_id, bm25(chunks_fts) FROM chunks_fts WHERE chunks_fts MATCH ? AND tenant_id = ? ORDER BY bm25(chunks_fts) LIMIT 300", Array(fts, Api_TenantId)) | |||||
| n = 0 | |||||
| ReDim ids(63) | |||||
| ReDim scores(63) | |||||
| Do While Not rs.EOF | |||||
| If n > UBound(ids) Then | |||||
| ReDim Preserve ids(n * 2) | |||||
| ReDim Preserve scores(n * 2) | |||||
| End If | |||||
| ids(n) = "" & rs(0) | |||||
| scores(n) = rs(1) | |||||
| n = n + 1 | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| Set ranker = New Ranker_Class | |||||
| ranker.Run "chunk", fts, task, Api_TenantId, allowed | |||||
| NoteRanker ranker | |||||
| n = ranker.Count | |||||
| If n > 0 Then | |||||
| ReDim ids(n - 1) | |||||
| ReDim scores(n - 1) | |||||
| For i = 0 To n - 1 | |||||
| ids(i) = ranker.IdAt(i) | |||||
| scores(i) = -ranker.ScoreAt(i) | |||||
| Next | |||||
| End If | |||||
| idList = IdSqlList(ids, n) | idList = IdSqlList(ids, n) | ||||
| If Len(idList) > 0 Then | If Len(idList) > 0 Then | ||||
| Dim chunkRows | Dim chunkRows | ||||
| @@ -419,10 +416,12 @@ Class ApiContextController_Class | |||||
| If Len(allowed) = 0 Then | If Len(allowed) = 0 Then | ||||
| AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty" | AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty" | ||||
| End If | End If | ||||
| AddWarning warnings, "semantic retrieval is not configured; matches are lexical only" | |||||
| If Len(m_rankWarning) > 0 Then | |||||
| AddWarning warnings, m_rankWarning | |||||
| End If | |||||
| out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""task"":" & JsonLite_Quote(task) & _ | out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""task"":" & JsonLite_Quote(task) & _ | ||||
| ",""strategy"":""lexical"",""format"":""structured"",""verification_filter"":" & JsonLite_Quote(vf) & ",""detail_level"":" & JsonLite_Quote(detail) & _ | |||||
| ",""strategy"":" & JsonLite_Quote(m_strategy) & ",""format"":""structured"",""verification_filter"":" & JsonLite_Quote(vf) & ",""detail_level"":" & JsonLite_Quote(detail) & _ | |||||
| ",""budget"":{""max_context_tokens"":" & budget & ",""used_tokens"":" & used & ",""counting_method"":""estimate_chars_div_4""" & _ | ",""budget"":{""max_context_tokens"":" & budget & ",""used_tokens"":" & used & ",""counting_method"":""estimate_chars_div_4""" & _ | ||||
| ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _ | ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _ | ||||
| ",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}" | ",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}" | ||||
| @@ -461,6 +460,16 @@ Class ApiContextController_Class | |||||
| ' Columns relied on by AddMemory / AddMemoryRow: | ' Columns relied on by AddMemory / AddMemoryRow: | ||||
| ' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance, | ' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance, | ||||
| ' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until | ' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until | ||||
| ' Strategy/warning of the last ranking (hybrid unless semantic retrieval was unavailable for any section) | |||||
| Private Sub NoteRanker(r) | |||||
| If Len(r.Warning) > 0 Then | |||||
| m_rankWarning = r.Warning | |||||
| m_strategy = "lexical" | |||||
| ElseIf Len(m_rankWarning) = 0 Then | |||||
| m_strategy = r.Strategy | |||||
| End If | |||||
| End Sub | |||||
| Private Function CtxMemorySelect() | Private Function CtxMemorySelect() | ||||
| CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _ | CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _ | ||||
| "r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _ | "r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _ | ||||
| @@ -140,6 +140,7 @@ Class ApiDocumentsController_Class | |||||
| End If | End If | ||||
| Else | Else | ||||
| DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev) | DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev) | ||||
| Emb_MarkDeleteChunks docId, curRev | |||||
| End If | End If | ||||
| DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & revNo & ", ?, ?, " & Len(norm) & ", " & Chunk_Count & ", ?, ?)", _ | DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & revNo & ", ?, ?, " & Len(norm) & ", " & Chunk_Count & ", ?, ?)", _ | ||||
| Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts) | Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts) | ||||
| @@ -149,6 +150,7 @@ Class ApiDocumentsController_Class | |||||
| Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts) | Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts) | ||||
| DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _ | DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _ | ||||
| Array(Chunk_Text(i), chunkId, Api_TenantId, nsId) | Array(Chunk_Text(i), chunkId, Api_TenantId, nsId) | ||||
| Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo | |||||
| Next | Next | ||||
| If revNo > 1 Then | If revNo > 1 Then | ||||
| DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId) | DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId) | ||||
| @@ -172,6 +174,7 @@ Class ApiDocumentsController_Class | |||||
| End If | End If | ||||
| On Error GoTo 0 | On Error GoTo 0 | ||||
| Emb_AfterWrite Api_TenantId, 64 | |||||
| Api_Audit "document.ingest", "document", docId, "ok" | Api_Audit "document.ingest", "document", docId, "ok" | ||||
| Response.AddHeader "Location", "/api/v1/documents/" & docId | Response.AddHeader "Location", "/api/v1/documents/" & docId | ||||
| Api_Send 201, resp | Api_Send 201, resp | ||||
| @@ -297,7 +300,7 @@ Class ApiDocumentsController_Class | |||||
| '--------------------------------------------------------------- | '--------------------------------------------------------------- | ||||
| Public Sub Search() | Public Sub Search() | ||||
| Dim body, input, query, fts, maxResults, detail, allowed, nsList, ids(), scores(), n, rs, sql, out, count, i, j, idList, rowJson() | Dim body, input, query, fts, maxResults, detail, allowed, nsList, ids(), scores(), n, rs, sql, out, count, i, j, idList, rowJson() | ||||
| Dim requested, arr, ok, wanted, warn | |||||
| Dim requested, arr, ok, wanted, warn, ranker, warnJson | |||||
| If Not Api_Authenticate() Then Exit Sub | If Not Api_Authenticate() Then Exit Sub | ||||
| body = Api_ReadBody() | body = Api_ReadBody() | ||||
| @@ -338,28 +341,25 @@ Class ApiDocumentsController_Class | |||||
| Exit Sub | Exit Sub | ||||
| End If | End If | ||||
| ' Step 1: ranked candidate chunk ids from the index (tenant filtered); step 2: join canonical rows, apply | |||||
| ' the namespace and current-revision filters. The first result set is closed before the second query. | |||||
| Set rs = DAL().Query("SELECT chunk_id, bm25(chunks_fts) FROM chunks_fts WHERE chunks_fts MATCH ? AND tenant_id = ? ORDER BY bm25(chunks_fts) LIMIT 300", Array(fts, Api_TenantId)) | |||||
| n = 0 | |||||
| ReDim ids(63) | |||||
| ReDim scores(63) | |||||
| Do While Not rs.EOF | |||||
| If n > UBound(ids) Then | |||||
| ReDim Preserve ids(n * 2) | |||||
| ReDim Preserve scores(n * 2) | |||||
| End If | |||||
| ids(n) = "" & rs(0) | |||||
| scores(n) = rs(1) | |||||
| n = n + 1 | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| ' Step 1: ranked candidate chunk ids (lexical, fused with semantic when configured; tenant filtered); | |||||
| ' step 2: join canonical rows, apply the namespace and current-revision filters. | |||||
| Set ranker = New Ranker_Class | |||||
| ranker.Run "chunk", fts, query, Api_TenantId, allowed | |||||
| n = ranker.Count | |||||
| warnJson = "" | |||||
| If Len(ranker.Warning) > 0 Then | |||||
| warnJson = JsonLite_Quote(ranker.Warning) | |||||
| End If | |||||
| If n = 0 Then | If n = 0 Then | ||||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}" | |||||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[" & warnJson & "]}" | |||||
| Exit Sub | Exit Sub | ||||
| End If | End If | ||||
| ReDim ids(n - 1) | |||||
| ReDim scores(n - 1) | |||||
| For i = 0 To n - 1 | |||||
| ids(i) = ranker.IdAt(i) | |||||
| scores(i) = -ranker.ScoreAt(i) ' ChunkJson negates again | |||||
| Next | |||||
| idList = "" | idList = "" | ||||
| For i = 0 To n - 1 | For i = 0 To n - 1 | ||||
| @@ -393,7 +393,7 @@ Class ApiDocumentsController_Class | |||||
| End If | End If | ||||
| Next | Next | ||||
| Api_Audit "document.search", "search", "", "ok" | Api_Audit "document.search", "search", "", "ok" | ||||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[]}" | |||||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}" | |||||
| End Sub | End Sub | ||||
| '=============================================================== | '=============================================================== | ||||
| @@ -103,6 +103,7 @@ Class ApiMemoriesController_Class | |||||
| "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts) | "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts) | ||||
| InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts | InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts | ||||
| Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw | Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw | ||||
| Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1 | |||||
| resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed"",""duplicate"":false}" | resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed"",""duplicate"":false}" | ||||
| StoreIdem idemKey, reqHash, 201, resp | StoreIdem idemKey, reqHash, 201, resp | ||||
| If Err.Number <> 0 Then | If Err.Number <> 0 Then | ||||
| @@ -119,6 +120,7 @@ Class ApiMemoriesController_Class | |||||
| End If | End If | ||||
| On Error GoTo 0 | On Error GoTo 0 | ||||
| Emb_AfterWrite Api_TenantId, 8 | |||||
| Api_Audit "memory.remember", "memory", memId, "ok" | Api_Audit "memory.remember", "memory", memId, "ok" | ||||
| Response.AddHeader "Location", "/api/v1/memories/" & memId | Response.AddHeader "Location", "/api/v1/memories/" & memId | ||||
| Api_Send 201, resp | Api_Send 201, resp | ||||
| @@ -379,6 +381,7 @@ Class ApiMemoriesController_Class | |||||
| DAL().BeginTransaction | DAL().BeginTransaction | ||||
| InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts | InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts | ||||
| Search_IndexMemory id, newRev, Api_TenantId, nsId, title, content, tagsRaw | Search_IndexMemory id, newRev, Api_TenantId, nsId, title, content, tagsRaw | ||||
| Emb_MarkPending "memory", id, Api_TenantId, nsId, newRev | |||||
| DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _ | DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _ | ||||
| Array(newRev, ts, id, Api_TenantId, curRev) | Array(newRev, ts, id, Api_TenantId, curRev) | ||||
| If Err.Number <> 0 Then | If Err.Number <> 0 Then | ||||
| @@ -395,6 +398,7 @@ Class ApiMemoriesController_Class | |||||
| End If | End If | ||||
| On Error GoTo 0 | On Error GoTo 0 | ||||
| Emb_AfterWrite Api_TenantId, 8 | |||||
| Api_Audit "memory.correct", "memory", id, "ok" | Api_Audit "memory.correct", "memory", id, "ok" | ||||
| Response.AddHeader "ETag", """" & newRev & """" | Response.AddHeader "ETag", """" & newRev & """" | ||||
| resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed""}" | resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed""}" | ||||
| @@ -429,6 +433,7 @@ Class ApiMemoriesController_Class | |||||
| On Error Resume Next | On Error Resume Next | ||||
| DAL().BeginTransaction | DAL().BeginTransaction | ||||
| Search_UnindexMemory id | Search_UnindexMemory id | ||||
| Emb_MarkDelete "memory", id | |||||
| DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id | DAL().Execute "DELETE FROM memory_revisions WHERE memory_id = ?", id | ||||
| DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId) | DAL().Execute "DELETE FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId) | ||||
| If Err.Number <> 0 Then | If Err.Number <> 0 Then | ||||
| @@ -440,6 +445,7 @@ Class ApiMemoriesController_Class | |||||
| DAL().CommitTransaction | DAL().CommitTransaction | ||||
| On Error GoTo 0 | On Error GoTo 0 | ||||
| Emb_AfterWrite Api_TenantId, 8 | |||||
| Api_Audit "memory.forget", "memory", id, "ok" | Api_Audit "memory.forget", "memory", id, "ok" | ||||
| Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}" | Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}" | ||||
| End Sub | End Sub | ||||
| @@ -599,12 +605,13 @@ Class ApiMemoriesController_Class | |||||
| '--------------------------------------------------------------- | '--------------------------------------------------------------- | ||||
| ' POST /api/v1/recall | ' POST /api/v1/recall | ||||
| ' {"query","types":[],"namespace_ids":[],"verification_filter":"verified_only|include_unverified","max_results","detail_level":"full|summary"} | ' {"query","types":[],"namespace_ids":[],"verification_filter":"verified_only|include_unverified","max_results","detail_level":"full|summary"} | ||||
| ' Lexical (FTS5/bm25) retrieval over active memories the caller can read. Trusted retrieval is the default, so | |||||
| ' Hybrid retrieval (FTS5/bm25 fused with vector similarity when configured, see core/lib.Embeddings.asp) over | |||||
| ' active memories the caller can read. Trusted retrieval is the default, so | |||||
| ' unverified memories are left out unless asked for (they are labelled when included). | ' unverified memories are left out unless asked for (they are labelled when included). | ||||
| '--------------------------------------------------------------- | '--------------------------------------------------------------- | ||||
| Public Sub Recall() | Public Sub Recall() | ||||
| Dim body, input, query, fts, maxResults, detail, vf, allowed, requested, typesSql, ids(), scores(), n, rs, i, j, idList, sql | Dim body, input, query, fts, maxResults, detail, vf, allowed, requested, typesSql, ids(), scores(), n, rs, i, j, idList, sql | ||||
| Dim rowJson(), out, count, excluded, now_, v, st, params, warnings | |||||
| Dim rowJson(), out, count, excluded, now_, v, st, params, warnings, ranker | |||||
| If Not Api_Authenticate() Then Exit Sub | If Not Api_Authenticate() Then Exit Sub | ||||
| body = Api_ReadBody() | body = Api_ReadBody() | ||||
| @@ -651,21 +658,22 @@ Class ApiMemoriesController_Class | |||||
| Exit Sub | Exit Sub | ||||
| End If | End If | ||||
| Set rs = DAL().Query("SELECT memory_id, bm25(memories_fts) FROM memories_fts WHERE memories_fts MATCH ? AND tenant_id = ? ORDER BY bm25(memories_fts) LIMIT 300", Array(fts, Api_TenantId)) | |||||
| n = 0 | |||||
| ReDim ids(63) | |||||
| ReDim scores(63) | |||||
| Do While Not rs.EOF | |||||
| If n > UBound(ids) Then | |||||
| ReDim Preserve ids(n * 2) | |||||
| ReDim Preserve scores(n * 2) | |||||
| End If | |||||
| ids(n) = "" & rs(0) | |||||
| scores(n) = rs(1) | |||||
| n = n + 1 | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| ' Lexical + (when configured) semantic candidates, fused; scores are negated here to match the output below | |||||
| Set ranker = New Ranker_Class | |||||
| ranker.Run "memory", fts, query, Api_TenantId, allowed | |||||
| n = ranker.Count | |||||
| If n > 0 Then | |||||
| ReDim ids(n - 1) | |||||
| ReDim scores(n - 1) | |||||
| For i = 0 To n - 1 | |||||
| ids(i) = ranker.IdAt(i) | |||||
| scores(i) = -ranker.ScoreAt(i) | |||||
| Next | |||||
| End If | |||||
| warnings = "" | |||||
| If Len(ranker.Warning) > 0 Then | |||||
| warnings = JsonLite_Quote(ranker.Warning) | |||||
| End If | |||||
| out = "" | out = "" | ||||
| count = 0 | count = 0 | ||||
| @@ -711,10 +719,13 @@ Class ApiMemoriesController_Class | |||||
| Next | Next | ||||
| End If | End If | ||||
| If excluded > 0 Then | If excluded > 0 Then | ||||
| warnings = "[""semantic retrieval is not configured; results are lexical only"",""" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them""]" | |||||
| If Len(warnings) > 0 Then | |||||
| warnings = warnings & "," | |||||
| End If | |||||
| warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them""" | |||||
| End If | End If | ||||
| Api_Audit "memory.recall", "search", "", "ok" | Api_Audit "memory.recall", "search", "", "ok" | ||||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":" & warnings & "}" | |||||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}" | |||||
| End Sub | End Sub | ||||
| '=============================================================== | '=============================================================== | ||||
| @@ -18,6 +18,7 @@ | |||||
| <!--#include file="../core/lib.JsonLite.asp"--> | <!--#include file="../core/lib.JsonLite.asp"--> | ||||
| <!--#include file="../core/lib.Api.asp"--> | <!--#include file="../core/lib.Api.asp"--> | ||||
| <!--#include file="../core/lib.Search.asp"--> | <!--#include file="../core/lib.Search.asp"--> | ||||
| <!--#include file="../core/lib.Embeddings.asp"--> | |||||
| <!--#include file="../app/models/autoload_models.asp" --> | <!--#include file="../app/models/autoload_models.asp" --> | ||||
| <!--#include file="../app/controllers/autoload_controllers.asp" --> | <!--#include file="../app/controllers/autoload_controllers.asp" --> | ||||
| <!--#include file="../core/mvc.asp"--> | <!--#include file="../core/mvc.asp"--> | ||||
| @@ -0,0 +1,571 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' Semantic retrieval: embeddings (Ollama) + vector index (Qdrant) + hybrid ranking (spec FR-008, FR-009, section 10). | |||||
| ' | |||||
| ' SQLite is the source of truth. Table embedding_index records, per memory/chunk, what the vector store should hold | |||||
| ' (status pending | indexed | failed | delete, model, dimensions, revision). Write paths only mark rows inside their | |||||
| ' transaction (Emb_MarkPending / Emb_MarkDelete*); after commit they call Emb_AfterWrite, which indexes a bounded batch | |||||
| ' and never fails the request. scripts\embed.cmd processes everything left over or rebuilds the index. | |||||
| ' | |||||
| ' Vectors are never parsed in VBScript: Ollama's JSON array text is passed straight into the Qdrant request body. | |||||
| ' Qdrant points use the memory/chunk id as point id and carry tenant_id, namespace_id, kind and revision as payload. | |||||
| ' Search filters by tenant, kind and the caller's readable namespaces in Qdrant, and callers then re-check every hit | |||||
| ' against the canonical tables (namespace, lifecycle, validity, current revision), as for lexical hits. | |||||
| ' | |||||
| ' Settings (web.config appSettings): | |||||
| ' EmbeddingProvider ollama | none (default none: lexical only, with a warning) | |||||
| ' EmbeddingUrl http://ollama:11434 | |||||
| ' EmbeddingModel nomic-embed-text | |||||
| ' EmbeddingDimensions 768 | |||||
| ' EmbeddingDocumentPrefix "search_document: " (model-specific task prefixes; empty for models without them) | |||||
| ' EmbeddingQueryPrefix "search_query: " | |||||
| ' EmbeddingMinScore cosine similarity below which a semantic hit is ignored (default 0.6; model-specific: for | |||||
| ' nomic-embed-text relevant pairs scored 0.61-0.67, unrelated ones up to 0.58) | |||||
| ' VectorStoreUrl http://qdrant:6333 | |||||
| ' The Qdrant collection is amk_<model>_<dimensions>, so changing the model starts a new collection (run embed reindex). | |||||
| ' No native object is held across calls: each HTTP call creates and releases its own MSXML2.ServerXMLHTTP. | |||||
| '======================================================================================================================= | |||||
| Const EMB_RRF_K = 60 | |||||
| Const EMB_BATCH = 16 | |||||
| Const EMB_MAX_ATTEMPTS = 5 | |||||
| Const EMB_MAX_TEXT = 8000 | |||||
| Dim Emb_LastError | |||||
| Emb_LastError = "" | |||||
| Function Emb_Setting(key, dflt) | |||||
| Dim v | |||||
| v = "" & GetAppSetting(key) | |||||
| If Len(v) = 0 Then | |||||
| v = dflt | |||||
| End If | |||||
| Emb_Setting = v | |||||
| End Function | |||||
| Function Emb_Enabled() | |||||
| Emb_Enabled = (LCase(Emb_Setting("EmbeddingProvider", "none")) = "ollama") | |||||
| End Function | |||||
| Function Emb_Model() | |||||
| Emb_Model = Emb_Setting("EmbeddingModel", "nomic-embed-text") | |||||
| End Function | |||||
| Function Emb_Dims() | |||||
| Emb_Dims = CLng(Emb_Setting("EmbeddingDimensions", "768")) | |||||
| End Function | |||||
| Function Emb_MinScore() | |||||
| Emb_MinScore = CDbl(Replace(Emb_Setting("EmbeddingMinScore", "0.6"), ".", Mid(CStr(1.5), 2, 1))) | |||||
| End Function | |||||
| Function Emb_Collection() | |||||
| Dim m, i, c, out | |||||
| m = LCase(Emb_Model()) | |||||
| out = "" | |||||
| For i = 1 To Len(m) | |||||
| c = Mid(m, i, 1) | |||||
| If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Then | |||||
| out = out & c | |||||
| Else | |||||
| out = out & "_" | |||||
| End If | |||||
| Next | |||||
| Emb_Collection = "amk_" & out & "_" & Emb_Dims() | |||||
| End Function | |||||
| ' One HTTP call. Returns the response text; status 0 and Emb_LastError on a transport failure. | |||||
| Function Emb_Http(method, url, body, ByRef status) | |||||
| Dim http, text | |||||
| Emb_Http = "" | |||||
| status = 0 | |||||
| On Error Resume Next | |||||
| Set http = Server.CreateObject("MSXML2.ServerXMLHTTP") | |||||
| http.SetTimeouts 2000, 2000, 10000, 60000 | |||||
| http.Open method, url, False | |||||
| If Len(body) > 0 Then | |||||
| http.SetRequestHeader "Content-Type", "application/json" | |||||
| http.Send body | |||||
| Else | |||||
| http.Send | |||||
| End If | |||||
| If Err.Number <> 0 Then | |||||
| Emb_LastError = method & " " & url & ": " & Err.Description | |||||
| Err.Clear | |||||
| Set http = Nothing | |||||
| Exit Function | |||||
| End If | |||||
| status = http.Status | |||||
| text = "" & http.ResponseText | |||||
| Set http = Nothing | |||||
| On Error GoTo 0 | |||||
| If status < 200 Or status > 299 Then | |||||
| Emb_LastError = method & " " & url & ": HTTP " & status & " " & Left(text, 200) | |||||
| End If | |||||
| Emb_Http = text | |||||
| End Function | |||||
| ' Embeds texts (array of strings) with the given task prefix. Returns an array of raw JSON vectors ("[0.1,...]"), | |||||
| ' one per text, or Empty on failure (Emb_LastError says why). | |||||
| Function Emb_EmbedTexts(texts, prefix) | |||||
| Dim body, i, resp, status, p, q, inner, vecs, marker | |||||
| Emb_EmbedTexts = Empty | |||||
| body = "" | |||||
| For i = 0 To UBound(texts) | |||||
| If i > 0 Then | |||||
| body = body & "," | |||||
| End If | |||||
| body = body & JsonLite_Quote(prefix & Left("" & texts(i), EMB_MAX_TEXT)) | |||||
| Next | |||||
| body = "{""model"":" & JsonLite_Quote(Emb_Model()) & ",""truncate"":true,""input"":[" & body & "]}" | |||||
| resp = Emb_Http("POST", Emb_Setting("EmbeddingUrl", "http://ollama:11434") & "/api/embed", body, status) | |||||
| If status <> 200 Then | |||||
| Exit Function | |||||
| End If | |||||
| ' {"model":"...","embeddings":[[...],[...]],...}: vectors hold only numbers, so "]]" ends the list | |||||
| marker = """embeddings"":[[" | |||||
| p = InStr(resp, marker) | |||||
| If p = 0 Then | |||||
| Emb_LastError = "embedding response without embeddings" | |||||
| Exit Function | |||||
| End If | |||||
| p = p + Len(marker) | |||||
| q = InStr(p, resp, "]]") | |||||
| If q = 0 Then | |||||
| Emb_LastError = "embedding response is truncated" | |||||
| Exit Function | |||||
| End If | |||||
| inner = Replace(Replace(Mid(resp, p, q - p), " ", ""), vbLf, "") | |||||
| vecs = Split(inner, "],[") | |||||
| If UBound(vecs) <> UBound(texts) Then | |||||
| Emb_LastError = "embedding count mismatch (" & (UBound(vecs) + 1) & " for " & (UBound(texts) + 1) & " texts)" | |||||
| Exit Function | |||||
| End If | |||||
| For i = 0 To UBound(vecs) | |||||
| If UBound(Split(vecs(i), ",")) + 1 <> Emb_Dims() Then | |||||
| Emb_LastError = "model returned " & (UBound(Split(vecs(i), ",")) + 1) & " dimensions, EmbeddingDimensions is " & Emb_Dims() | |||||
| Exit Function | |||||
| End If | |||||
| vecs(i) = "[" & vecs(i) & "]" | |||||
| Next | |||||
| Emb_EmbedTexts = vecs | |||||
| End Function | |||||
| ' Creates the collection (cosine, configured size) and keyword payload indexes once per process. | |||||
| Function Emb_EnsureCollection() | |||||
| Dim name, base, status, resp, f | |||||
| name = Emb_Collection() | |||||
| Emb_EnsureCollection = False | |||||
| If Application("emb_ok_" & name) = True Then | |||||
| Emb_EnsureCollection = True | |||||
| Exit Function | |||||
| End If | |||||
| base = Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & name | |||||
| resp = Emb_Http("GET", base, "", status) | |||||
| If status = 404 Then | |||||
| resp = Emb_Http("PUT", base, "{""vectors"":{""size"":" & Emb_Dims() & ",""distance"":""Cosine""}}", status) | |||||
| If status <> 200 Then | |||||
| Exit Function | |||||
| End If | |||||
| For Each f In Array("tenant_id", "namespace_id", "kind") | |||||
| resp = Emb_Http("PUT", base & "/index?wait=true", "{""field_name"":""" & f & """,""field_schema"":""keyword""}", status) | |||||
| Next | |||||
| ElseIf status <> 200 Then | |||||
| Exit Function | |||||
| End If | |||||
| Application.Lock | |||||
| Application("emb_ok_" & name) = True | |||||
| Application.Unlock | |||||
| Emb_EnsureCollection = True | |||||
| End Function | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Bookkeeping (call inside the write transaction) | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Sub Emb_MarkPending(kind, targetId, tenantId, namespaceId, revision) | |||||
| DAL().Execute "INSERT INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _ | |||||
| "VALUES (?, ?, ?, ?, ?, 'pending', 0, ?) ON CONFLICT(target_kind, target_id) DO UPDATE SET status = 'pending', " & _ | |||||
| "revision = excluded.revision, namespace_id = excluded.namespace_id, attempts = 0, error = NULL, updated_at = excluded.updated_at", _ | |||||
| Array(kind, targetId, tenantId, namespaceId, CLng(revision), Api_Now()) | |||||
| End Sub | |||||
| Sub Emb_MarkDelete(kind, targetId) | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), kind, targetId) | |||||
| End Sub | |||||
| ' Old revision's chunks of a document leave the vector index | |||||
| Sub Emb_MarkDeleteChunks(documentId, revision) | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = 'chunk' AND target_id IN " & _ | |||||
| "(SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(Api_Now(), documentId, CLng(revision)) | |||||
| End Sub | |||||
| ' After commit: index a bounded batch for this tenant. Never raises; a failure leaves rows pending/failed for later. | |||||
| Sub Emb_AfterWrite(tenantId, maxItems) | |||||
| Dim n | |||||
| If Not Emb_Enabled() Then | |||||
| Exit Sub | |||||
| End If | |||||
| On Error Resume Next | |||||
| n = Emb_ProcessPending(tenantId, maxItems) | |||||
| If Err.Number <> 0 Then | |||||
| Emb_LastError = "process: " & Err.Description | |||||
| Err.Clear | |||||
| End If | |||||
| On Error GoTo 0 | |||||
| End Sub | |||||
| ' Processes deletions and up to maxItems pending/failed rows (tenantId "" = all tenants). Returns rows indexed. | |||||
| Function Emb_ProcessPending(tenantId, maxItems) | |||||
| Dim rs, sql, ids, n, idList, status, resp, rows, i, j, k, cnt, texts(), kinds(), tids(), tens(), nss(), revs(), text, rev, ok | |||||
| Dim batchStart, batchEnd, bt(), vecs, body, done, ts | |||||
| Emb_ProcessPending = 0 | |||||
| If Not Emb_Enabled() Then | |||||
| Exit Function | |||||
| End If | |||||
| If Not Emb_EnsureCollection() Then | |||||
| Exit Function | |||||
| End If | |||||
| '--- deletions ------------------------------------------------------------------------------------------------ | |||||
| sql = "SELECT target_id FROM embedding_index WHERE status = 'delete'" | |||||
| If Len(tenantId) > 0 Then | |||||
| sql = sql & " AND tenant_id = ?" | |||||
| Set rs = DAL().Query(sql & " LIMIT 256", tenantId) | |||||
| Else | |||||
| Set rs = DAL().Query(sql & " LIMIT 256", Empty) | |||||
| End If | |||||
| idList = "" | |||||
| ids = "" | |||||
| Do While Not rs.EOF | |||||
| If Api_IsId("" & rs(0)) Then | |||||
| If Len(idList) > 0 Then | |||||
| idList = idList & "," | |||||
| ids = ids & "," | |||||
| End If | |||||
| idList = idList & "'" & rs(0) & "'" | |||||
| ids = ids & """" & rs(0) & """" | |||||
| End If | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| If Len(idList) > 0 Then | |||||
| resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _ | |||||
| "{""points"":[" & ids & "]}", status) | |||||
| If status = 200 Then | |||||
| DAL().Execute "DELETE FROM embedding_index WHERE status = 'delete' AND target_id IN (" & idList & ")", Empty | |||||
| Else | |||||
| Exit Function | |||||
| End If | |||||
| End If | |||||
| '--- pending and retryable failures --------------------------------------------------------------------------- | |||||
| sql = "SELECT target_kind, target_id, tenant_id, namespace_id, revision FROM embedding_index WHERE (status = 'pending' OR (status = 'failed' AND attempts < " & EMB_MAX_ATTEMPTS & "))" | |||||
| If Len(tenantId) > 0 Then | |||||
| Set rs = DAL().Query(sql & " AND tenant_id = ? ORDER BY updated_at LIMIT " & CLng(maxItems), tenantId) | |||||
| Else | |||||
| Set rs = DAL().Query(sql & " ORDER BY updated_at LIMIT " & CLng(maxItems), Empty) | |||||
| End If | |||||
| rows = Empty | |||||
| If Not rs.EOF Then | |||||
| rows = rs.GetRows() | |||||
| End If | |||||
| rs.Close | |||||
| If IsEmpty(rows) Then | |||||
| Exit Function | |||||
| End If | |||||
| ' Load the text to embed for every row (each query closed before the next) | |||||
| cnt = UBound(rows, 2) + 1 | |||||
| ReDim texts(cnt - 1) | |||||
| ReDim kinds(cnt - 1) | |||||
| ReDim tids(cnt - 1) | |||||
| ReDim tens(cnt - 1) | |||||
| ReDim nss(cnt - 1) | |||||
| ReDim revs(cnt - 1) | |||||
| k = 0 | |||||
| For i = 0 To cnt - 1 | |||||
| text = "" | |||||
| rev = 0 | |||||
| If "" & rows(0, i) = "memory" Then | |||||
| Set rs = DAL().Query("SELECT r.title, r.content, m.current_revision, m.namespace_id FROM memories m JOIN memory_revisions r " & _ | |||||
| "ON r.memory_id = m.id AND r.revision = m.current_revision WHERE m.id = ?", "" & rows(1, i)) | |||||
| If Not rs.EOF Then | |||||
| text = "" & rs(0) & vbLf & rs(1) | |||||
| rev = CLng(rs(2)) | |||||
| rows(3, i) = "" & rs(3) | |||||
| End If | |||||
| rs.Close | |||||
| Else | |||||
| Set rs = DAL().Query("SELECT content, document_revision FROM chunks WHERE id = ?", "" & rows(1, i)) | |||||
| If Not rs.EOF Then | |||||
| text = "" & rs(0) | |||||
| rev = CLng(rs(1)) | |||||
| End If | |||||
| rs.Close | |||||
| End If | |||||
| If Len(text) = 0 Then | |||||
| ' the source is gone: drop the row (and any point) | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), "" & rows(0, i), "" & rows(1, i)) | |||||
| Else | |||||
| texts(k) = text | |||||
| kinds(k) = "" & rows(0, i) | |||||
| tids(k) = "" & rows(1, i) | |||||
| tens(k) = "" & rows(2, i) | |||||
| nss(k) = "" & rows(3, i) | |||||
| revs(k) = rev | |||||
| k = k + 1 | |||||
| End If | |||||
| Next | |||||
| done = 0 | |||||
| batchStart = 0 | |||||
| Do While batchStart < k | |||||
| batchEnd = batchStart + EMB_BATCH - 1 | |||||
| If batchEnd > k - 1 Then | |||||
| batchEnd = k - 1 | |||||
| End If | |||||
| ReDim bt(batchEnd - batchStart) | |||||
| For j = batchStart To batchEnd | |||||
| bt(j - batchStart) = texts(j) | |||||
| Next | |||||
| vecs = Emb_EmbedTexts(bt, Emb_Setting("EmbeddingDocumentPrefix", "")) | |||||
| ok = Not IsEmpty(vecs) | |||||
| If ok Then | |||||
| body = "" | |||||
| For j = batchStart To batchEnd | |||||
| If j > batchStart Then | |||||
| body = body & "," | |||||
| End If | |||||
| body = body & "{""id"":""" & tids(j) & """,""vector"":" & vecs(j - batchStart) & ",""payload"":{""tenant_id"":""" & tens(j) & _ | |||||
| """,""namespace_id"":""" & nss(j) & """,""kind"":""" & kinds(j) & """,""revision"":" & revs(j) & "}}" | |||||
| Next | |||||
| resp = Emb_Http("PUT", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points?wait=true", _ | |||||
| "{""points"":[" & body & "]}", status) | |||||
| ok = (status = 200) | |||||
| End If | |||||
| ts = Api_Now() | |||||
| For j = batchStart To batchEnd | |||||
| If ok Then | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'indexed', model = ?, dimensions = ?, revision = ?, attempts = 0, error = NULL, updated_at = ? " & _ | |||||
| "WHERE target_kind = ? AND target_id = ? AND status <> 'delete'", Array(Emb_Model(), Emb_Dims(), revs(j), ts, kinds(j), tids(j)) | |||||
| done = done + 1 | |||||
| Else | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'failed', attempts = attempts + 1, error = ?, updated_at = ? WHERE target_kind = ? AND target_id = ?", _ | |||||
| Array(Left(Emb_LastError, 500), ts, kinds(j), tids(j)) | |||||
| End If | |||||
| Next | |||||
| If Not ok Then | |||||
| Exit Do ' provider or store down: leave the rest for later | |||||
| End If | |||||
| batchStart = batchEnd + 1 | |||||
| Loop | |||||
| Emb_ProcessPending = done | |||||
| End Function | |||||
| ' Removes a whole tenant from the vector store and the bookkeeping (provision purge). Best effort for the store. | |||||
| Sub Emb_DeleteTenant(tenantId) | |||||
| Dim status, resp | |||||
| If Emb_Enabled() Then | |||||
| If Emb_EnsureCollection() Then | |||||
| resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _ | |||||
| "{""filter"":{""must"":[{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}]}}", status) | |||||
| End If | |||||
| End If | |||||
| DAL().Execute "DELETE FROM embedding_index WHERE tenant_id = ?", tenantId | |||||
| End Sub | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| ' Hybrid ranking. Lexical (FTS5/bm25) and, when configured, semantic (Qdrant cosine) candidate lists are merged with | |||||
| ' reciprocal rank fusion (raw scores of the two engines are not comparable). Without semantic retrieval the order and | |||||
| ' scores are the lexical ones (negated bm25). Callers still apply the canonical filters to every id. | |||||
| ' Set r = New Ranker_Class : r.Run "memory"|"chunk", ftsQuery, queryText, tenantId, allowedSqlList | |||||
| ' r.Count, r.IdAt(i), r.ScoreAt(i), r.Strategy ("lexical"|"hybrid"), r.Warning ("" or a sentence) | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Class Ranker_Class | |||||
| Private m_ids(), m_scores(), m_n, m_strategy, m_warning | |||||
| Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN | |||||
| Private Sub Class_Initialize() | |||||
| m_n = 0 | |||||
| ReDim m_ids(0) | |||||
| ReDim m_scores(0) | |||||
| m_strategy = "lexical" | |||||
| m_warning = "" | |||||
| End Sub | |||||
| Public Property Get Count() | |||||
| Count = m_n | |||||
| End Property | |||||
| Public Function IdAt(i) | |||||
| IdAt = m_ids(i) | |||||
| End Function | |||||
| Public Function ScoreAt(i) | |||||
| ScoreAt = m_scores(i) | |||||
| End Function | |||||
| Public Property Get Strategy() | |||||
| Strategy = m_strategy | |||||
| End Property | |||||
| Public Property Get Warning() | |||||
| Warning = m_warning | |||||
| End Property | |||||
| Public Sub Run(kind, fts, queryText, tenantId, allowed) | |||||
| Dim rs, tbl, col, i | |||||
| If kind = "memory" Then | |||||
| tbl = "memories_fts" | |||||
| col = "memory_id" | |||||
| Else | |||||
| tbl = "chunks_fts" | |||||
| col = "chunk_id" | |||||
| End If | |||||
| m_lexN = 0 | |||||
| ReDim m_lex(63) | |||||
| ReDim m_lexScore(63) | |||||
| If Len(fts) > 0 Then | |||||
| Set rs = DAL().Query("SELECT " & col & ", bm25(" & tbl & ") FROM " & tbl & " WHERE " & tbl & " MATCH ? AND tenant_id = ? ORDER BY bm25(" & tbl & ") LIMIT 300", Array(fts, tenantId)) | |||||
| Do While Not rs.EOF | |||||
| If m_lexN > UBound(m_lex) Then | |||||
| ReDim Preserve m_lex(m_lexN * 2) | |||||
| ReDim Preserve m_lexScore(m_lexN * 2) | |||||
| End If | |||||
| m_lex(m_lexN) = "" & rs(0) | |||||
| m_lexScore(m_lexN) = -CDbl(rs(1)) | |||||
| m_lexN = m_lexN + 1 | |||||
| rs.MoveNext | |||||
| Loop | |||||
| rs.Close | |||||
| End If | |||||
| m_semN = 0 | |||||
| ReDim m_sem(0) | |||||
| If Not Emb_Enabled() Then | |||||
| m_warning = "semantic retrieval is not configured; results are lexical only" | |||||
| ElseIf Len(allowed) = 0 Then | |||||
| m_strategy = "hybrid" | |||||
| ElseIf SemanticSearch(kind, queryText, tenantId, allowed) Then | |||||
| m_strategy = "hybrid" | |||||
| Else | |||||
| m_warning = "semantic retrieval is unavailable; results are lexical only" | |||||
| End If | |||||
| If m_strategy = "hybrid" Then | |||||
| Fuse | |||||
| Else | |||||
| m_n = m_lexN | |||||
| ReDim m_ids(m_n) | |||||
| ReDim m_scores(m_n) | |||||
| For i = 0 To m_lexN - 1 | |||||
| m_ids(i) = m_lex(i) | |||||
| m_scores(i) = m_lexScore(i) | |||||
| Next | |||||
| End If | |||||
| End Sub | |||||
| ' Embeds the query and asks Qdrant for the closest points of this kind in the tenant's allowed namespaces. | |||||
| Private Function SemanticSearch(kind, queryText, tenantId, allowed) | |||||
| Dim vecs, body, resp, status, p, q, id, sc, minScore | |||||
| SemanticSearch = False | |||||
| If Not Emb_EnsureCollection() Then | |||||
| Exit Function | |||||
| End If | |||||
| vecs = Emb_EmbedTexts(Array(queryText), Emb_Setting("EmbeddingQueryPrefix", "")) | |||||
| If IsEmpty(vecs) Then | |||||
| Exit Function | |||||
| End If | |||||
| body = "{""query"":" & vecs(0) & ",""limit"":100,""with_payload"":false,""filter"":{""must"":[" & _ | |||||
| "{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}," & _ | |||||
| "{""key"":""kind"",""match"":{""value"":""" & kind & """}}," & _ | |||||
| "{""key"":""namespace_id"",""match"":{""any"":[" & Replace(allowed, "'", """") & "]}}]}}" | |||||
| resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/query", body, status) | |||||
| If status <> 200 Then | |||||
| Exit Function | |||||
| End If | |||||
| minScore = Emb_MinScore() | |||||
| ' {"result":{"points":[{"id":"...","version":n,"score":0.8},...]},...}: scan id/score pairs in order | |||||
| p = InStr(resp, """id"":""") | |||||
| Do While p > 0 | |||||
| p = p + 6 | |||||
| q = InStr(p, resp, """") | |||||
| id = Mid(resp, p, q - p) | |||||
| p = InStr(q, resp, """score"":") | |||||
| If p = 0 Then | |||||
| Exit Do | |||||
| End If | |||||
| p = p + 8 | |||||
| q = p | |||||
| Do While q <= Len(resp) | |||||
| If InStr("0123456789.-+eE", Mid(resp, q, 1)) = 0 Then | |||||
| Exit Do | |||||
| End If | |||||
| q = q + 1 | |||||
| Loop | |||||
| sc = CDbl(Replace(Mid(resp, p, q - p), ".", Mid(CStr(1.5), 2, 1))) | |||||
| If sc >= minScore Then | |||||
| If m_semN > UBound(m_sem) Then | |||||
| ReDim Preserve m_sem(m_semN * 2 + 1) | |||||
| End If | |||||
| m_sem(m_semN) = id | |||||
| m_semN = m_semN + 1 | |||||
| End If | |||||
| p = InStr(q, resp, """id"":""") | |||||
| Loop | |||||
| SemanticSearch = True | |||||
| End Function | |||||
| ' Reciprocal rank fusion over the top 100 of each list, sorted by fused score (descending) | |||||
| Private Sub Fuse() | |||||
| Dim i, j, lim, found, t, ts | |||||
| m_n = 0 | |||||
| ReDim m_ids(200) | |||||
| ReDim m_scores(200) | |||||
| lim = m_lexN | |||||
| If lim > 100 Then | |||||
| lim = 100 | |||||
| End If | |||||
| For i = 0 To lim - 1 | |||||
| m_ids(m_n) = m_lex(i) | |||||
| m_scores(m_n) = 1 / (EMB_RRF_K + i + 1) | |||||
| m_n = m_n + 1 | |||||
| Next | |||||
| lim = m_semN | |||||
| If lim > 100 Then | |||||
| lim = 100 | |||||
| End If | |||||
| For i = 0 To lim - 1 | |||||
| found = -1 | |||||
| For j = 0 To m_n - 1 | |||||
| If m_ids(j) = m_sem(i) Then | |||||
| found = j | |||||
| Exit For | |||||
| End If | |||||
| Next | |||||
| If found >= 0 Then | |||||
| m_scores(found) = m_scores(found) + 1 / (EMB_RRF_K + i + 1) | |||||
| Else | |||||
| m_ids(m_n) = m_sem(i) | |||||
| m_scores(m_n) = 1 / (EMB_RRF_K + i + 1) | |||||
| m_n = m_n + 1 | |||||
| End If | |||||
| Next | |||||
| ' insertion sort, stable for equal scores (lexical order first) | |||||
| For i = 1 To m_n - 1 | |||||
| t = m_ids(i) | |||||
| ts = m_scores(i) | |||||
| j = i - 1 | |||||
| Do While j >= 0 | |||||
| If m_scores(j) >= ts Then | |||||
| Exit Do | |||||
| End If | |||||
| m_ids(j + 1) = m_ids(j) | |||||
| m_scores(j + 1) = m_scores(j) | |||||
| j = j - 1 | |||||
| Loop | |||||
| m_ids(j + 1) = t | |||||
| m_scores(j + 1) = ts | |||||
| Next | |||||
| End Sub | |||||
| End Class | |||||
| %> | |||||
| @@ -12,13 +12,19 @@ | |||||
| ' --------------------------------------------------------------------------------------------------------------------- | ' --------------------------------------------------------------------------------------------------------------------- | ||||
| ' Turns free text into a safe FTS5 expression: up to 16 word tokens, each double-quoted, joined with OR so bm25 ranks | ' 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. | ' 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) | Function Search_FtsQuery(text) | ||||
| Dim t, i, c, n, tok, out, count, code | |||||
| Dim t, i, c, n, tok, out, count, code, outAll, countAll | |||||
| t = "" & text | t = "" & text | ||||
| n = Len(t) | n = Len(t) | ||||
| tok = "" | tok = "" | ||||
| out = "" | out = "" | ||||
| count = 0 | count = 0 | ||||
| outAll = "" | |||||
| countAll = 0 | |||||
| For i = 1 To n + 1 | For i = 1 To n + 1 | ||||
| If i <= n Then | If i <= n Then | ||||
| c = Mid(t, i, 1) | c = Mid(t, i, 1) | ||||
| @@ -27,21 +33,34 @@ Function Search_FtsQuery(text) | |||||
| c = " " | c = " " | ||||
| code = 32 | code = 32 | ||||
| End If | End If | ||||
| If (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (c >= "0" And c <= "9") Or c = "_" Or code > 127 Then | |||||
| ' 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 | tok = tok & c | ||||
| Else | Else | ||||
| If Len(tok) > 0 Then | 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 count < 16 Then | ||||
| If Len(out) > 0 Then | |||||
| out = out & " OR " | |||||
| 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 | ||||
| out = out & """" & Left(tok, 64) & """" | |||||
| count = count + 1 | |||||
| End If | End If | ||||
| tok = "" | tok = "" | ||||
| End If | End If | ||||
| End If | End If | ||||
| Next | Next | ||||
| If Len(out) = 0 Then | |||||
| out = outAll | |||||
| End If | |||||
| Search_FtsQuery = out | Search_FtsQuery = out | ||||
| End Function | End Function | ||||
| @@ -0,0 +1,33 @@ | |||||
| <% | |||||
| '======================================================================================================================= | |||||
| ' MIGRATION: create_embedding_index_table | |||||
| '======================================================================================================================= | |||||
| ' Bookkeeping for semantic (vector) indexing (spec FR-008): one row per indexed memory or chunk. The vectors live in | |||||
| ' the vector store (Qdrant, derived data); this table records what should be there, for which revision, with which | |||||
| ' model/dimensions, and whether it succeeded, so a failed or stale index can always be rebuilt from SQLite. | |||||
| ' status: pending (needs embedding), indexed, failed (attempts counts retries), delete (point must be removed) | |||||
| '----------------------------------------------------------------------------------------------------------------------- | |||||
| Sub Migration_Up(migration) | |||||
| migration.ExecuteSQL "CREATE TABLE embedding_index (" & _ | |||||
| "target_kind TEXT NOT NULL CHECK (target_kind IN ('memory','chunk')), " & _ | |||||
| "target_id TEXT NOT NULL, " & _ | |||||
| "tenant_id TEXT NOT NULL, " & _ | |||||
| "namespace_id TEXT NOT NULL, " & _ | |||||
| "revision INTEGER NOT NULL, " & _ | |||||
| "status TEXT NOT NULL CHECK (status IN ('pending','indexed','failed','delete')), " & _ | |||||
| "model TEXT, " & _ | |||||
| "dimensions INTEGER, " & _ | |||||
| "attempts INTEGER NOT NULL DEFAULT 0, " & _ | |||||
| "error TEXT, " & _ | |||||
| "updated_at TEXT NOT NULL, " & _ | |||||
| "PRIMARY KEY (target_kind, target_id))" | |||||
| migration.CreateIndex "idx_embedding_index_status", "embedding_index", "status, tenant_id" | |||||
| migration.CreateIndex "idx_embedding_index_tenant", "embedding_index", "tenant_id" | |||||
| End Sub | |||||
| Sub Migration_Down(migration) | |||||
| migration.DropIndex "idx_embedding_index_tenant", "embedding_index" | |||||
| migration.DropIndex "idx_embedding_index_status", "embedding_index" | |||||
| migration.DropTable "embedding_index" | |||||
| End Sub | |||||
| %> | |||||
| @@ -15,3 +15,25 @@ services: | |||||
| volumes: | volumes: | ||||
| - .:/opt/axonasp/site | - .:/opt/axonasp/site | ||||
| restart: unless-stopped | restart: unless-stopped | ||||
| # Embedding provider (semantic retrieval). Reached from axonasp as http://ollama:11434. | |||||
| # Pull the model once: docker exec ollama ollama pull nomic-embed-text | |||||
| ollama: | |||||
| image: ollama/ollama:0.13.0 | |||||
| container_name: ollama | |||||
| volumes: | |||||
| - ollama-models:/root/.ollama | |||||
| restart: unless-stopped | |||||
| # Vector index (derived data; SQLite stays the source of truth and can rebuild it). | |||||
| # Reached from axonasp as http://qdrant:6333. | |||||
| qdrant: | |||||
| image: qdrant/qdrant:v1.16.0 | |||||
| container_name: qdrant | |||||
| volumes: | |||||
| - qdrant-data:/qdrant/storage | |||||
| restart: unless-stopped | |||||
| volumes: | |||||
| ollama-models: | |||||
| qdrant-data: | |||||
| @@ -3,7 +3,7 @@ | |||||
| "info": { | "info": { | ||||
| "title": "Agent Memory API", | "title": "Agent Memory API", | ||||
| "version": "1.0.0-phase3", | "version": "1.0.0-phase3", | ||||
| "description": "Universal AI Agent Memory platform, phases 1-3: memories with revisions and verification, sessions with checkpoints, Markdown/text document ingestion with chunk locators, lexical search and recall, health. Authenticate with `Authorization: Bearer <api key>`; the tenant is derived from the key. Anything the caller cannot see is reported as 404. Phase 3: POST /context assembles a budgeted task briefing." | |||||
| "description": "Universal AI Agent Memory platform, phases 1-3: memories with revisions and verification, sessions with checkpoints, Markdown/text document ingestion with chunk locators, lexical search and recall, health. Authenticate with `Authorization: Bearer <api key>`; the tenant is derived from the key. Anything the caller cannot see is reported as 404. Phase 3: POST /context assembles a budgeted task briefing. Retrieval is hybrid (lexical + embeddings via a local Ollama model and a Qdrant index) and degrades to lexical with a warning. Relevance scores are ranking signals: negated bm25 when lexical, reciprocal-rank-fusion values when hybrid." | |||||
| }, | }, | ||||
| "servers": [ | "servers": [ | ||||
| { | { | ||||
| @@ -517,7 +517,11 @@ | |||||
| }, | }, | ||||
| "strategy": { | "strategy": { | ||||
| "type": "string", | "type": "string", | ||||
| "example": "lexical" | |||||
| "enum": [ | |||||
| "hybrid", | |||||
| "lexical" | |||||
| ], | |||||
| "description": "hybrid when semantic retrieval ran for every section; lexical (with a warning) when it is not configured or unavailable" | |||||
| }, | }, | ||||
| "budget": { | "budget": { | ||||
| "type": "object", | "type": "object", | ||||
| @@ -1726,7 +1730,7 @@ | |||||
| }, | }, | ||||
| "/recall": { | "/recall": { | ||||
| "post": { | "post": { | ||||
| "summary": "Lexical recall over active memories; unverified memories are hidden unless verification_filter=include_unverified", | |||||
| "summary": "Hybrid recall over active memories (FTS5/bm25 fused with vector similarity by reciprocal rank fusion; lexical only, with a warning, when the embedding provider is off or down). Unverified memories are hidden unless verification_filter=include_unverified", | |||||
| "security": [ | "security": [ | ||||
| { | { | ||||
| "bearerAuth": [] | "bearerAuth": [] | ||||
| @@ -2080,7 +2084,7 @@ | |||||
| }, | }, | ||||
| "/search": { | "/search": { | ||||
| "post": { | "post": { | ||||
| "summary": "Lexical (FTS5/bm25) search over current document chunks; results are untrusted reference data", | |||||
| "summary": "Hybrid search over current document chunks (lexical fused with vector similarity; lexical only, with a warning, when the embedding provider is off or down). Results are untrusted reference content", | |||||
| "security": [ | "security": [ | ||||
| { | { | ||||
| "bearerAuth": [] | "bearerAuth": [] | ||||
| @@ -2168,7 +2172,7 @@ | |||||
| }, | }, | ||||
| "/context": { | "/context": { | ||||
| "post": { | "post": { | ||||
| "summary": "Assemble a token-budgeted task briefing: constraints by scope, working state, preferences, conflicts, lexical matches and reference passages", | |||||
| "summary": "Assemble a token-budgeted task briefing: constraints by scope, working state, preferences, conflicts, hybrid matches and reference passages", | |||||
| "security": [ | "security": [ | ||||
| { | { | ||||
| "bearerAuth": [] | "bearerAuth": [] | ||||
| @@ -38,6 +38,21 @@ | |||||
| <!-- Cache-bust parameter name (default: "v") --> | <!-- Cache-bust parameter name (default: "v") --> | ||||
| <add key="CacheBustParamName" value="v" /> | <add key="CacheBustParamName" value="v" /> | ||||
| <!-- | |||||
| Semantic retrieval (core/lib.Embeddings.asp). EmbeddingProvider "none" = lexical only. | |||||
| The ollama and qdrant services come from docker-compose.yml. Pull the model once: | |||||
| docker exec ollama ollama pull nomic-embed-text | |||||
| Changing the model or dimensions starts a new vector collection: run scripts\embed.cmd reindex. | |||||
| --> | |||||
| <add key="EmbeddingProvider" value="ollama" /> | |||||
| <add key="EmbeddingUrl" value="http://ollama:11434" /> | |||||
| <add key="EmbeddingModel" value="nomic-embed-text" /> | |||||
| <add key="EmbeddingDimensions" value="768" /> | |||||
| <add key="EmbeddingDocumentPrefix" value="search_document: " /> | |||||
| <add key="EmbeddingQueryPrefix" value="search_query: " /> | |||||
| <add key="EmbeddingMinScore" value="0.6" /> | |||||
| <add key="VectorStoreUrl" value="http://qdrant:6333" /> | |||||
| </appSettings> | </appSettings> | ||||
| <system.webServer> | <system.webServer> | ||||
| @@ -0,0 +1,84 @@ | |||||
| <% | |||||
| ' Semantic index maintenance (see core/lib.Embeddings.asp). Run through scripts\embed.cmd, which sets EMBED_ACTION: | |||||
| ' status | run | reindex | |||||
| ' The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site | |||||
| %> | |||||
| <!--#include file="../core/autoload_core.asp" --> | |||||
| <% | |||||
| Dim sh : Set sh = CreateObject("WScript.Shell") | |||||
| Dim action : action = LCase(Trim(sh.ExpandEnvironmentStrings("%EMBED_ACTION%"))) | |||||
| Dim rs, total, n, rounds, ts | |||||
| Sub ShowStatus() | |||||
| Dim r | |||||
| Response.Write "provider: " & Emb_Setting("EmbeddingProvider", "none") & vbCrLf | |||||
| Response.Write "model: " & Emb_Model() & " (" & Emb_Dims() & " dimensions)" & vbCrLf | |||||
| Response.Write "collection: " & Emb_Collection() & vbCrLf | |||||
| Set r = DAL().Query("SELECT status, COUNT(*) FROM embedding_index GROUP BY status ORDER BY status", Empty) | |||||
| Do While Not r.EOF | |||||
| Response.Write " " & r(0) & ": " & r(1) & vbCrLf | |||||
| r.MoveNext | |||||
| Loop | |||||
| r.Close | |||||
| Set r = DAL().Query("SELECT COUNT(*) FROM embedding_index WHERE status = 'indexed' AND (model <> ? OR dimensions <> ?)", Array(Emb_Model(), Emb_Dims())) | |||||
| If Not r.EOF Then | |||||
| If CLng(r(0)) > 0 Then | |||||
| Response.Write " stale (other model): " & r(0) & " -> run: scripts\embed.cmd reindex" & vbCrLf | |||||
| End If | |||||
| End If | |||||
| r.Close | |||||
| Set r = DAL().Query("SELECT error FROM embedding_index WHERE status = 'failed' ORDER BY updated_at DESC LIMIT 1", Empty) | |||||
| If Not r.EOF Then | |||||
| Response.Write " last error: " & r(0) & vbCrLf | |||||
| End If | |||||
| r.Close | |||||
| End Sub | |||||
| Sub RunAll() | |||||
| total = 0 | |||||
| rounds = 0 | |||||
| Do | |||||
| Emb_LastError = "" | |||||
| n = Emb_ProcessPending("", 64) | |||||
| total = total + n | |||||
| rounds = rounds + 1 | |||||
| If n = 0 Or rounds > 10000 Then | |||||
| Exit Do | |||||
| End If | |||||
| Loop | |||||
| Response.Write "indexed: " & total & vbCrLf | |||||
| If Len(Emb_LastError) > 0 Then | |||||
| Response.Write "ERROR: " & Emb_LastError & vbCrLf | |||||
| End If | |||||
| End Sub | |||||
| Select Case action | |||||
| Case "status" | |||||
| ShowStatus | |||||
| Case "run" | |||||
| If Not Emb_Enabled() Then | |||||
| Response.Write "EmbeddingProvider is not ollama in public/web.config; nothing to do." & vbCrLf | |||||
| Else | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'pending', attempts = 0 WHERE status = 'failed'", Empty | |||||
| RunAll | |||||
| ShowStatus | |||||
| End If | |||||
| Case "reindex" | |||||
| If Not Emb_Enabled() Then | |||||
| Response.Write "EmbeddingProvider is not ollama in public/web.config; nothing to do." & vbCrLf | |||||
| Else | |||||
| ts = Api_Now() | |||||
| ' rows for everything that should be indexed (missing ones are added), all set to pending | |||||
| DAL().Execute "INSERT OR IGNORE INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _ | |||||
| "SELECT 'memory', m.id, m.tenant_id, m.namespace_id, m.current_revision, 'pending', 0, ? FROM memories m WHERE m.lifecycle_status = 'active'", ts | |||||
| DAL().Execute "INSERT OR IGNORE INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _ | |||||
| "SELECT 'chunk', c.id, d.tenant_id, d.namespace_id, c.document_revision, 'pending', 0, ? FROM chunks c JOIN documents d ON d.id = c.document_id " & _ | |||||
| "WHERE c.document_revision = d.current_revision", ts | |||||
| DAL().Execute "UPDATE embedding_index SET status = 'pending', attempts = 0, error = NULL, updated_at = ? WHERE status <> 'delete'", ts | |||||
| RunAll | |||||
| ShowStatus | |||||
| End If | |||||
| Case Else | |||||
| Response.Write "Usage: scripts\embed.cmd status|run|reindex" & vbCrLf | |||||
| End Select | |||||
| %> | |||||
| @@ -0,0 +1,12 @@ | |||||
| @echo off | |||||
| rem Semantic index maintenance, run inside the "axonasp" container. | |||||
| rem | |||||
| rem scripts\embed.cmd status counts per status, model and collection | |||||
| rem scripts\embed.cmd run embed every pending/failed memory and chunk (resets failed attempts first) | |||||
| rem scripts\embed.cmd reindex mark every active memory and current chunk pending, then run | |||||
| rem (after changing EmbeddingModel/EmbeddingDimensions, or to rebuild the vector store) | |||||
| setlocal | |||||
| set CMD=%1 | |||||
| if "%CMD%"=="" set CMD=status | |||||
| docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "EMBED_ACTION=%CMD%" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp | |||||
| exit /b %errorlevel% | |||||
| @@ -181,6 +181,8 @@ Select Case action | |||||
| If Not TenantExists(a1) Then | If Not TenantExists(a1) Then | ||||
| Fail "usage: purge <tenant_id> (tenant must exist)" | Fail "usage: purge <tenant_id> (tenant must exist)" | ||||
| Else | Else | ||||
| ' vector points and their bookkeeping first (the store is outside the transaction; best effort) | |||||
| Emb_DeleteTenant a1 | |||||
| DAL().BeginTransaction | DAL().BeginTransaction | ||||
| DAL().Execute "DELETE FROM chunks_fts WHERE tenant_id = ?", a1 | DAL().Execute "DELETE FROM chunks_fts WHERE tenant_id = ?", a1 | ||||
| DAL().Execute "DELETE FROM memories_fts WHERE tenant_id = ?", a1 | DAL().Execute "DELETE FROM memories_fts WHERE tenant_id = ?", a1 | ||||
| @@ -104,7 +104,7 @@ check "items carry revision and provenance" "yes" "$(echo "$R" | jq_ "'yes' if a | |||||
| check "used tokens within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=d['budget']['max_context_tokens'] else 'no'")" | check "used tokens within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=d['budget']['max_context_tokens'] else 'no'")" | ||||
| check "complete and not truncated" "True False" "$(echo "$R" | jq_ "d['budget']['complete'], d['budget']['truncated']" | tr -d '(),')" | check "complete and not truncated" "True False" "$(echo "$R" | jq_ "d['budget']['complete'], d['budget']['truncated']" | tr -d '(),')" | ||||
| check "counting method declared" "estimate_chars_div_4" "$(echo "$R" | jq_ "d['budget']['counting_method']")" | check "counting method declared" "estimate_chars_div_4" "$(echo "$R" | jq_ "d['budget']['counting_method']")" | ||||
| check "lexical-only warning" "yes" "$(has 'lexical only' "$R")" | |||||
| check "strategy reported" "yes" "$(echo "$R" | jq_ "'yes' if d['strategy'] in ('hybrid','lexical') else 'no'")" | |||||
| check "tenant B content never included" "no" "$(has 'Tenant B secret' "$R")" | check "tenant B content never included" "no" "$(has 'Tenant B secret' "$R")" | ||||
| check "escaped content round-trips" "yes" "$(echo "$R" | jq_ "'yes' if any(x['content']=='Zebracorn quote \"q\" and <script>alert(1)</script> tag.' for x in d['knowledge']) else 'no'")" | check "escaped content round-trips" "yes" "$(echo "$R" | jq_ "'yes' if any(x['content']=='Zebracorn quote \"q\" and <script>alert(1)</script> tag.' for x in d['knowledge']) else 'no'")" | ||||
| check "UTF-8 round trip" "yes" "$(echo "$R" | python -I -c " | check "UTF-8 round trip" "yes" "$(echo "$R" | python -I -c " | ||||
| @@ -0,0 +1,126 @@ | |||||
| #!/usr/bin/env bash | |||||
| # Phase 3 checks for semantic retrieval (spec FR-008, FR-009, section 10): embeddings via Ollama, vectors in Qdrant, | |||||
| # hybrid ranking in /recall, /search and /context, isolation (AC-06), re-indexing on correction, removal on forget, | |||||
| # purge and new document revisions (AC-13), degradation to lexical when the provider is down (AC-16), recovery with | |||||
| # scripts/embed.asp, and a cold start. | |||||
| # | |||||
| # Needs the containers from docker-compose.yml running (axonasp, ollama with nomic-embed-text pulled, qdrant) and | |||||
| # EmbeddingProvider=ollama in public/web.config. Provisions throw-away tenants and purges them at the end. Stops and | |||||
| # restarts the ollama container once. | |||||
| # bash tests/phase3-semantic.sh | |||||
| set -u | |||||
| BASE=${BASE:-http://localhost:8801/api/v1} | |||||
| COLL=${COLL:-amk_nomic_embed_text_768} | |||||
| PASS=0; FAIL=0; FAILED=(); TENANTS=() | |||||
| prov() { | |||||
| MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \ | |||||
| -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \ | |||||
| axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r' | |||||
| } | |||||
| embed() { MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "EMBED_ACTION=$1" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp 2>&1 | tr -d '\r'; } | |||||
| field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } | |||||
| jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; } | |||||
| cleanup() { docker start ollama >/dev/null 2>&1; for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; } | |||||
| trap cleanup EXIT | |||||
| check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; } | |||||
| code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } | |||||
| body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } | |||||
| jq_() { python -I -c "import sys,json;d=json.load(sys.stdin);print($1)"; } | |||||
| js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; } | |||||
| remember() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5")}" | jget id; } | |||||
| verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"verified\",\"method\":\"manual\",\"revision\":${3:-1}}" >/dev/null; } | |||||
| recall() { body "$1" POST /recall -d "{\"query\":$(js "$2")}"; } | |||||
| ids() { jq_ "' '.join(r.get('id', r.get('chunk_id','')) for r in d['results'])"; } | |||||
| # number of vector points of a tenant, optionally of one kind (asked from inside the axonasp container, which can | |||||
| # reach qdrant): points <tenant_id> [memory|chunk] | |||||
| points() { | |||||
| local q | |||||
| q=$(python -I -c " | |||||
| import json,sys | |||||
| must=[{'key':'tenant_id','match':{'value':sys.argv[1]}}] | |||||
| if len(sys.argv)>2 and sys.argv[2]: must.append({'key':'kind','match':{'value':sys.argv[2]}}) | |||||
| print(json.dumps({'exact':True,'filter':{'must':must}}))" "$1" "${2:-}") | |||||
| docker exec axonasp wget -qO- --header='Content-Type: application/json' --post-data="$q" \ | |||||
| "http://qdrant:6333/collections/$COLL/points/count" | python -I -c "import sys,json;print(json.load(sys.stdin)['result']['count'])" | |||||
| } | |||||
| # ---- setup ------------------------------------------------------------------------------------------------ | |||||
| TA=$(prov tenant "p3s-A" | field tenant_id); TB=$(prov tenant "p3s-B" | field tenant_id); TENANTS=("$TA" "$TB") | |||||
| mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); } | |||||
| mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY | |||||
| mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY | |||||
| mk "$TB" writerB agent; BID=$P_ID; BK=$P_KEY | |||||
| prov grant "$WID" /kb "read,write,delete,verify" 1 >/dev/null | |||||
| prov grant "$BID" /kb "read,write,delete,verify" 1 >/dev/null | |||||
| prov grant "$BLID" /elsewhere "read" 1 >/dev/null | |||||
| NS=$(prov namespace "$TA" /kb | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id) | |||||
| [ -n "$NS" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; } | |||||
| # ---- cold start: first request after a restart is a write that must also be embedded -------------------------- | |||||
| docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done | |||||
| M1=$(remember "$WK" "$NS" semantic "Release rule" "Never deploy to production on Fridays."); verify "$WK" "$M1" | |||||
| check "cold: write embedded immediately" "1" "$(points "$TA" memory)" | |||||
| M2=$(remember "$WK" "$NS" semantic "Fruit" "Bananas are a good source of potassium."); verify "$WK" "$M2" | |||||
| M3=$(remember "$WK" "$NS" semantic "Staging" "The staging database is reset every night at 2am."); verify "$WK" "$M3" | |||||
| MB=$(remember "$BK" "$NSB" semantic "B release rule" "Tenant B never deploys to production on Fridays either."); verify "$BK" "$MB" | |||||
| check "all memories embedded" "3" "$(points "$TA" memory)" | |||||
| # ---- semantic recall without word overlap --------------------------------------------------------------------- | |||||
| R=$(recall "$WK" "fruit nutrition") | |||||
| check "paraphrase finds memory" "$M2" "$(echo "$R" | ids)" | |||||
| check "strategy hybrid" "hybrid" "$(echo "$R" | jq_ "d['strategy']")" | |||||
| check "no degradation warning" "0" "$(echo "$R" | jq_ "len(d['warnings'])")" | |||||
| check "second paraphrase" "$M3" "$(recall "$WK" "test environment data wipe schedule" | ids)" | |||||
| check "release question ranks the rule first" "$M1" "$(recall "$WK" "When are we allowed to ship a release?" | jq_ "d['results'][0]['id']")" | |||||
| check "unrelated query below threshold" "" "$(recall "$WK" "quantum chromodynamics lecture" | ids)" | |||||
| check "other tenant never sees A by meaning" "$MB" "$(recall "$BK" "When are we allowed to ship a release?" | ids)" | |||||
| check "principal without namespace sees nothing" "" "$(recall "$BLK" "fruit nutrition" | ids)" | |||||
| # ---- correction re-embeds, forget removes the point ----------------------------------------------------------- | |||||
| check "correct -> 200" "200" "$(code "$WK" PATCH /memories/$M2 -H 'If-Match: 1' -d '{"title":"Coffee machine","content":"The office coffee machine is descaled every Monday."}')" | |||||
| verify "$WK" "$M2" 2 | |||||
| check "old meaning no longer matches" "" "$(recall "$WK" "fruit nutrition" | ids)" | |||||
| check "new meaning matches" "$M2" "$(recall "$WK" "when is the espresso maker cleaned" | ids)" | |||||
| check "forget -> 200" "200" "$(code "$WK" DELETE /memories/$M3)" | |||||
| check "forgotten memory point removed" "2" "$(points "$TA" memory)" | |||||
| # ---- documents --------------------------------------------------------------------------------------------------- | |||||
| DOC1=$(printf '# Runbook\n\nIf the payment gateway times out, restart the checkout worker and page the on-call engineer.\n') | |||||
| D=$(body "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"Runbook\",\"source_uri\":\"kb://runbook\",\"format\":\"markdown\",\"content\":$(js "$DOC1")}" | jget document_id) | |||||
| S=$(body "$WK" POST /search -d '{"query":"what to do when card processing hangs"}') | |||||
| check "semantic chunk search" "yes" "$(echo "$S" | jq_ "'yes' if d['results'] and 'payment gateway' in d['results'][0]['content'] else 'no'")" | |||||
| check "search strategy hybrid" "hybrid" "$(echo "$S" | jq_ "d['strategy']")" | |||||
| P_BEFORE=$(points "$TA" chunk) | |||||
| DOC2=$(printf '# Runbook\n\nFor holiday rotas ask the team lead.\n') | |||||
| body "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"Runbook\",\"source_uri\":\"kb://runbook\",\"format\":\"markdown\",\"content\":$(js "$DOC2")}" >/dev/null | |||||
| check "new revision replaces old chunk points" "$P_BEFORE" "$(points "$TA" chunk)" | |||||
| check "old revision text not found by meaning" "0" "$(body "$WK" POST /search -d '{"query":"what to do when card processing hangs"}' | jq_ "len(d['results'])")" | |||||
| # ---- context uses the same ranking ------------------------------------------------------------------------------- | |||||
| C=$(body "$WK" POST /context -d "{\"task\":\"Plan the timing of the next production release\",\"namespace_ids\":[\"$NS\"]}") | |||||
| check "context finds rule by meaning" "yes" "$(echo "$C" | jq_ "'yes' if any(x['id']=='$M1' for x in d['knowledge']) else 'no'")" | |||||
| check "context strategy hybrid" "hybrid" "$(echo "$C" | jq_ "d['strategy']")" | |||||
| # ---- degradation: provider down ---------------------------------------------------------------------------------- | |||||
| docker stop ollama >/dev/null | |||||
| R=$(recall "$WK" "Fridays production") | |||||
| check "provider down: recall still 200" "$M1" "$(echo "$R" | ids)" | |||||
| check "provider down: lexical strategy" "lexical" "$(echo "$R" | jq_ "d['strategy']")" | |||||
| check "provider down: warning" "yes" "$(echo "$R" | jq_ "'yes' if any('unavailable' in w for w in d['warnings']) else 'no'")" | |||||
| check "provider down: remember still 201" "201" "$(code "$WK" POST /remember -d "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"Pets\",\"content\":\"Dogs are allowed in the office on Thursdays.\"}")" | |||||
| M4=$(body "$WK" GET "/memories?namespace_id=$NS&limit=50" | python -I -c "import sys,json;print([m['id'] for m in json.load(sys.stdin)['data'] if m['title']=='Pets'][0])") | |||||
| verify "$WK" "$M4" | |||||
| check "provider down: new memory not yet embedded" "2" "$(points "$TA" memory)" | |||||
| check "provider down: status shows failed" "yes" "$(embed status | grep -q 'failed: ' && echo yes || echo no)" | |||||
| docker start ollama >/dev/null; for i in $(seq 1 30); do docker exec axonasp wget -qO- http://ollama:11434/api/version >/dev/null 2>&1 && break; sleep 1; done | |||||
| embed run >/dev/null | |||||
| check "embed run catches up" "3" "$(points "$TA" memory)" | |||||
| check "caught-up memory found by meaning" "$M4" "$(recall "$WK" "can I bring my puppy to work" | ids)" | |||||
| # ---- purge removes every point of the tenant --------------------------------------------------------------------- | |||||
| prov purge "$TB" >/dev/null; TENANTS=("$TA") | |||||
| check "purge removes tenant points" "0" "$(points "$TB")" | |||||
| echo "passed: $PASS failed: $FAIL" | |||||
| for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done | |||||
| [ "$FAIL" -eq 0 ] | |||||
Powered by TurnKey Linux.