Ranker_Class.ApplyFeedback scales each candidate's score by the tenant's ratings of its current revision (x1.1 per useful up to 5, x0.9 per not_useful up to 5, x0.5 per incorrect/harmful up to 3) and re-sorts. Recall and search results carry feedback counts; all three endpoints warn when results were demoted. A corrected memory starts without feedback. tests/phase3-learning.sh: 93 checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>pull/1/head
| @@ -36,7 +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). | |||
| - 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`. | |||
| - 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 `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. | |||
| - Semantic retrieval: `core/lib.Embeddings.asp` (Ollama client, Qdrant client, `embedding_index` bookkeeping, `Ranker_Class` used by recall/search/context; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). 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 `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items. | |||
| - Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.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 five suites (`tests/phase*.sh`). | |||
| @@ -58,7 +58,7 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec | |||
| - 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 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. The `embed-worker` container retries pending/failed items every 30 seconds; `GET /health/ready` reports `degraded` (still 200) and the backlog when the provider or vector store is down. | |||
| - Phase 3 (part): learning loop. Agents record experiences in a session (`POST /sessions/:id/events`) and propose knowledge with evidence (`POST /learn`: a new memory, or a new revision of `target_memory_id` at `base_revision`). Another principal with `verify` reviews it (`POST /candidates/:id/review`); the author cannot approve its own candidate without `admin`. Accepting creates the memory (an identical active one is reused), or revises the target if it has not changed meanwhile (else 409 `stale_candidate`), copies the evidence with pinned target revisions and, with `"verify": true`, records a verification. `GET /memories/:id/sources` shows evidence and verifications per revision (evidence the caller cannot read is shown as `available: false`, without its id). Recall, search and context return a `query_id` and record the returned results and revisions (the query text is kept only as a hash); `POST /feedback` rates one result (useful, not_useful, incorrect, harmful). Forgetting a memory removes its evidence, verifications, feedback and telemetry rows. | |||
| - Phase 3 (part): learning loop. Agents record experiences in a session (`POST /sessions/:id/events`) and propose knowledge with evidence (`POST /learn`: a new memory, or a new revision of `target_memory_id` at `base_revision`). Another principal with `verify` reviews it (`POST /candidates/:id/review`); the author cannot approve its own candidate without `admin`. Accepting creates the memory (an identical active one is reused), or revises the target if it has not changed meanwhile (else 409 `stale_candidate`), copies the evidence with pinned target revisions and, with `"verify": true`, records a verification. `GET /memories/:id/sources` shows evidence and verifications per revision (evidence the caller cannot read is shown as `available: false`, without its id). Recall, search and context return a `query_id` and record the returned results and revisions (the query text is kept only as a hash); `POST /feedback` rates one result (useful, not_useful, incorrect, harmful). Ratings on a result's current revision adjust its rank in recall, search and context (useful raises it, incorrect/harmful halve its score per rating); results show their `feedback` counts and a warning names demoted results. A corrected memory starts without feedback. Forgetting a memory removes its evidence, verifications, feedback and telemetry rows. | |||
| **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). | |||
| @@ -67,10 +67,10 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec | |||
| - `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\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` (79 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), `bash tests/phase3-learning.sh` (85). Each creates and purges its own tenants. | |||
| - Tests (containers must be running): `bash tests/phase1-api.sh` (79 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), `bash tests/phase3-learning.sh` (93). Each creates and purges its own tenants. | |||
| **Next (not started)** | |||
| 1. Use feedback in ranking (today it is recorded only), and consolidation of related experiences into candidates. | |||
| 1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`). | |||
| 2. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). | |||
| ## Configuration | |||
| @@ -36,7 +36,7 @@ Class ApiContextController_Class | |||
| Private m_errs | |||
| ' candidates, in rank order within each section | |||
| Private m_cSec(), m_cJson(), m_cTok(), m_cTel(), m_cN, m_spec | |||
| Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok, m_strategy, m_rankWarning | |||
| Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok, m_strategy, m_rankWarning, m_demoted | |||
| Public Property Get useLayout() | |||
| useLayout = False | |||
| @@ -206,6 +206,7 @@ Class ApiContextController_Class | |||
| m_seen = Chr(31) | |||
| m_strategy = "lexical" | |||
| m_rankWarning = "" | |||
| m_demoted = 0 | |||
| m_dupes = 0 | |||
| m_unverifiedExcluded = 0 | |||
| policiesCapped = False | |||
| @@ -421,6 +422,9 @@ Class ApiContextController_Class | |||
| If Len(allowed) = 0 Then | |||
| AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty" | |||
| End If | |||
| If m_demoted > 0 Then | |||
| AddWarning warnings, m_demoted & " matched item(s) ranked lower because of negative feedback on their current revision" | |||
| End If | |||
| If Len(m_rankWarning) > 0 Then | |||
| AddWarning warnings, m_rankWarning | |||
| End If | |||
| @@ -470,6 +474,7 @@ Class ApiContextController_Class | |||
| ' 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) | |||
| m_demoted = m_demoted + r.Demoted | |||
| If Len(r.Warning) > 0 Then | |||
| m_rankWarning = r.Warning | |||
| m_strategy = "lexical" | |||
| @@ -381,6 +381,9 @@ Class ApiDocumentsController_Class | |||
| For j = 0 To n - 1 | |||
| If ids(j) = "" & rs(0) Then | |||
| rowJson(j) = ChunkJson(rs, (detail = "snippet"), scores(j)) | |||
| If Len(ranker.FeedbackAt(j)) > 0 Then | |||
| rowJson(j) = Left(rowJson(j), Len(rowJson(j)) - 1) & ",""feedback"":" & ranker.FeedbackAt(j) & "}" | |||
| End If | |||
| revs(j) = CLng(rs(2)) | |||
| Exit For | |||
| End If | |||
| @@ -400,6 +403,12 @@ Class ApiDocumentsController_Class | |||
| Tel_AddResult spec, "chunk", ids(j), revs(j), -CDbl(scores(j)) | |||
| End If | |||
| Next | |||
| If ranker.Demoted > 0 Then | |||
| If Len(warnJson) > 0 Then | |||
| warnJson = warnJson & "," | |||
| End If | |||
| warnJson = warnJson & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback") | |||
| End If | |||
| Tel_Record qid, "search", ranker.Strategy, query, spec, t0 | |||
| Api_Audit "document.search", "search", "", "ok" | |||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}" | |||
| @@ -707,7 +707,11 @@ Class ApiMemoriesController_Class | |||
| If ids(j) = "" & rs(0) Then | |||
| v = MemoryJson(rs, (detail = "summary")) | |||
| If detail = "summary" Then v = SummaryOnly(v, rs) | |||
| rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j))) & "}" | |||
| rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j))) | |||
| If Len(ranker.FeedbackAt(j)) > 0 Then | |||
| rowJson(j) = rowJson(j) & ",""feedback"":" & ranker.FeedbackAt(j) | |||
| End If | |||
| rowJson(j) = rowJson(j) & "}" | |||
| revs(j) = CLng(rs(10)) | |||
| Exit For | |||
| End If | |||
| @@ -732,6 +736,12 @@ Class ApiMemoriesController_Class | |||
| End If | |||
| warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them""" | |||
| End If | |||
| If ranker.Demoted > 0 Then | |||
| If Len(warnings) > 0 Then | |||
| warnings = warnings & "," | |||
| End If | |||
| warnings = warnings & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback on their current revision") | |||
| End If | |||
| Tel_Record qid, "recall", ranker.Strategy, query, spec, t0 | |||
| Api_Audit "memory.recall", "search", "", "ok" | |||
| Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}" | |||
| @@ -379,9 +379,12 @@ End Sub | |||
| ' 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) | |||
| ' Feedback (POST /feedback) on the CURRENT revision of a result then scales its score: x(1 + 0.1 per useful, max 5), | |||
| ' x0.9 per not_useful (max 5), x0.5 per incorrect/harmful (max 3), and the list is re-sorted. | |||
| ' r.FeedbackAt(i) ("" or a JSON object of counts), r.Demoted (results with more negative than useful ratings) | |||
| '----------------------------------------------------------------------------------------------------------------------- | |||
| Class Ranker_Class | |||
| Private m_ids(), m_scores(), m_n, m_strategy, m_warning | |||
| Private m_ids(), m_scores(), m_n, m_strategy, m_warning, m_fb(), m_demoted | |||
| Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN | |||
| Private Sub Class_Initialize() | |||
| @@ -390,8 +393,18 @@ Class Ranker_Class | |||
| ReDim m_scores(0) | |||
| m_strategy = "lexical" | |||
| m_warning = "" | |||
| m_demoted = 0 | |||
| ReDim m_fb(0) | |||
| End Sub | |||
| Public Function FeedbackAt(i) | |||
| FeedbackAt = "" & m_fb(i) | |||
| End Function | |||
| Public Property Get Demoted() | |||
| Demoted = m_demoted | |||
| End Property | |||
| Public Property Get Count() | |||
| Count = m_n | |||
| End Property | |||
| @@ -462,8 +475,92 @@ Class Ranker_Class | |||
| m_scores(i) = m_lexScore(i) | |||
| Next | |||
| End If | |||
| ApplyFeedback kind, tenantId | |||
| End Sub | |||
| ' Usefulness feedback of the tenant on the current revision of each candidate (top 300) adjusts its score. | |||
| Private Sub ApplyFeedback(kind, tenantId) | |||
| Dim i, j, idList, lim, sql, rs, rows, u, nu, neg, f, t, ts, tf | |||
| ReDim m_fb(m_n) | |||
| If m_n = 0 Then | |||
| Exit Sub | |||
| End If | |||
| lim = m_n | |||
| If lim > 300 Then | |||
| lim = 300 | |||
| End If | |||
| idList = "" | |||
| For i = 0 To lim - 1 | |||
| If Api_IsId(m_ids(i)) Then | |||
| If Len(idList) > 0 Then | |||
| idList = idList & "," | |||
| End If | |||
| idList = idList & "'" & m_ids(i) & "'" | |||
| End If | |||
| Next | |||
| If Len(idList) = 0 Then | |||
| Exit Sub | |||
| End If | |||
| sql = "SELECT f.target_id, SUM(CASE WHEN f.usefulness = 'useful' THEN 1 ELSE 0 END), SUM(CASE WHEN f.usefulness = 'not_useful' THEN 1 ELSE 0 END), " & _ | |||
| "SUM(CASE WHEN f.usefulness IN ('incorrect','harmful') THEN 1 ELSE 0 END) FROM feedback f " | |||
| If kind = "memory" Then | |||
| sql = sql & "JOIN memories m ON m.id = f.target_id AND m.current_revision = f.target_revision " | |||
| End If | |||
| sql = sql & "WHERE f.tenant_id = ? AND f.target_kind = '" & kind & "' AND f.target_id IN (" & idList & ") GROUP BY f.target_id" | |||
| Set rs = DAL().Query(sql, tenantId) | |||
| rows = Empty | |||
| If Not rs.EOF Then | |||
| rows = rs.GetRows() | |||
| End If | |||
| rs.Close | |||
| If IsEmpty(rows) Then | |||
| Exit Sub | |||
| End If | |||
| For j = 0 To UBound(rows, 2) | |||
| u = CLng(rows(1, j)) | |||
| nu = CLng(rows(2, j)) | |||
| neg = CLng(rows(3, j)) | |||
| For i = 0 To lim - 1 | |||
| If m_ids(i) = "" & rows(0, j) Then | |||
| f = (1 + 0.1 * Min_(u, 5)) * (0.9 ^ Min_(nu, 5)) * (0.5 ^ Min_(neg, 3)) | |||
| m_scores(i) = m_scores(i) * f | |||
| m_fb(i) = "{""useful"":" & u & ",""not_useful"":" & nu & ",""incorrect_or_harmful"":" & neg & "}" | |||
| If neg > u Then | |||
| m_demoted = m_demoted + 1 | |||
| End If | |||
| Exit For | |||
| End If | |||
| Next | |||
| Next | |||
| ' re-sort (stable insertion sort, descending) | |||
| For i = 1 To m_n - 1 | |||
| t = m_ids(i) | |||
| ts = m_scores(i) | |||
| tf = m_fb(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) | |||
| m_fb(j + 1) = m_fb(j) | |||
| j = j - 1 | |||
| Loop | |||
| m_ids(j + 1) = t | |||
| m_scores(j + 1) = ts | |||
| m_fb(j + 1) = tf | |||
| Next | |||
| End Sub | |||
| Private Function Min_(a, b) | |||
| If a < b Then | |||
| Min_ = a | |||
| Else | |||
| Min_ = b | |||
| End If | |||
| End Function | |||
| ' 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 | |||
| @@ -2213,7 +2213,8 @@ | |||
| } | |||
| } | |||
| } | |||
| } | |||
| }, | |||
| "description": " Feedback (POST /feedback) on a result's current revision adjusts its rank; such results carry feedback {useful, not_useful, incorrect_or_harmful} and demoted results are named in warnings." | |||
| } | |||
| }, | |||
| "/ingestion/jobs": { | |||
| @@ -2567,7 +2568,8 @@ | |||
| } | |||
| } | |||
| } | |||
| } | |||
| }, | |||
| "description": " Feedback (POST /feedback) on a result's current revision adjusts its rank; such results carry feedback {useful, not_useful, incorrect_or_harmful} and demoted results are named in warnings." | |||
| } | |||
| }, | |||
| "/health/live": { | |||
| @@ -191,6 +191,24 @@ Q3=$(echo "$R" | jget query_id) | |||
| check "context returns query_id" "yes" "$([ "${Q3:0:4}" = "qry-" ] && echo yes || echo no)" | |||
| check "feedback on a context item -> 201" "201" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q3\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" | |||
| # ---- feedback adjusts ranking (current revision only) ------------------------------------------------------- | |||
| check "search shows chunk feedback" "1" "$(body "$RK" POST /search -d '{"query":"quillfeather daemon gentle"}' | jq_ "[r for r in d['results'] if r['chunk_id']=='$CH'][0]['feedback']['incorrect_or_harmful']")" | |||
| KA=$(remember "$WK" "$NS" semantic "Kestrel cache" "Kestrel cache holds 64 MB."); verify "$VK" "$KA" | |||
| KB=$(remember "$WK" "$NS" semantic "Kestrel cache" "Kestrel cache holds 128 MB."); verify "$VK" "$KB" | |||
| R=$(body "$RK" POST /recall -d "{\"query\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}") | |||
| QK=$(echo "$R" | jget query_id); TOP=$(echo "$R" | jq_ "d['results'][0]['id']"); OTHER=$(echo "$R" | jq_ "d['results'][1]['id']") | |||
| check "two kestrel results before feedback" "yes" "$([ -n "$TOP" ] && [ -n "$OTHER" ] && [ "$TOP" != "$OTHER" ] && echo yes || echo no)" | |||
| for k in "$RK" "$VK"; do code "$k" POST /feedback -d "{\"query_id\":\"$QK\",\"result_id\":\"$TOP\",\"usefulness\":\"incorrect\"}" >/dev/null; done | |||
| R=$(body "$RK" POST /recall -d "{\"query\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}") | |||
| check "negative feedback demotes the result" "$OTHER" "$(echo "$R" | jq_ "d['results'][0]['id']")" | |||
| check "demoted result carries feedback counts" "2" "$(echo "$R" | jq_ "[r for r in d['results'] if r['id']=='$TOP'][0]['feedback']['incorrect_or_harmful']")" | |||
| check "recall warns about demotion" "yes" "$(has 'negative feedback' "$R")" | |||
| check "context warns about demotion" "yes" "$(has 'negative feedback' "$(body "$RK" POST /context -d "{\"task\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}")")" | |||
| code "$WK" PATCH /memories/$TOP -H 'If-Match: 1' -d '{"content":"Kestrel cache holds 256 MB."}' >/dev/null; verify "$VK" "$TOP" 2 | |||
| R=$(body "$RK" POST /recall -d "{\"query\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}") | |||
| check "new revision starts without feedback" "None" "$(echo "$R" | jq_ "[r for r in d['results'] if r['id']=='$TOP'][0].get('feedback')")" | |||
| check "no demotion warning after correction" "no" "$(has 'negative feedback' "$R")" | |||
| # ---- forgetting removes linked data -------------------------------------------------------------------------- | |||
| C8=$(learn "$WK" "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Port clash v2\",\"content\":\"Prefer 7102.\",\"target_memory_id\":\"$MEM1\",\"base_revision\":1}" | jget id) | |||
| check "forget accepted memory -> 200" "200" "$(code "$AK" DELETE /memories/$MEM1)" | |||
Powered by TurnKey Linux.