From 138e4026ef89b4422485a37136036e36d7d172de Mon Sep 17 00:00:00 2001 From: Daniel Covington Date: Sat, 5 Dec 2026 06:55:57 -0500 Subject: [PATCH] Phase 3: learning loop (experiences, candidates and review, evidence, feedback) - ApiLearningController: POST/GET /sessions/:id/events, POST /learn, GET /candidates[/:id], POST /candidates/:id/review (verify permission, no self-approval without admin, stale revision proposals 409, duplicates reuse the memory), GET /memories/:id/sources (evidence the caller cannot read is shown without its id), POST /feedback. - core/lib.Learning.asp: evidence validation and pinning, shared memory writes, telemetry. Recall, search and context record the query_id they return and each result revision. - Migration for experiences, learning_candidates, evidence_links, retrieval_queries, retrieval_results and feedback; forget and provision purge remove the linked rows. - Readiness reports degraded plus the embedding backlog; embed-worker container retries pending items every 30 s. - tests/phase3-learning.sh (85 checks); OpenAPI, README and AGENTS.md updated. - scripts/kb.sh: use this repo's own knowledge base (keys in git-ignored .amk.env). Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + AGENTS.md | 19 +- README.md | 8 +- app/controllers/ApiContextController.asp | 40 +- app/controllers/ApiDocumentsController.asp | 17 +- app/controllers/ApiHealthController.asp | 50 +- app/controllers/ApiLearningController.asp | 946 +++++++ app/controllers/ApiMemoriesController.asp | 15 +- app/controllers/autoload_controllers.asp | 1 + core/autoload_core.asp | 1 + core/lib.ControllerRegistry.asp | 1 + core/lib.JsonLite.asp | 66 + core/lib.Learning.asp | 284 +++ ...37_create_learning_and_feedback_tables.asp | 120 + docker-compose.yml | 17 + public/Default.asp | 10 + public/api/memory-v1.openapi.json | 2241 +++++++++++++---- scripts/embed.asp | 24 +- scripts/kb.sh | 43 + scripts/provision.asp | 6 + tests/phase3-learning.sh | 204 ++ 21 files changed, 3591 insertions(+), 525 deletions(-) create mode 100644 app/controllers/ApiLearningController.asp create mode 100644 core/lib.Learning.asp create mode 100644 db/migrations/20261205113137_create_learning_and_feedback_tables.asp create mode 100644 scripts/kb.sh create mode 100644 tests/phase3-learning.sh diff --git a/.gitignore b/.gitignore index 483eca8..d864bfa 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,6 @@ # Notes for porting changes upstream (local only) /UPSTREAM-TODO.txt + +# Local knowledge base keys (scripts/kb.sh) +/.amk.env diff --git a/AGENTS.md b/AGENTS.md index 45a4125..7c23ff3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,8 +36,18 @@ 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 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. +- 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. +- 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`). + +### This repo's own knowledge base (dogfooding) + +The running API holds a tenant for this repo (`agent-memory-dev`, namespace `/projects/agent-memory`). Settings and keys are in `.amk.env` (git-ignored, local only; never print or commit the keys). Use `bash scripts/kb.sh` from Git Bash: + +- At the start of a task: `kb.sh context ""` (verified lessons/decisions plus passages from the ingested docs), or `kb.sh search ""` for a quick lookup before reading whole files. +- After learning something non-obvious (a new gotcha, a decision): `kb.sh learn lesson|decision|constraint "" "<content>"`. It stays a proposal until the owner reviews it (`kb.sh candidates`, `kb.sh review <id> accept|reject`); the agent key cannot approve its own proposals, and agents must not use `AMK_OWNER_KEY`. +- After editing AGENTS.md, README.md or the specification: `kb.sh ingest <file>` (re-ingesting replaces the previous revision). +- The tests never touch this tenant; `provision purge` on it deletes everything. ### Adding a table end to end (the workflow that was verified) @@ -159,7 +169,10 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o - **Response after the layout header:** the layout header is already in the buffer when an action runs, so `Response.Clear` before `Response.Redirect`, and for non-HTML actions set `useLayout` to False (the API controllers do). - **Static files under `public/`** (for example `public/api/*.openapi.json`) are served directly; the rewrite rule skips existing files and directories. Only routes in `public/Default.asp` go through the MVC dispatcher; a route needs the controller in `autoload_controllers.asp` **and** in `ControllerRegistry` (the generators do both). - **Swagger UI:** the multi-spec dropdown (`urls: [...]`) only works with `presets: [SwaggerUIBundle.presets.apis, SwaggerUIStandalonePreset]` and `layout: "StandaloneLayout"`. Without them the page says "No API definition provided". -- **Git Bash:** `curl` sends non-ASCII literals as cp1252, not UTF-8 (use `ΓΌ` escapes or a file with `--data-binary @file`); read CSRF tokens from the form with a cookie jar (`-c/-b`); strip `\r` from values printed by Python on Windows before putting them in URLs. +- **Git Bash:** `curl` sends non-ASCII literals as cp1252, not UTF-8 (use `\u00fc` escapes or a file with `--data-binary @file`); read CSRF tokens from the form with a cookie jar (`-c/-b`); strip `\r` from values printed by Python on Windows before putting them in URLs. Python on Windows also reads piped stdin as cp1252: tests that compare non-ASCII text must call `sys.stdin.reconfigure(encoding='utf-8')` (`python -I` ignores `PYTHONIOENCODING`). +- **No 405 from the router.** A known path with an unrouted method answers 404, like an unknown path. Tests assert 404 for now. +- **`Api_ToInt` clamps** to its range instead of rejecting, so use it for limits and paging only; validate values that must be rejected when out of range (for example `?revision=`) explicitly. +- **SQLite NOT NULL columns and the 8-parameter limit.** Every NOT NULL column without a default must be in the INSERT; when the parameters run out, inline server-generated values that cannot contain user input (for example `Api_Now()` timestamps) rather than moving them to the follow-up UPDATE. - **Include order matters for class methods.** A class method cannot see a global Function/Class defined in a file included *after* the class's file (`GetRouter()`, `Flash()` failed with "Object required" / "doesn't support this property or method"). `core/autoload_core.asp` therefore includes `mvc.asp` last. - **Dynamic Eval/Execute in classes is unreliable.** `Eval`/`Execute` inside a Class method cannot see global functions; with a runtime-built string they re-emit a method's inline HTML twice (second copy after the footer); `CallByName` is a silent no-op. Do not dispatch with them. - **Call sites bind to the first class.** `CurrentController.Invoke ...` in one place was bound to the first controller's `Invoke` and reused for every later controller (the first dispatched action's body appeared on every route; title/layout were right). Each controller therefore exposes a global `<Name>Controller_Invoke(actionName, args)` and the dispatcher calls it through `GetRef` (`MVC_InvokeAction`). New controllers must define `Invoke` and `<Name>Controller_Invoke` (the generators emit both). diff --git a/README.md b/README.md index fb44e0b..7803440 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,8 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec - 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 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. +- 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. **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). @@ -66,11 +67,12 @@ 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` (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. +- 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), `bash tests/phase3-learning.sh` (85). Each creates and purges its own tenants. **Next (not started)** -1. Experiences, candidates and review; feedback (AC-18). +1. Use feedback in ranking (today it is recorded only), and consolidation of related experiences into candidates. 2. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). +3. 405 for a known path with the wrong method (the router answers 404 today). ## Configuration diff --git a/app/controllers/ApiContextController.asp b/app/controllers/ApiContextController.asp index 9c281af..325aacd 100644 --- a/app/controllers/ApiContextController.asp +++ b/app/controllers/ApiContextController.asp @@ -35,7 +35,7 @@ Const CTX_MAX_POLICIES = 200 Class ApiContextController_Class Private m_errs ' candidates, in rank order within each section - Private m_cSec(), m_cJson(), m_cTok(), m_cN + 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 Public Property Get useLayout() @@ -58,8 +58,9 @@ Class ApiContextController_Class Dim rs, sql, now_, i, j, n, ids(), scores(), idList, sec, json, warnings, complete Dim stateJson, stateTok, sessNs, sessStatus, sessObjective, curRev, savedAt Dim used, requiredTok, policyCount, truncated, omittedBudget, omittedLimit, cap - Dim outSec(), cnt(), out, refSeen, txt, policiesCapped, ranker + Dim outSec(), cnt(), out, refSeen, txt, policiesCapped, ranker, qid, t0 + t0 = Timer If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub @@ -200,6 +201,8 @@ Class ApiContextController_Class ReDim m_cSec(31) ReDim m_cJson(31) ReDim m_cTok(31) + ReDim m_cTel(31) + m_spec = "" m_seen = Chr(31) m_strategy = "lexical" m_rankWarning = "" @@ -323,7 +326,7 @@ Class ApiContextController_Class Else refSeen = refSeen & txt & Chr(31) json = RefJson(chunkRows, j, detail, -CDbl(scores(i))) - AddCand CTX_REFERENCES, json, m_lastTok + AddCand CTX_REFERENCES, json, m_lastTok, "chunk|" & ids(i) & "|" & CLng(chunkRows(2, j)) & "|" & JsonLite_Num(-CDbl(scores(i))) cap = cap + 1 End If Exit For @@ -362,6 +365,7 @@ Class ApiContextController_Class For i = 0 To m_cN - 1 If m_cSec(i) = CTX_CONSTRAINTS Then AppendTo outSec, cnt, CTX_CONSTRAINTS, m_cJson(i) + AddTel i End If Next @@ -393,6 +397,7 @@ Class ApiContextController_Class Else used = used + m_cTok(i) AppendTo outSec, cnt, sec, m_cJson(i) + AddTel i End If End If Next @@ -420,7 +425,10 @@ Class ApiContextController_Class AddWarning warnings, m_rankWarning End If - out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""task"":" & JsonLite_Quote(task) & _ + ' Telemetry: the query id is returned so results can be rated with POST /feedback + qid = Tel_NewQueryId() + Tel_Record qid, "context", m_strategy, task, m_spec, t0 + out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""query_id"":" & JsonLite_Quote(qid) & ",""task"":" & JsonLite_Quote(task) & _ ",""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""" & _ ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _ @@ -520,7 +528,7 @@ Class ApiContextController_Class End If m_seen = m_seen & key & Chr(31) json = MemJson(rows, j, detail, score, st, (sec = CTX_CONSTRAINTS)) - AddCand target, json, m_lastTok + AddCand target, json, m_lastTok, "memory|" & rows(0, j) & "|" & CLng(rows(3, j)) & "|" & TelScore(score) End Sub Private Function MemJson(rows, j, detail, score, st, isPolicy) @@ -588,18 +596,38 @@ Class ApiContextController_Class RefJson = s End Function - Private Sub AddCand(sec, json, tok) + ' tel: "kind|id|revision|score" of the item, recorded for feedback if the item makes it into the briefing + Private Sub AddCand(sec, json, tok, tel) If m_cN > UBound(m_cSec) Then ReDim Preserve m_cSec(m_cN * 2) ReDim Preserve m_cJson(m_cN * 2) ReDim Preserve m_cTok(m_cN * 2) + ReDim Preserve m_cTel(m_cN * 2) End If m_cSec(m_cN) = sec m_cJson(m_cN) = json m_cTok(m_cN) = tok + m_cTel(m_cN) = tel m_cN = m_cN + 1 End Sub + Private Sub AddTel(i) + If Len(m_spec) > 0 Then + m_spec = m_spec & Chr(30) + End If + m_spec = m_spec & m_cTel(i) + End Sub + + ' Constraints and preferences are loaded by scope and have no similarity score + Private Function TelScore(score) + TelScore = "0" + If IsNumeric(score) Then + If Not IsEmpty(score) Then + TelScore = JsonLite_Num(score) + End If + End If + End Function + Private Sub AppendTo(outSec, cnt, sec, json) If cnt(sec) > 0 Then outSec(sec) = outSec(sec) & "," diff --git a/app/controllers/ApiDocumentsController.asp b/app/controllers/ApiDocumentsController.asp index 95eb36c..0e43c9c 100644 --- a/app/controllers/ApiDocumentsController.asp +++ b/app/controllers/ApiDocumentsController.asp @@ -300,8 +300,9 @@ Class ApiDocumentsController_Class '--------------------------------------------------------------- Public Sub Search() 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, ranker, warnJson + Dim requested, arr, ok, wanted, warn, ranker, warnJson, revs(), qid, spec, t0 + t0 = Timer If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub @@ -336,8 +337,11 @@ Class ApiDocumentsController_Class allowed = Api_AllowedNamespaceIds("read") If Len(allowed) > 0 And Len(requested) > 0 Then allowed = Intersect(allowed, requested) + qid = Tel_NewQueryId() + spec = "" If Len(allowed) = 0 Then - Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}" + Tel_Record qid, "search", "lexical", query, spec, t0 + Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}" Exit Sub End If @@ -351,7 +355,8 @@ Class ApiDocumentsController_Class warnJson = JsonLite_Quote(ranker.Warning) End If If n = 0 Then - Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[" & warnJson & "]}" + Tel_Record qid, "search", ranker.Strategy, query, spec, t0 + Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[" & warnJson & "]}" Exit Sub End If ReDim ids(n - 1) @@ -371,10 +376,12 @@ Class ApiDocumentsController_Class sql = ChunkSelect() & " WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") AND c.document_revision = d.current_revision" Set rs = DAL().Query(sql, Api_TenantId) ReDim rowJson(n - 1) + ReDim revs(n - 1) Do While Not rs.EOF For j = 0 To n - 1 If ids(j) = "" & rs(0) Then rowJson(j) = ChunkJson(rs, (detail = "snippet"), scores(j)) + revs(j) = CLng(rs(2)) Exit For End If Next @@ -390,10 +397,12 @@ Class ApiDocumentsController_Class If count > 0 Then out = out & "," out = out & rowJson(j) count = count + 1 + Tel_AddResult spec, "chunk", ids(j), revs(j), -CDbl(scores(j)) End If Next + Tel_Record qid, "search", ranker.Strategy, query, spec, t0 Api_Audit "document.search", "search", "", "ok" - Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}" + Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}" End Sub '=============================================================== diff --git a/app/controllers/ApiHealthController.asp b/app/controllers/ApiHealthController.asp index 777f70f..09f3996 100644 --- a/app/controllers/ApiHealthController.asp +++ b/app/controllers/ApiHealthController.asp @@ -2,7 +2,8 @@ ' ApiHealthController: liveness and readiness probes (spec 9, health). No authentication, no tenant data. ' ' GET /api/v1/health/live Live 200 while the process answers -' GET /api/v1/health/ready Ready 200 when the database answers, else 503 +' GET /api/v1/health/ready Ready 200 when the database answers (status ready, or degraded when the embedding +' provider / vector store is unreachable), else 503 Class ApiHealthController_Class Public Property Get useLayout() useLayout = False @@ -19,9 +20,13 @@ Class ApiHealthController_Class Api_Send 200, "{""status"":""live""}" End Sub + ' 503 only when the database is down. Semantic retrieval is optional (lexical keeps working), so an unreachable + ' embedding provider or vector store gives 200 with status "degraded". Counts only, no tenant data. Public Sub Ready() - Dim rs, ok + Dim rs, ok, emb, store, pending, failed, status, resp, st ok = False + pending = 0 + failed = 0 On Error Resume Next Set rs = DAL().Query("SELECT 1", Empty) If Err.Number = 0 Then @@ -29,12 +34,47 @@ Class ApiHealthController_Class rs.Close End If Err.Clear - On Error GoTo 0 If ok Then - Api_Send 200, "{""status"":""ready""}" + Set rs = DAL().Query("SELECT SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END), SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) FROM embedding_index", Empty) + If Err.Number = 0 Then + If Not rs.EOF Then + If Not IsNull(rs(0)) Then + pending = CLng(rs(0)) + failed = CLng(rs(1)) + End If + End If + rs.Close + End If + Err.Clear + End If + On Error GoTo 0 + If Not ok Then + Api_Send 503, "{""status"":""unavailable"",""checks"":{""database"":""down""}}" + Exit Sub + End If + + status = "ready" + If Emb_Enabled() Then + resp = Emb_Http("GET", Emb_Setting("EmbeddingUrl", "http://ollama:11434") & "/api/version", "", st) + If st = 200 Then + emb = "up" + Else + emb = "down" + status = "degraded" + End If + resp = Emb_Http("GET", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/readyz", "", st) + If st = 200 Then + store = "up" + Else + store = "down" + status = "degraded" + End If Else - Api_Send 503, "{""status"":""unavailable""}" + emb = "disabled" + store = "disabled" End If + Api_Send 200, "{""status"":""" & status & """,""checks"":{""database"":""up"",""embeddings"":""" & emb & """,""vector_store"":""" & store & """}" & _ + ",""embedding_backlog"":{""pending"":" & pending & ",""failed"":" & failed & "}}" End Sub ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) diff --git a/app/controllers/ApiLearningController.asp b/app/controllers/ApiLearningController.asp new file mode 100644 index 0000000..b7da420 --- /dev/null +++ b/app/controllers/ApiLearningController.asp @@ -0,0 +1,946 @@ +<% +' ApiLearningController: experiences, learning candidates and review, evidence, feedback (spec FR-012, FR-013, +' FR-014, FR-020, section 12, AC-08, AC-16, AC-18). Stateless JSON API, no layout. +' Helpers: core/lib.Api.asp (auth, errors), core/lib.Learning.asp (evidence, memory writes, telemetry). +' +' POST /api/v1/sessions/:id/events RecordEvent {"task","outcome":"success|failure|partial|unknown","problem","action","result","environment":{}} +' GET /api/v1/sessions/:id/events Events experiences of the session, oldest first +' POST /api/v1/learn Learn {"namespace_id","type","title","content","summary","tags","confidence", +' "target_memory_id","base_revision","evidence":[{"kind","id","role","excerpt"}]} +' GET /api/v1/candidates Candidates ?namespace_id= &state=proposed|accepted|rejected &limit= +' GET /api/v1/candidates/:id Candidate with its evidence +' POST /api/v1/candidates/:id/review Review {"decision":"accept|reject","notes","verify":true|false} +' GET /api/v1/memories/:id/sources Sources evidence and verifications of a revision (?revision=, default current) +' POST /api/v1/feedback Feedback {"query_id","result_id","usefulness":"useful|not_useful|incorrect|harmful","comment"} +' +' Permissions on the namespace: write (RecordEvent, Learn), read (Events, Candidates, Candidate, Sources, Feedback), +' verify (Review). Reviewing your own candidate needs admin: a proposer cannot approve itself. Accepting creates a +' memory (or a new revision of target_memory_id, if it is still at base_revision) with the candidate's evidence; it +' stays unverified unless "verify": true, which records a verification by the reviewer. Without permission: 404. +Class ApiLearningController_Class + Private m_errs + + Public Property Get useLayout() + useLayout = False + End Property + + Public Property Let useLayout(v) + End Property + + Public Property Get Title() + Title = "Learning API" + End Property + + '--------------------------------------------------------------- + ' POST /api/v1/sessions/:id/events + '--------------------------------------------------------------- + Public Sub RecordEvent(id) + Dim body, input, idemKey, reqHash, rs, nsId, status, task, outcome, problem, action, result, envRaw, expId, ts, resp, k + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + idemKey = Api_Header("Idempotency-Key") + If Len(idemKey) > 200 Then + Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." + Exit Sub + End If + reqHash = Api_Sha256("events|" & id & "|" & body) + If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub + + Set rs = DAL().Query("SELECT namespace_id, status FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_Error 404, "session_not_found", "Session not found." + Exit Sub + End If + nsId = "" & rs(0) + status = "" & rs(1) + rs.Close + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_Error 404, "session_not_found", "Session not found." + Exit Sub + End If + + m_errs = "" + task = ReqString(input, "task", 2000) + outcome = LCase("" & ReqString(input, "outcome", 20)) + problem = OptString(input, "problem", 4000) + action = OptString(input, "action", 4000) + result = OptString(input, "result", 4000) + envRaw = ObjectJson(input, "environment") + If Len(m_errs) = 0 Then + If outcome <> "success" And outcome <> "failure" And outcome <> "partial" And outcome <> "unknown" Then + AddErr "outcome must be success, failure, partial or unknown." + End If + End If + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + If status <> "active" Then + Api_Error 409, "session_not_active", "The session is " & status & "; experiences can only be recorded in an active session." + Exit Sub + End If + + expId = Api_NewId() + ts = Api_Now() + resp = "{""id"":" & JsonLite_Quote(expId) & ",""session_id"":" & JsonLite_Quote(id) & ",""outcome"":" & JsonLite_Quote(outcome) & ",""created_at"":" & JsonLite_Quote(ts) & "}" + On Error Resume Next + DAL().BeginTransaction + DAL().Execute "INSERT INTO experiences (id, tenant_id, namespace_id, session_id, principal_id, task, outcome, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ + Array(expId, Api_TenantId, nsId, id, Api_PrincipalId, task, outcome, ts) + DAL().Execute "UPDATE experiences SET problem = ?, action = ?, result = ?, environment = ? WHERE id = ?", Array(problem, action, result, envRaw, expId) + Api_IdempotencyStore idemKey, reqHash, 201, resp + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + On Error GoTo 0 + + Api_Audit "session.event", "experience", expId, "ok" + Api_Send 201, resp + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/sessions/:id/events + '--------------------------------------------------------------- + Public Sub Events(id) + Dim rs, nsId, out, n + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + Set rs = DAL().Query("SELECT namespace_id FROM sessions WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_Error 404, "session_not_found", "Session not found." + Exit Sub + End If + nsId = "" & rs(0) + rs.Close + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_Error 404, "session_not_found", "Session not found." + Exit Sub + End If + + Set rs = DAL().Query("SELECT id, task, problem, action, result, outcome, environment, principal_id, created_at FROM experiences " & _ + "WHERE session_id = ? AND tenant_id = ? ORDER BY created_at, id LIMIT 200", Array(id, Api_TenantId)) + out = "" + n = 0 + Do While Not rs.EOF + If n > 0 Then + out = out & "," + End If + out = out & "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""task"":" & JsonLite_Quote("" & rs(1)) & ",""problem"":" & JStr(rs(2)) & _ + ",""action"":" & JStr(rs(3)) & ",""result"":" & JStr(rs(4)) & ",""outcome"":" & JsonLite_Quote("" & rs(5)) & _ + ",""environment"":" & JRaw(rs(6), "null") & ",""recorded_by"":" & JsonLite_Quote("" & rs(7)) & ",""created_at"":" & JsonLite_Quote("" & rs(8)) & "}" + n = n + 1 + rs.MoveNext + Loop + rs.Close + Api_Send 200, "{""session_id"":" & JsonLite_Quote(id) & ",""data"":[" & out & "]}" + End Sub + + '--------------------------------------------------------------- + ' POST /api/v1/learn + '--------------------------------------------------------------- + Public Sub Learn() + Dim body, input, idemKey, reqHash, nsId, memType, title, content, summary, tagsRaw, confidence, targetId, baseRev + Dim ev, msg, rs, candId, ts, resp, k + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + idemKey = Api_Header("Idempotency-Key") + If Len(idemKey) > 200 Then + Api_Error 400, "invalid_idempotency_key", "Idempotency-Key must be at most 200 characters." + Exit Sub + End If + reqHash = Api_Sha256("learn|" & body) + If Not Api_IdempotencyGate(idemKey, reqHash) Then Exit Sub + + m_errs = "" + nsId = ReqString(input, "namespace_id", 64) + memType = LCase("" & ReqString(input, "type", 40)) + title = ReqString(input, "title", 200) + content = ReqString(input, "content", 100000) + summary = OptString(input, "summary", 2000) + tagsRaw = TagsJson(input) + confidence = OptUnit(input, "confidence") + targetId = OptString(input, "target_memory_id", 64) + baseRev = Null + If Not IsNull(targetId) Then + If Not Api_IsId(targetId) Then + AddErr "target_memory_id must be a valid id." + End If + If Not input.Exists("base_revision") Then + AddErr "base_revision is required with target_memory_id." + ElseIf VarType(input.Item("base_revision")) <> vbDouble Then + AddErr "base_revision must be a number." + Else + baseRev = CLng(input.Item("base_revision")) + End If + End If + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + If Not Api_CanAccessNamespace(nsId, "write") Then + Api_Audit "candidate.learn", "namespace", nsId, "denied" + Api_Error 404, "namespace_not_found", "Namespace not found." + Exit Sub + End If + Set rs = DAL().Query("SELECT 1 FROM memory_types WHERE code = ?", memType) + If rs.EOF Then + rs.Close + Api_Invalid Array("type '" & memType & "' is not a known memory type.") + Exit Sub + End If + rs.Close + If Not IsNull(targetId) Then + ' A revision proposal must target a memory of the same namespace and type that the caller can read. + Set rs = DAL().Query("SELECT 1 FROM memories WHERE id = ? AND tenant_id = ? AND namespace_id = ? AND type = ?", Array(targetId, Api_TenantId, nsId, memType)) + If rs.EOF Then + rs.Close + Api_Invalid Array("target_memory_id was not found in this namespace with this type.") + Exit Sub + End If + rs.Close + End If + Set ev = New Evidence_Class + msg = ev.Load(input, "evidence") + If Len(msg) > 0 Then + Api_Invalid Array(msg) + Exit Sub + End If + + candId = Api_NewId() + ts = Api_Now() + resp = "{""id"":" & JsonLite_Quote(candId) & ",""state"":""proposed"",""namespace_id"":" & JsonLite_Quote(nsId) & ",""type"":" & JsonLite_Quote(memType) & _ + ",""evidence_count"":" & ev.Count & "}" + On Error Resume Next + DAL().BeginTransaction + DAL().Execute "INSERT INTO learning_candidates (id, tenant_id, namespace_id, type, title, content, author_principal_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ + Array(candId, Api_TenantId, nsId, memType, title, content, Api_PrincipalId, ts) + DAL().Execute "UPDATE learning_candidates SET summary = ?, tags = ?, confidence = ?, target_memory_id = ?, base_revision = ? WHERE id = ?", _ + Array(summary, tagsRaw, confidence, targetId, baseRev, candId) + ev.Save "candidate", candId, Null + Api_IdempotencyStore idemKey, reqHash, 201, resp + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + On Error GoTo 0 + + Api_Audit "candidate.learn", "candidate", candId, "ok" + Response.AddHeader "Location", "/api/v1/candidates/" & candId + Api_Send 201, resp + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/candidates + '--------------------------------------------------------------- + Public Sub Candidates() + Dim allowed, nsFilter, state, limit, sql, rs, out, n + + If Not Api_Authenticate() Then Exit Sub + nsFilter = Trim("" & Request.QueryString("namespace_id")) + state = LCase(Trim("" & Request.QueryString("state"))) + limit = Api_ToInt(Request.QueryString("limit"), 50, 1, 200) + If Len(state) > 0 Then + If state <> "proposed" And state <> "accepted" And state <> "rejected" Then + Api_Invalid Array("state must be proposed, accepted or rejected.") + Exit Sub + End If + End If + If Len(nsFilter) > 0 Then + If Not Api_IsId(nsFilter) Then + Api_Invalid Array("namespace_id must be a valid id.") + Exit Sub + End If + End If + allowed = Api_AllowedNamespaceIds("read") + out = "" + n = 0 + If Len(allowed) > 0 Then + sql = CandidateSelect() & " WHERE tenant_id = ? AND namespace_id IN (" & allowed & ")" + If Len(nsFilter) > 0 Then + sql = sql & " AND namespace_id = '" & nsFilter & "'" + End If + If Len(state) > 0 Then + sql = sql & " AND state = '" & state & "'" + End If + Set rs = DAL().Query(sql & " ORDER BY created_at DESC, id LIMIT " & limit, Api_TenantId) + Do While Not rs.EOF + If n > 0 Then + out = out & "," + End If + out = out & CandidateJson(rs, True) + n = n + 1 + rs.MoveNext + Loop + rs.Close + End If + Api_Send 200, "{""data"":[" & out & "]}" + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/candidates/:id + '--------------------------------------------------------------- + Public Sub Candidate(id) + Dim rs, json, nsId + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + Set rs = DAL().Query(CandidateSelect() & " WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(1) + json = CandidateJson(rs, False) + rs.Close + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_NotFound + Exit Sub + End If + json = Left(json, Len(json) - 1) & ",""evidence"":" & EvidenceJson("candidate", id, Null) & "}" + Api_Send 200, "{""data"":" & json & "}" + End Sub + + '--------------------------------------------------------------- + ' POST /api/v1/candidates/:id/review + '--------------------------------------------------------------- + Public Sub Review(id) + Dim body, input, rs, nsId, state, author, memType, title, summary, content, tagsRaw, confidence, targetId, baseRev + Dim decision, notes, doVerify, ts, k, memId, rev, dup, tNs, tType, tRev, tStatus, verStatus, hash + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + Set rs = DAL().Query("SELECT namespace_id, state, author_principal_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision " & _ + "FROM learning_candidates WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(0) + state = "" & rs(1) + author = "" & rs(2) + memType = "" & rs(3) + title = "" & rs(4) + summary = rs(5) + content = "" & rs(6) + tagsRaw = rs(7) + confidence = rs(8) + targetId = rs(9) + baseRev = rs(10) + rs.Close + If Not Api_CanAccessNamespace(nsId, "verify") Then + Api_Audit "candidate.review", "candidate", id, "denied" + Api_NotFound + Exit Sub + End If + + m_errs = "" + decision = LCase("" & ReqString(input, "decision", 20)) + notes = OptString(input, "notes", 2000) + doVerify = False + If input.Exists("verify") Then + If VarType(input.Item("verify")) = vbBoolean Then + doVerify = input.Item("verify") + ElseIf Not IsNull(input.Item("verify")) Then + AddErr "verify must be true or false." + End If + End If + If Len(m_errs) = 0 Then + If decision <> "accept" And decision <> "reject" Then + AddErr "decision must be accept or reject." + End If + End If + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + If state <> "proposed" Then + Api_Error 409, "candidate_already_reviewed", "The candidate was already " & state & "." + Exit Sub + End If + If author = Api_PrincipalId Then + If Not Api_CanAccessNamespace(nsId, "admin") Then + Api_Audit "candidate.review", "candidate", id, "self_review_denied" + Api_Error 403, "self_review_not_allowed", "A candidate cannot be reviewed by its author without admin permission on the namespace." + Exit Sub + End If + End If + + ts = Api_Now() + If decision = "reject" Then + On Error Resume Next + DAL().Execute "UPDATE learning_candidates SET state = 'rejected', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ? WHERE id = ? AND state = 'proposed'", _ + Array(Api_PrincipalId, notes, ts, id) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + Api_Audit "candidate.review", "candidate", id, "rejected" + Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""rejected""}" + Exit Sub + End If + + ' accept: check the target (revision proposals) or look for an identical active memory (new memories) + dup = False + memId = "" + rev = 0 + If Not IsNull(targetId) Then + Set rs = DAL().Query("SELECT namespace_id, type, current_revision, lifecycle_status FROM memories WHERE id = ? AND tenant_id = ?", Array("" & targetId, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_Error 409, "target_memory_missing", "The memory this candidate revises no longer exists." + Exit Sub + End If + tNs = "" & rs(0) + tType = "" & rs(1) + tRev = CLng(rs(2)) + tStatus = "" & rs(3) + rs.Close + If tStatus <> "active" Then + Api_Error 409, "target_memory_not_active", "The memory this candidate revises is " & tStatus & "." + Exit Sub + End If + If tRev <> CLng(baseRev) Then + Api_Error 409, "stale_candidate", "The memory changed since the candidate was proposed (base revision " & baseRev & ", current " & tRev & ")." + Exit Sub + End If + Else + hash = Mem_Hash(nsId, memType, title, content) + Set rs = DAL().Query("SELECT m.id, m.current_revision FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision " & _ + "WHERE m.tenant_id = ? AND m.namespace_id = ? AND m.type = ? AND m.lifecycle_status = 'active' AND r.content_hash = ?", Array(Api_TenantId, nsId, memType, hash)) + If Not rs.EOF Then + dup = True + memId = "" & rs(0) + rev = CLng(rs(1)) + End If + rs.Close + End If + + On Error Resume Next + DAL().BeginTransaction + If Not IsNull(targetId) Then + memId = "" & targetId + rev = Mem_Revise(memId, nsId, memType, tRev, title, summary, content, tagsRaw, confidence, "accepted candidate " & id) + ElseIf Not dup Then + memId = Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, "accepted candidate " & id) + rev = 1 + End If + Evidence_CopyCandidate id, memId, rev + If doVerify Then + Mem_Verify memId, rev, "candidate_review", notes + End If + DAL().Execute "UPDATE learning_candidates SET state = 'accepted', reviewer_principal_id = ?, review_notes = ?, reviewed_at = ?, resulting_memory_id = ?, resulting_revision = ? " & _ + "WHERE id = ? AND state = 'proposed'", Array(Api_PrincipalId, notes, ts, memId, rev, id) + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + DAL().RollbackTransaction + Api_DbFailed k, "" + Exit Sub + End If + DAL().CommitTransaction + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + Set rs = DAL().Query("SELECT verification_status FROM memory_revisions WHERE memory_id = ? AND revision = ?", Array(memId, rev)) + verStatus = "unverified" + If Not rs.EOF Then + verStatus = "" & rs(0) + End If + rs.Close + Emb_AfterWrite Api_TenantId, 8 + Api_Audit "candidate.review", "candidate", id, "accepted" + Api_Send 200, "{""id"":" & JsonLite_Quote(id) & ",""state"":""accepted"",""resulting_memory_id"":" & JsonLite_Quote(memId) & _ + ",""resulting_revision"":" & rev & ",""verification_status"":" & JsonLite_Quote(verStatus) & ",""duplicate"":" & LCase(CStr(dup)) & "}" + End Sub + + '--------------------------------------------------------------- + ' GET /api/v1/memories/:id/sources + '--------------------------------------------------------------- + Public Sub Sources(id) + Dim rs, nsId, curRev, rev, q, ver, n, cand + + If Not Api_Authenticate() Then Exit Sub + If Not Api_IsId(id) Then + Api_NotFound + Exit Sub + End If + Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_NotFound + Exit Sub + End If + nsId = "" & rs(0) + curRev = CLng(rs(1)) + rs.Close + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_NotFound + Exit Sub + End If + rev = curRev + q = Trim("" & Request.QueryString("revision")) + If Len(q) > 0 Then + ' Api_ToInt clamps, so check the range on the raw value + rev = -1 + If Len(q) <= 9 Then + If IsNumeric(q) Then + If InStr(q, ".") = 0 Then + rev = CLng(q) + End If + End If + End If + If rev < 1 Or rev > curRev Then + Api_Invalid Array("revision must be a whole number between 1 and " & curRev & ".") + Exit Sub + End If + End If + + Set rs = DAL().Query("SELECT method, result, notes, reviewer_principal_id, created_at FROM verifications WHERE memory_id = ? AND revision = ? ORDER BY created_at", Array(id, rev)) + ver = "" + n = 0 + Do While Not rs.EOF + If n > 0 Then + ver = ver & "," + End If + ver = ver & "{""method"":" & JsonLite_Quote("" & rs(0)) & ",""result"":" & JsonLite_Quote("" & rs(1)) & ",""notes"":" & JStr(rs(2)) & _ + ",""reviewer"":" & JsonLite_Quote("" & rs(3)) & ",""created_at"":" & JsonLite_Quote("" & rs(4)) & "}" + n = n + 1 + rs.MoveNext + Loop + rs.Close + Set rs = DAL().Query("SELECT id FROM learning_candidates WHERE resulting_memory_id = ? AND resulting_revision = ? AND tenant_id = ?", Array(id, rev, Api_TenantId)) + cand = "null" + If Not rs.EOF Then + cand = JsonLite_Quote("" & rs(0)) + End If + rs.Close + Api_Send 200, "{""memory_id"":" & JsonLite_Quote(id) & ",""revision"":" & rev & ",""current_revision"":" & curRev & _ + ",""from_candidate"":" & cand & ",""evidence"":" & EvidenceJson("memory", id, rev) & ",""verifications"":[" & ver & "]}" + End Sub + + '--------------------------------------------------------------- + ' POST /api/v1/feedback + '--------------------------------------------------------------- + Public Sub Feedback() + Dim body, input, queryId, resultId, usefulness, comment, rs, kind, rev, nsId, ts, fbId, k, existing + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + m_errs = "" + queryId = ReqString(input, "query_id", 80) + resultId = ReqString(input, "result_id", 64) + usefulness = LCase("" & ReqString(input, "usefulness", 20)) + comment = OptString(input, "comment", 2000) + If Len(m_errs) = 0 Then + If usefulness <> "useful" And usefulness <> "not_useful" And usefulness <> "incorrect" And usefulness <> "harmful" Then + AddErr "usefulness must be useful, not_useful, incorrect or harmful." + End If + If Left(queryId, 4) <> "qry-" Or Not Api_IsId(Mid(queryId, 5)) Then + AddErr "query_id must be a query id returned by recall, search or context." + End If + If Not Api_IsId(resultId) Then + AddErr "result_id must be a valid id." + End If + End If + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + + ' The result must belong to that query, in this tenant, and still be readable by the caller. + Set rs = DAL().Query("SELECT r.target_kind, r.target_revision FROM retrieval_results r JOIN retrieval_queries q ON q.id = r.query_id " & _ + "WHERE r.query_id = ? AND r.target_id = ? AND q.tenant_id = ?", Array(queryId, resultId, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_Error 404, "result_not_found", "That result was not returned by that query." + Exit Sub + End If + kind = "" & rs(0) + rev = CLng(rs(1)) + rs.Close + nsId = "" + If kind = "memory" Then + Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(resultId, Api_TenantId)) + Else + Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(resultId, Api_TenantId)) + End If + If Not rs.EOF Then + nsId = "" & rs(0) + End If + rs.Close + If Len(nsId) = 0 Then + Api_Error 404, "result_not_found", "That result was not returned by that query." + Exit Sub + End If + If Not Api_CanAccessNamespace(nsId, "read") Then + Api_Error 404, "result_not_found", "That result was not returned by that query." + Exit Sub + End If + + ' One rating per principal, query and result; a new submission replaces the earlier one. + Set rs = DAL().Query("SELECT id FROM feedback WHERE query_id = ? AND target_kind = ? AND target_id = ? AND principal_id = ?", Array(queryId, kind, resultId, Api_PrincipalId)) + existing = "" + If Not rs.EOF Then + existing = "" & rs(0) + End If + rs.Close + ts = Api_Now() + On Error Resume Next + If Len(existing) > 0 Then + fbId = existing + DAL().Execute "UPDATE feedback SET usefulness = ?, comment = ?, updated_at = ? WHERE id = ?", Array(usefulness, comment, ts, fbId) + Else + fbId = Api_NewId() + ' 8-parameter limit: the server-generated timestamp is inlined (ISO text from Api_Now, no user input) + DAL().Execute "INSERT INTO feedback (id, tenant_id, query_id, target_kind, target_id, target_revision, principal_id, usefulness, created_at, updated_at) " & _ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '" & ts & "', '" & ts & "')", Array(fbId, Api_TenantId, queryId, kind, resultId, rev, Api_PrincipalId, usefulness) + DAL().Execute "UPDATE feedback SET comment = ? WHERE id = ?", Array(comment, fbId) + End If + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + Api_Audit "retrieval.feedback", kind, resultId, usefulness + If Len(existing) > 0 Then + Api_Send 200, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness) + Else + Api_Send 201, FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness) + End If + End Sub + + '=============================================================== + ' Helpers + '=============================================================== + Private Function FeedbackJson(fbId, queryId, kind, resultId, rev, usefulness) + FeedbackJson = "{""id"":" & JsonLite_Quote(fbId) & ",""query_id"":" & JsonLite_Quote(queryId) & ",""target_kind"":" & JsonLite_Quote(kind) & _ + ",""target_id"":" & JsonLite_Quote(resultId) & ",""target_revision"":" & rev & ",""usefulness"":" & JsonLite_Quote(usefulness) & "}" + End Function + + ' Columns: 0 id, 1 namespace_id, 2 type, 3 title, 4 summary, 5 content, 6 tags, 7 confidence, 8 target_memory_id, 9 base_revision, + ' 10 state, 11 author, 12 reviewer, 13 review_notes, 14 resulting_memory_id, 15 resulting_revision, 16 created_at, 17 reviewed_at + Private Function CandidateSelect() + CandidateSelect = "SELECT id, namespace_id, type, title, summary, content, tags, confidence, target_memory_id, base_revision, state, " & _ + "author_principal_id, reviewer_principal_id, review_notes, resulting_memory_id, resulting_revision, created_at, reviewed_at FROM learning_candidates" + End Function + + Private Function CandidateJson(rs, brief) + Dim s + s = "{""id"":" & JsonLite_Quote("" & rs(0)) & ",""namespace_id"":" & JsonLite_Quote("" & rs(1)) & ",""type"":" & JsonLite_Quote("" & rs(2)) & _ + ",""title"":" & JsonLite_Quote("" & rs(3)) & ",""summary"":" & JStr(rs(4)) + If Not brief Then + s = s & ",""content"":" & JsonLite_Quote("" & rs(5)) + End If + s = s & ",""tags"":" & JRaw(rs(6), "[]") & ",""confidence"":" & JNum(rs(7)) & ",""target_memory_id"":" & JStr(rs(8)) & ",""base_revision"":" & JNum(rs(9)) & _ + ",""state"":" & JsonLite_Quote("" & rs(10)) & ",""author"":" & JsonLite_Quote("" & rs(11)) & ",""reviewer"":" & JStr(rs(12)) & _ + ",""review_notes"":" & JStr(rs(13)) & ",""resulting_memory_id"":" & JStr(rs(14)) & ",""resulting_revision"":" & JNum(rs(15)) & _ + ",""created_at"":" & JsonLite_Quote("" & rs(16)) & ",""reviewed_at"":" & JStr(rs(17)) & ",""content_trust"":""proposed_knowledge""}" + CandidateJson = s + End Function + + ' Evidence of an owner as a JSON array. A target the caller cannot read (or that is gone) is shown without its id. + Private Function EvidenceJson(ownerKind, ownerId, ownerRev) + Dim rs, rows, i, out, kind, tid, ns, avail, r2 + If IsNull(ownerRev) Then + Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND tenant_id = ? ORDER BY created_at, id", _ + Array(ownerKind, ownerId, Api_TenantId)) + Else + Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt, created_at FROM evidence_links WHERE owner_kind = ? AND owner_id = ? AND owner_revision = ? AND tenant_id = ? ORDER BY created_at, id", _ + Array(ownerKind, ownerId, CLng(ownerRev), Api_TenantId)) + End If + rows = Empty + If Not rs.EOF Then + rows = rs.GetRows() + End If + rs.Close + out = "" + If Not IsEmpty(rows) Then + For i = 0 To UBound(rows, 2) + kind = "" & rows(0, i) + tid = "" & rows(1, i) + ns = TargetNamespace(kind, tid) + avail = False + If Len(ns) > 0 Then + avail = Api_CanAccessNamespace(ns, "read") + End If + If i > 0 Then + out = out & "," + End If + out = out & "{""kind"":" & JsonLite_Quote(kind) + If avail Then + out = out & ",""id"":" & JsonLite_Quote(tid) & ",""revision"":" & JNum(rows(2, i)) + End If + out = out & ",""available"":" & LCase(CStr(avail)) & ",""role"":" & JsonLite_Quote("" & rows(3, i)) + If avail Then + out = out & ",""excerpt"":" & JStr(rows(4, i)) + End If + out = out & ",""content_trust"":""" + If kind = "chunk" Or kind = "document" Then + out = out & "untrusted_reference" + Else + out = out & "evidence" + End If + out = out & """}" + Next + End If + EvidenceJson = "[" & out & "]" + End Function + + Private Function TargetNamespace(kind, tid) + Dim rs + TargetNamespace = "" + Select Case kind + Case "experience" + Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId)) + Case "chunk" + Set rs = DAL().Query("SELECT d.namespace_id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(tid, Api_TenantId)) + Case "memory" + Set rs = DAL().Query("SELECT namespace_id FROM memories WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId)) + Case Else + Set rs = DAL().Query("SELECT namespace_id FROM documents WHERE id = ? AND tenant_id = ?", Array(tid, Api_TenantId)) + End Select + If Not rs.EOF Then + TargetNamespace = "" & rs(0) + End If + rs.Close + End Function + + Private Function JStr(v) + If IsNull(v) Then + JStr = "null" + Else + JStr = JsonLite_Quote("" & v) + End If + End Function + + Private Function JNum(v) + If IsNull(v) Then + JNum = "null" + ElseIf Len("" & v) = 0 Then + JNum = "null" + Else + JNum = JsonLite_Num(v) + End If + End Function + + Private Function JRaw(v, dflt) + If IsNull(v) Then + JRaw = dflt + ElseIf Len("" & v) = 0 Then + JRaw = dflt + Else + JRaw = "" & v + End If + End Function + + Private Sub AddErr(msg) + If Len(m_errs) > 0 Then + m_errs = m_errs & Chr(30) + End If + m_errs = m_errs & msg + End Sub + + Private Function ReqString(input, name, maxLen) + Dim v + ReqString = "" + If Not input.Exists(name) Then + AddErr name & " is required." + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + AddErr name & " is required." + Exit Function + End If + If VarType(v) <> vbString Then + AddErr name & " must be a string." + Exit Function + End If + v = Trim(v) + If Len(v) = 0 Then + AddErr name & " must not be empty." + Exit Function + End If + If Len(v) > maxLen Then + AddErr name & " must be at most " & maxLen & " characters." + Exit Function + End If + ReqString = v + End Function + + Private Function OptString(input, name, maxLen) + Dim v + OptString = Null + If Not input.Exists(name) Then + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + Exit Function + End If + If VarType(v) <> vbString Then + AddErr name & " must be a string." + Exit Function + End If + If Len(v) > maxLen Then + AddErr name & " must be at most " & maxLen & " characters." + Exit Function + End If + OptString = v + End Function + + Private Function OptUnit(input, name) + Dim v + OptUnit = Null + If Not input.Exists(name) Then + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + Exit Function + End If + If VarType(v) <> vbDouble Then + AddErr name & " must be a number between 0 and 1." + Exit Function + End If + If v < 0 Or v > 1 Then + AddErr name & " must be between 0 and 1." + Exit Function + End If + OptUnit = v + End Function + + Private Function TagsJson(input) + Dim arr, i, out, t + TagsJson = Null + If Not input.HasRaw("tags") Then + If input.Exists("tags") Then + If Not IsNull(input.Item("tags")) Then + AddErr "tags must be an array of strings." + End If + End If + Exit Function + End If + arr = JsonLite_ParseStringArray(input.Raw("tags")) + If IsNull(arr) Then + AddErr "tags must be an array of strings." + Exit Function + End If + If UBound(arr) > 31 Then + AddErr "tags may contain at most 32 entries." + Exit Function + End If + out = "" + For i = 0 To UBound(arr) + t = Trim(arr(i)) + If Len(t) = 0 Or Len(t) > 64 Then + AddErr "each tag must be 1 to 64 characters." + Exit Function + End If + If i > 0 Then + out = out & "," + End If + out = out & JsonLite_Quote(t) + Next + TagsJson = "[" & out & "]" + End Function + + ' Optional JSON object stored as raw text (max 16 KB), or Null + Private Function ObjectJson(input, name) + Dim raw + ObjectJson = Null + If Not input.HasRaw(name) Then + If input.Exists(name) Then + If Not IsNull(input.Item(name)) Then + AddErr name & " must be a JSON object." + End If + End If + Exit Function + End If + raw = input.Raw(name) + If Left(raw, 1) <> "{" Then + AddErr name & " must be a JSON object." + Exit Function + End If + If Len(raw) > 16384 Then + AddErr name & " must be at most 16 KB." + Exit Function + End If + ObjectJson = raw + End Function + + ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) + Public Sub Invoke(actionName, args) + Select Case LCase(actionName) + Case "recordevent" : RecordEvent args(0) + Case "events" : Events args(0) + Case "learn" : Learn + Case "candidates" : Candidates + Case "candidate" : Candidate args(0) + Case "review" : Review args(0) + Case "sources" : Sources args(0) + Case "feedback" : Feedback + Case Else + Err.Raise 438, "ApiLearningController_Class", "Action '" & actionName & "' not found" + End Select + End Sub + +End Class + +Dim ApiLearningController_Class__Singleton +Function ApiLearningController() + If IsEmpty(ApiLearningController_Class__Singleton) Then + Set ApiLearningController_Class__Singleton = New ApiLearningController_Class + End If + Set ApiLearningController = ApiLearningController_Class__Singleton +End Function + +' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) +Sub ApiLearningController_Invoke(actionName, args) + ApiLearningController().Invoke actionName, args +End Sub +%> diff --git a/app/controllers/ApiMemoriesController.asp b/app/controllers/ApiMemoriesController.asp index 32ccf27..85960a3 100644 --- a/app/controllers/ApiMemoriesController.asp +++ b/app/controllers/ApiMemoriesController.asp @@ -434,6 +434,7 @@ Class ApiMemoriesController_Class DAL().BeginTransaction Search_UnindexMemory id Emb_MarkDelete "memory", id + Mem_ForgetLinked 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) If Err.Number <> 0 Then @@ -611,8 +612,9 @@ Class ApiMemoriesController_Class '--------------------------------------------------------------- Public Sub Recall() 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, ranker + Dim rowJson(), out, count, excluded, now_, v, st, params, warnings, ranker, revs(), qid, spec, t0 + t0 = Timer If Not Api_Authenticate() Then Exit Sub body = Api_ReadBody() If IsEmpty(body) Then Exit Sub @@ -653,8 +655,11 @@ Class ApiMemoriesController_Class allowed = Api_AllowedNamespaceIds("read") If Len(allowed) > 0 And Len(requested) > 0 Then allowed = IntersectIds(allowed, requested) warnings = "[""semantic retrieval is not configured; results are lexical only""]" + qid = Tel_NewQueryId() + spec = "" If Len(allowed) = 0 Then - Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""results"":[],""warnings"":" & warnings & "}" + Tel_Record qid, "recall", "lexical", query, spec, t0 + Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":""lexical"",""results"":[],""warnings"":" & warnings & "}" Exit Sub End If @@ -692,6 +697,7 @@ Class ApiMemoriesController_Class If Len(typesSql) > 0 Then sql = sql & " AND m.type IN (" & typesSql & ")" Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_)) ReDim rowJson(n - 1) + ReDim revs(n - 1) Do While Not rs.EOF st = "" & rs(18) If vf = "verified_only" And st <> "verified" Then @@ -702,6 +708,7 @@ Class ApiMemoriesController_Class 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))) & "}" + revs(j) = CLng(rs(10)) Exit For End If Next @@ -715,6 +722,7 @@ Class ApiMemoriesController_Class If count > 0 Then out = out & "," out = out & rowJson(j) count = count + 1 + Tel_AddResult spec, "memory", ids(j), revs(j), -CDbl(scores(j)) End If Next End If @@ -724,8 +732,9 @@ Class ApiMemoriesController_Class End If warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them""" End If + Tel_Record qid, "recall", ranker.Strategy, query, spec, t0 Api_Audit "memory.recall", "search", "", "ok" - Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}" + Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""verification_filter"":" & JsonLite_Quote(vf) & ",""results"":[" & out & "],""warnings"":[" & warnings & "]}" End Sub '=============================================================== diff --git a/app/controllers/autoload_controllers.asp b/app/controllers/autoload_controllers.asp index bcf45c1..ccd3076 100644 --- a/app/controllers/autoload_controllers.asp +++ b/app/controllers/autoload_controllers.asp @@ -6,3 +6,4 @@ <!--#include file="ApiHealthController.asp" --> <!--#include file="ApiDocumentsController.asp" --> <!--#include file="ApiContextController.asp" --> +<!--#include file="ApiLearningController.asp" --> diff --git a/core/autoload_core.asp b/core/autoload_core.asp index d0a8365..af778a7 100644 --- a/core/autoload_core.asp +++ b/core/autoload_core.asp @@ -19,6 +19,7 @@ <!--#include file="../core/lib.Api.asp"--> <!--#include file="../core/lib.Search.asp"--> <!--#include file="../core/lib.Embeddings.asp"--> +<!--#include file="../core/lib.Learning.asp"--> <!--#include file="../app/models/autoload_models.asp" --> <!--#include file="../app/controllers/autoload_controllers.asp" --> <!--#include file="../core/mvc.asp"--> diff --git a/core/lib.ControllerRegistry.asp b/core/lib.ControllerRegistry.asp index 180f852..dcaef1c 100644 --- a/core/lib.ControllerRegistry.asp +++ b/core/lib.ControllerRegistry.asp @@ -16,6 +16,7 @@ Class ControllerRegistry_Class RegisterController "homecontroller" RegisterController "errorcontroller" RegisterController "apicontextcontroller" + RegisterController "apilearningcontroller" RegisterController "apidocumentscontroller" RegisterController "apihealthcontroller" RegisterController "apisessionscontroller" diff --git a/core/lib.JsonLite.asp b/core/lib.JsonLite.asp index 0a68baf..661dd7b 100644 --- a/core/lib.JsonLite.asp +++ b/core/lib.JsonLite.asp @@ -410,6 +410,72 @@ Function JsonLite_ParseStringArray(text) JsonLite_ParseStringArray = p.RunStringArray(text) End Function +' Raw texts of the objects in a JSON array of objects ("[{...},{...}]"), each parseable with JsonLite_Parse. +' Returns an empty array for "[]", Null when the text is not an array whose elements are all objects. +' The text has already been validated as JSON by the body parse, so only depth and strings are tracked. +Function JsonLite_SplitObjectArray(text) + Dim t, i, n, c, depth, inStr_, esc, start, items(), cnt + JsonLite_SplitObjectArray = Null + t = Trim("" & text) + n = Len(t) + If n < 2 Then + Exit Function + End If + If Left(t, 1) <> "[" Or Right(t, 1) <> "]" Then + Exit Function + End If + cnt = 0 + ReDim items(7) + depth = 0 + inStr_ = False + esc = False + start = 0 + For i = 2 To n - 1 + c = Mid(t, i, 1) + If inStr_ Then + If esc Then + esc = False + ElseIf c = "\" Then + esc = True + ElseIf c = """" Then + inStr_ = False + End If + ElseIf c = """" Then + If depth = 0 Then + Exit Function ' a string element + End If + inStr_ = True + ElseIf c = "{" Or c = "[" Then + If depth = 0 Then + If c = "[" Then + Exit Function ' a nested array element + End If + start = i + End If + depth = depth + 1 + ElseIf c = "}" Or c = "]" Then + depth = depth - 1 + If depth = 0 Then + If cnt > UBound(items) Then + ReDim Preserve items(cnt * 2) + End If + items(cnt) = Mid(t, start, i - start + 1) + cnt = cnt + 1 + End If + ElseIf depth = 0 Then + If c <> "," And c <> " " And c <> vbTab And c <> vbCr And c <> vbLf Then + Exit Function ' a number/true/false/null element + End If + End If + Next + If cnt = 0 Then + JsonLite_SplitObjectArray = Array() + Else + ReDim Preserve items(cnt - 1) + JsonLite_SplitObjectArray = items + End If +End Function + Dim JsonLite_SurrogateSeen JsonLite_SurrogateSeen = False diff --git a/core/lib.Learning.asp b/core/lib.Learning.asp new file mode 100644 index 0000000..6cb4a34 --- /dev/null +++ b/core/lib.Learning.asp @@ -0,0 +1,284 @@ +<% +'======================================================================================================================= +' Learning loop support (spec FR-012, FR-013, FR-014, FR-020, section 12): evidence links, memory writes shared by +' remember/correct and candidate review, and retrieval telemetry for feedback (AC-18). +' +' Evidence : Set ev = New Evidence_Class : msg = ev.Load(input, "evidence") ("" = ok, else a validation message) +' then, inside the write transaction: ev.Save "memory"|"candidate", ownerId, ownerRevision (or Null) +' Every target must be in the caller's tenant and readable by the caller; the target revision is +' pinned at link time (memory/document current revision, chunk document revision). +' Memories : Mem_InsertRevision, Mem_Create, Mem_Revise (call inside a transaction; they also update the lexical +' index and mark the semantic index pending; call Emb_AfterWrite after commit) +' Telemetry : Tel_Record queryId, operation, strategy, queryText, resultsSpec, startTimer +' resultsSpec = "kind|id|revision|score" items joined by Chr(30). Only a hash of the query is kept. +'======================================================================================================================= +Const EVIDENCE_MAX = 20 + +Class Evidence_Class + Private m_kind(), m_id(), m_rev(), m_role(), m_excerpt(), m_n + + Private Sub Class_Initialize() + m_n = 0 + ReDim m_kind(EVIDENCE_MAX) + ReDim m_id(EVIDENCE_MAX) + ReDim m_rev(EVIDENCE_MAX) + ReDim m_role(EVIDENCE_MAX) + ReDim m_excerpt(EVIDENCE_MAX) + End Sub + + Public Property Get Count() + Count = m_n + End Property + + ' Reads and validates input(name): an optional array of {"kind","id","role","excerpt"}. + Public Function Load(input, name) + Dim items, i, o, kind, id, role, excerpt, rev, ns, rs, pos + Load = "" + m_n = 0 + If Not input.HasRaw(name) Then + If input.Exists(name) Then + If Not IsNull(input.Item(name)) Then + Load = name & " must be an array of objects." + End If + End If + Exit Function + End If + items = JsonLite_SplitObjectArray(input.Raw(name)) + If IsNull(items) Then + Load = name & " must be an array of objects." + Exit Function + End If + If UBound(items) + 1 > EVIDENCE_MAX Then + Load = name & " may contain at most " & EVIDENCE_MAX & " items." + Exit Function + End If + For i = 0 To UBound(items) + pos = name & "[" & i & "]" + Set o = JsonLite_Parse(items(i)) + If o Is Nothing Then + Load = pos & " must be an object." + Exit Function + End If + kind = LCase("" & StrField(o, "kind")) + id = "" & StrField(o, "id") + role = LCase("" & StrField(o, "role")) + excerpt = StrField(o, "excerpt") + If Len(role) = 0 Then + role = "supports" + End If + If kind <> "experience" And kind <> "chunk" And kind <> "memory" And kind <> "document" Then + Load = pos & ".kind must be experience, chunk, memory or document." + Exit Function + End If + If role <> "supports" And role <> "contradicts" And role <> "context" Then + Load = pos & ".role must be supports, contradicts or context." + Exit Function + End If + If Not IsNull(excerpt) Then + If Len(excerpt) > 2000 Then + Load = pos & ".excerpt must be at most 2000 characters." + Exit Function + End If + End If + If Not Api_IsId(id) Then + Load = pos & ".id must be a valid id." + Exit Function + End If + ' Resolve the target in this tenant; a target the caller cannot read is reported like a missing one. + ns = "" + rev = Null + Select Case kind + Case "experience" + Set rs = DAL().Query("SELECT namespace_id FROM experiences WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If Not rs.EOF Then + ns = "" & rs(0) + End If + rs.Close + Case "chunk" + Set rs = DAL().Query("SELECT d.namespace_id, c.document_revision FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id = ? AND d.tenant_id = ?", Array(id, Api_TenantId)) + If Not rs.EOF Then + ns = "" & rs(0) + rev = CLng(rs(1)) + End If + rs.Close + Case "memory" + Set rs = DAL().Query("SELECT namespace_id, current_revision FROM memories WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If Not rs.EOF Then + ns = "" & rs(0) + rev = CLng(rs(1)) + End If + rs.Close + Case "document" + Set rs = DAL().Query("SELECT namespace_id, current_revision FROM documents WHERE id = ? AND tenant_id = ?", Array(id, Api_TenantId)) + If Not rs.EOF Then + ns = "" & rs(0) + rev = CLng(rs(1)) + End If + rs.Close + End Select + If Len(ns) = 0 Then + Load = pos & " was not found." + Exit Function + End If + If Not Api_CanAccessNamespace(ns, "read") Then + Load = pos & " was not found." + Exit Function + End If + m_kind(m_n) = kind + m_id(m_n) = id + m_rev(m_n) = rev + m_role(m_n) = role + m_excerpt(m_n) = excerpt + m_n = m_n + 1 + Next + End Function + + Private Function StrField(o, k) + Dim v + StrField = Null + If o.Exists(k) Then + v = o.Item(k) + If VarType(v) = vbString Then + StrField = v + End If + End If + End Function + + ' Writes the links (call inside the caller's transaction). ownerRevision: memory revision, or Null for candidates. + Public Sub Save(ownerKind, ownerId, ownerRevision) + Dim i, linkId + For i = 0 To m_n - 1 + linkId = Api_NewId() + DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", _ + Array(linkId, Api_TenantId, ownerKind, ownerId, m_kind(i), m_id(i), Api_PrincipalId, Api_Now()) + DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _ + Array(ownerRevision, m_rev(i), m_role(i), m_excerpt(i), linkId) + Next + End Sub +End Class + +' Copies a candidate's evidence to a memory revision (candidate acceptance; inside the transaction) +Sub Evidence_CopyCandidate(candidateId, memoryId, revision) + Dim rs, rows, i, linkId + Set rs = DAL().Query("SELECT target_kind, target_id, target_revision, role, excerpt FROM evidence_links WHERE owner_kind = 'candidate' AND owner_id = ?", candidateId) + rows = Empty + If Not rs.EOF Then + rows = rs.GetRows() + End If + rs.Close + If IsEmpty(rows) Then + Exit Sub + End If + For i = 0 To UBound(rows, 2) + linkId = Api_NewId() + DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, 'memory', ?, ?, ?, ?, ?)", _ + Array(linkId, Api_TenantId, memoryId, "" & rows(0, i), "" & rows(1, i), Api_PrincipalId, Api_Now()) + DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _ + Array(CLng(revision), rows(2, i), "" & rows(3, i), rows(4, i), linkId) + Next +End Sub + +'----------------------------------------------------------------------------------------------------------------------- +' Memory writes (inside a transaction) +'----------------------------------------------------------------------------------------------------------------------- +' G3DB allows at most 8 parameters per statement, so a revision is written in two steps. +Sub Mem_InsertRevision(revId, memId, revNo, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts) + DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) " & _ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", Array(revId, memId, revNo, title, content, hash, Api_PrincipalId, ts) + DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ? WHERE id = ?", _ + Array(summary, attrRaw, tagsRaw, confidence, importance, reason, revId) +End Sub + +Function Mem_Hash(nsId, memType, title, content) + Mem_Hash = Api_Sha256(nsId & "|" & memType & "|" & title & "|" & content) +End Function + +' New memory, revision 1. Returns the id. +Function Mem_Create(nsId, memType, title, summary, content, tagsRaw, confidence, reason) + Dim memId, ts + memId = Api_NewId() + ts = Api_Now() + DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) " & _ + "VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts) + Mem_InsertRevision Api_NewId(), memId, 1, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts + Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw + Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1 + Mem_Create = memId +End Function + +' New revision curRev + 1 of an existing memory (type and namespace unchanged). Returns the new revision number. +Function Mem_Revise(memId, nsId, memType, curRev, title, summary, content, tagsRaw, confidence, reason) + Dim newRev, ts + newRev = curRev + 1 + ts = Api_Now() + Mem_InsertRevision Api_NewId(), memId, newRev, title, summary, content, Null, tagsRaw, confidence, Null, Mem_Hash(nsId, memType, title, content), reason, ts + Search_IndexMemory memId, newRev, Api_TenantId, nsId, title, content, tagsRaw + Emb_MarkPending "memory", memId, Api_TenantId, nsId, newRev + DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _ + Array(newRev, ts, memId, Api_TenantId, CLng(curRev)) + Mem_Revise = newRev +End Function + +Sub Mem_Verify(memId, revision, method, notes) + DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, ?, ?, 'verified', ?, ?, ?)", _ + Array(Api_NewId(), memId, CLng(revision), method, notes, Api_PrincipalId, Api_Now()) + DAL().Execute "UPDATE memory_revisions SET verification_status = 'verified' WHERE memory_id = ? AND revision = ?", Array(memId, CLng(revision)) +End Sub + +' Derived and linked data of a memory that is being forgotten (inside the forget transaction, AC-13) +Sub Mem_ForgetLinked(memId) + DAL().Execute "DELETE FROM evidence_links WHERE owner_kind = 'memory' AND owner_id = ?", memId + DAL().Execute "DELETE FROM verifications WHERE memory_id = ?", memId + DAL().Execute "DELETE FROM feedback WHERE target_kind = 'memory' AND target_id = ?", memId + DAL().Execute "DELETE FROM retrieval_results WHERE target_kind = 'memory' AND target_id = ?", memId + ' Open proposals to revise it can no longer be applied; all candidates drop the reference (foreign key) + DAL().Execute "UPDATE learning_candidates SET state = 'rejected', review_notes = 'target memory was forgotten', reviewed_at = ? " & _ + "WHERE target_memory_id = ? AND state = 'proposed'", Array(Api_Now(), memId) + DAL().Execute "UPDATE learning_candidates SET target_memory_id = NULL WHERE target_memory_id = ?", memId +End Sub + +'----------------------------------------------------------------------------------------------------------------------- +' Retrieval telemetry (never fails the retrieval) +'----------------------------------------------------------------------------------------------------------------------- +Function Tel_NewQueryId() + Tel_NewQueryId = "qry-" & Api_NewId() +End Function + +Sub Tel_AddResult(ByRef spec, kind, id, revision, score) + If Len(spec) > 0 Then + spec = spec & Chr(30) + End If + spec = spec & kind & "|" & id & "|" & CLng(revision) & "|" & JsonLite_Num(score) +End Sub + +Sub Tel_Record(queryId, operation, strategy, queryText, spec, startTimer) + Dim items, i, parts, ms, cnt + On Error Resume Next + If Len(spec) = 0 Then + items = Array() + Else + items = Split(spec, Chr(30)) + End If + cnt = UBound(items) + 1 + ms = CLng((Timer - startTimer) * 1000) + If ms < 0 Then + ms = 0 + End If + DAL().BeginTransaction + DAL().Execute "INSERT INTO retrieval_queries (id, tenant_id, principal_id, operation, strategy, query_hash, result_count, duration_ms, created_at) " & _ + "VALUES (?, ?, ?, ?, ?, ?, " & cnt & ", " & ms & ", ?)", Array(queryId, Api_TenantId, Api_PrincipalId, operation, strategy, Api_Sha256("" & queryText), Api_Now()) + For i = 0 To cnt - 1 + parts = Split(items(i), "|") + DAL().Execute "INSERT OR IGNORE INTO retrieval_results (query_id, target_kind, target_id, target_revision, rank, score) VALUES (?, ?, ?, ?, ?, ?)", _ + Array(queryId, parts(0), parts(1), CLng(parts(2)), i + 1, CDbl(Replace(parts(3), ".", Mid(CStr(1.5), 2, 1)))) + Next + If Err.Number <> 0 Then + Err.Clear + DAL().RollbackTransaction + Else + DAL().CommitTransaction + End If + Err.Clear + On Error GoTo 0 +End Sub +%> diff --git a/db/migrations/20261205113137_create_learning_and_feedback_tables.asp b/db/migrations/20261205113137_create_learning_and_feedback_tables.asp new file mode 100644 index 0000000..d418641 --- /dev/null +++ b/db/migrations/20261205113137_create_learning_and_feedback_tables.asp @@ -0,0 +1,120 @@ +<% +'======================================================================================================================= +' MIGRATION: create_learning_and_feedback_tables +'======================================================================================================================= +' Phase 3 learning loop (spec FR-012, FR-013, FR-020, section 8, section 12, AC-18): +' experiences significant outcomes recorded in a session (task, problem, action, result, outcome) +' learning_candidates proposed knowledge (POST /learn); review accepts (creates or revises a memory) or rejects +' evidence_links evidence attached to a memory revision or a candidate (experience, chunk, memory, document) +' retrieval_queries one row per recall/search/context call (query text is stored only as a hash) +' retrieval_results the ranked targets and exact revisions a query returned +' feedback usefulness of one result of one query, by one principal +'----------------------------------------------------------------------------------------------------------------------- +Sub Migration_Up(migration) + migration.ExecuteSQL "CREATE TABLE experiences (" & _ + "id TEXT PRIMARY KEY, " & _ + "tenant_id TEXT NOT NULL REFERENCES tenants(id), " & _ + "namespace_id TEXT NOT NULL REFERENCES namespaces(id), " & _ + "session_id TEXT NOT NULL REFERENCES sessions(id), " & _ + "principal_id TEXT NOT NULL REFERENCES principals(id), " & _ + "task TEXT NOT NULL, " & _ + "problem TEXT, " & _ + "action TEXT, " & _ + "result TEXT, " & _ + "outcome TEXT NOT NULL CHECK (outcome IN ('success','failure','partial','unknown')), " & _ + "environment TEXT, " & _ + "created_at TEXT NOT NULL)" + migration.CreateIndex "idx_experiences_session", "experiences", "session_id, created_at" + migration.CreateIndex "idx_experiences_tenant", "experiences", "tenant_id" + + migration.ExecuteSQL "CREATE TABLE learning_candidates (" & _ + "id TEXT PRIMARY KEY, " & _ + "tenant_id TEXT NOT NULL REFERENCES tenants(id), " & _ + "namespace_id TEXT NOT NULL REFERENCES namespaces(id), " & _ + "type TEXT NOT NULL REFERENCES memory_types(code), " & _ + "title TEXT NOT NULL, " & _ + "summary TEXT, " & _ + "content TEXT NOT NULL, " & _ + "tags TEXT, " & _ + "confidence REAL, " & _ + "target_memory_id TEXT REFERENCES memories(id), " & _ + "base_revision INTEGER, " & _ + "state TEXT NOT NULL DEFAULT 'proposed' CHECK (state IN ('proposed','accepted','rejected')), " & _ + "author_principal_id TEXT NOT NULL REFERENCES principals(id), " & _ + "reviewer_principal_id TEXT REFERENCES principals(id), " & _ + "review_notes TEXT, " & _ + "resulting_memory_id TEXT, " & _ + "resulting_revision INTEGER, " & _ + "created_at TEXT NOT NULL, " & _ + "reviewed_at TEXT)" + migration.CreateIndex "idx_candidates_namespace", "learning_candidates", "tenant_id, namespace_id, state" + + migration.ExecuteSQL "CREATE TABLE evidence_links (" & _ + "id TEXT PRIMARY KEY, " & _ + "tenant_id TEXT NOT NULL REFERENCES tenants(id), " & _ + "owner_kind TEXT NOT NULL CHECK (owner_kind IN ('memory','candidate')), " & _ + "owner_id TEXT NOT NULL, " & _ + "owner_revision INTEGER, " & _ + "target_kind TEXT NOT NULL CHECK (target_kind IN ('experience','chunk','memory','document')), " & _ + "target_id TEXT NOT NULL, " & _ + "target_revision INTEGER, " & _ + "role TEXT NOT NULL DEFAULT 'supports' CHECK (role IN ('supports','contradicts','context')), " & _ + "excerpt TEXT, " & _ + "created_by TEXT NOT NULL REFERENCES principals(id), " & _ + "created_at TEXT NOT NULL)" + migration.CreateIndex "idx_evidence_owner", "evidence_links", "owner_kind, owner_id, owner_revision" + migration.CreateIndex "idx_evidence_tenant", "evidence_links", "tenant_id" + + migration.ExecuteSQL "CREATE TABLE retrieval_queries (" & _ + "id TEXT PRIMARY KEY, " & _ + "tenant_id TEXT NOT NULL REFERENCES tenants(id), " & _ + "principal_id TEXT NOT NULL REFERENCES principals(id), " & _ + "operation TEXT NOT NULL CHECK (operation IN ('recall','search','context')), " & _ + "strategy TEXT NOT NULL, " & _ + "query_hash TEXT NOT NULL, " & _ + "result_count INTEGER NOT NULL, " & _ + "duration_ms INTEGER, " & _ + "created_at TEXT NOT NULL)" + migration.CreateIndex "idx_retrieval_queries_tenant", "retrieval_queries", "tenant_id, created_at" + + migration.ExecuteSQL "CREATE TABLE retrieval_results (" & _ + "query_id TEXT NOT NULL REFERENCES retrieval_queries(id), " & _ + "target_kind TEXT NOT NULL CHECK (target_kind IN ('memory','chunk')), " & _ + "target_id TEXT NOT NULL, " & _ + "target_revision INTEGER NOT NULL, " & _ + "rank INTEGER NOT NULL, " & _ + "score REAL, " & _ + "PRIMARY KEY (query_id, target_kind, target_id))" + + migration.ExecuteSQL "CREATE TABLE feedback (" & _ + "id TEXT PRIMARY KEY, " & _ + "tenant_id TEXT NOT NULL REFERENCES tenants(id), " & _ + "query_id TEXT NOT NULL REFERENCES retrieval_queries(id), " & _ + "target_kind TEXT NOT NULL, " & _ + "target_id TEXT NOT NULL, " & _ + "target_revision INTEGER NOT NULL, " & _ + "principal_id TEXT NOT NULL REFERENCES principals(id), " & _ + "usefulness TEXT NOT NULL CHECK (usefulness IN ('useful','not_useful','incorrect','harmful')), " & _ + "comment TEXT, " & _ + "created_at TEXT NOT NULL, " & _ + "updated_at TEXT NOT NULL, " & _ + "UNIQUE (query_id, target_kind, target_id, principal_id))" + migration.CreateIndex "idx_feedback_target", "feedback", "target_kind, target_id" +End Sub + +Sub Migration_Down(migration) + migration.DropIndex "idx_feedback_target", "feedback" + migration.DropTable "feedback" + migration.DropTable "retrieval_results" + migration.DropIndex "idx_retrieval_queries_tenant", "retrieval_queries" + migration.DropTable "retrieval_queries" + migration.DropIndex "idx_evidence_tenant", "evidence_links" + migration.DropIndex "idx_evidence_owner", "evidence_links" + migration.DropTable "evidence_links" + migration.DropIndex "idx_candidates_namespace", "learning_candidates" + migration.DropTable "learning_candidates" + migration.DropIndex "idx_experiences_tenant", "experiences" + migration.DropIndex "idx_experiences_session", "experiences" + migration.DropTable "experiences" +End Sub +%> diff --git a/docker-compose.yml b/docker-compose.yml index 1c66391..e27598d 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -16,6 +16,23 @@ services: - .:/opt/axonasp/site restart: unless-stopped + # Background indexing: every 30 s, embeds memories/chunks still pending (writes only index a small batch + # after commit) and retries failed ones (up to 5 attempts; scripts\embed.cmd run resets them). + # Same image and mount as axonasp; the image entrypoint drops to the axonasp user. + embed-worker: + image: ghcr.io/guimaraeslucas/axonasp@sha256:39f582e2fcdb067d0141f94896e30bbe414e6c79db274077c653b543d519a741 + container_name: axonasp-embed-worker + environment: + SERVER_WEB_ROOT: /opt/axonasp/site + EMBED_ACTION: worker + command: ["/bin/sh", "-c", "while true; do ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp; sleep 30; done"] + volumes: + - .:/opt/axonasp/site + depends_on: + - ollama + - qdrant + 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: diff --git a/public/Default.asp b/public/Default.asp index ce3ddd2..8aa9cc7 100644 --- a/public/Default.asp +++ b/public/Default.asp @@ -41,6 +41,16 @@ ' Context assembly (Phase 3) router.AddRoute "POST", "/api/v1/context", "ApiContextController", "Assemble" + ' Learning loop: experiences, candidates and review, evidence, feedback (Phase 3) + router.AddRoute "POST", "/api/v1/sessions/:id/events", "ApiLearningController", "RecordEvent" + router.AddRoute "GET", "/api/v1/sessions/:id/events", "ApiLearningController", "Events" + router.AddRoute "POST", "/api/v1/learn", "ApiLearningController", "Learn" + router.AddRoute "GET", "/api/v1/candidates", "ApiLearningController", "Candidates" + router.AddRoute "GET", "/api/v1/candidates/:id", "ApiLearningController", "Candidate" + router.AddRoute "POST", "/api/v1/candidates/:id/review", "ApiLearningController", "Review" + router.AddRoute "GET", "/api/v1/memories/:id/sources", "ApiLearningController", "Sources" + router.AddRoute "POST", "/api/v1/feedback", "ApiLearningController", "Feedback" + ' Dispatch the request (resolves route and executes controller action). ' MVC() is called with parentheses: AxonASP cannot use "MVC.Method args" on a parameterless function. MVC().DispatchRequest Request.ServerVariables("REQUEST_METHOD"), GetRequestPath() diff --git a/public/api/memory-v1.openapi.json b/public/api/memory-v1.openapi.json index 9ff55d1..955e4b0 100644 --- a/public/api/memory-v1.openapi.json +++ b/public/api/memory-v1.openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Agent Memory API", "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. 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." + "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. Learning loop: experiences (POST /sessions/{id}/events), candidates proposed with POST /learn and reviewed by another principal (POST /candidates/{id}/review), evidence (GET /memories/{id}/sources) and feedback on retrieval results (POST /feedback, using the query_id of recall/search/context)." }, "servers": [ { @@ -621,15 +621,989 @@ "items": { "type": "string" } + }, + "query_id": { + "type": "string", + "description": "Pass to POST /feedback to rate an included memory or reference" + } + } + }, + "EvidenceInput": { + "type": "object", + "required": [ + "kind", + "id" + ], + "properties": { + "kind": { + "type": "string", + "enum": [ + "experience", + "chunk", + "memory", + "document" + ] + }, + "id": { + "type": "string", + "format": "uuid" + }, + "role": { + "type": "string", + "enum": [ + "supports", + "contradicts", + "context" + ], + "default": "supports" + }, + "excerpt": { + "type": "string", + "maxLength": 2000 + } + } + }, + "ExperienceRequest": { + "type": "object", + "required": [ + "task", + "outcome" + ], + "properties": { + "task": { + "type": "string", + "maxLength": 2000 + }, + "outcome": { + "type": "string", + "enum": [ + "success", + "failure", + "partial", + "unknown" + ] + }, + "problem": { + "type": "string", + "maxLength": 4000 + }, + "action": { + "type": "string", + "maxLength": 4000 + }, + "result": { + "type": "string", + "maxLength": 4000 + }, + "environment": { + "type": "object", + "description": "Free-form JSON object, max 16 KB" + } + } + }, + "Experience": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "task": { + "type": "string" + }, + "problem": { + "type": "string" + }, + "action": { + "type": "string" + }, + "result": { + "type": "string" + }, + "outcome": { + "type": "string" + }, + "recorded_by": { + "type": "string" + }, + "created_at": { + "type": "string" + }, + "environment": { + "type": "object", + "nullable": true + } + } + }, + "LearnRequest": { + "type": "object", + "required": [ + "namespace_id", + "type", + "title", + "content" + ], + "properties": { + "namespace_id": { + "type": "string", + "format": "uuid" + }, + "type": { + "type": "string" + }, + "title": { + "type": "string", + "maxLength": 200 + }, + "content": { + "type": "string", + "maxLength": 100000 + }, + "summary": { + "type": "string", + "maxLength": 2000 + }, + "tags": { + "type": "array", + "items": { + "type": "string" + }, + "maxItems": 32 + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "target_memory_id": { + "type": "string", + "format": "uuid", + "description": "Propose a new revision of this memory (same namespace and type)" + }, + "base_revision": { + "type": "integer", + "description": "Required with target_memory_id: the revision the proposal is based on" + }, + "evidence": { + "type": "array", + "maxItems": 20, + "items": { + "$ref": "#/components/schemas/EvidenceInput" + } + } + } + }, + "Candidate": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "namespace_id": { + "type": "string" + }, + "type": { + "type": "string" + }, + "title": { + "type": "string" + }, + "summary": { + "type": "string", + "nullable": true + }, + "content": { + "type": "string", + "description": "Detail only" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "confidence": { + "type": "number", + "nullable": true + }, + "target_memory_id": { + "type": "string", + "nullable": true + }, + "base_revision": { + "type": "integer", + "nullable": true + }, + "state": { + "type": "string", + "enum": [ + "proposed", + "accepted", + "rejected" + ] + }, + "author": { + "type": "string" + }, + "reviewer": { + "type": "string", + "nullable": true + }, + "review_notes": { + "type": "string", + "nullable": true + }, + "resulting_memory_id": { + "type": "string", + "nullable": true + }, + "resulting_revision": { + "type": "integer", + "nullable": true + }, + "created_at": { + "type": "string" + }, + "reviewed_at": { + "type": "string", + "nullable": true + }, + "content_trust": { + "type": "string", + "enum": [ + "proposed_knowledge" + ] + }, + "evidence": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EvidenceItem" + }, + "description": "Detail only" + } + } + }, + "EvidenceItem": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "id": { + "type": "string", + "description": "Omitted when available is false" + }, + "revision": { + "type": "integer", + "nullable": true, + "description": "Target revision pinned when the link was made" + }, + "available": { + "type": "boolean", + "description": "False when the target is gone or the caller cannot read it" + }, + "role": { + "type": "string" + }, + "excerpt": { + "type": "string", + "nullable": true + }, + "content_trust": { + "type": "string", + "enum": [ + "evidence", + "untrusted_reference" + ] + } + } + }, + "ReviewRequest": { + "type": "object", + "required": [ + "decision" + ], + "properties": { + "decision": { + "type": "string", + "enum": [ + "accept", + "reject" + ] + }, + "notes": { + "type": "string", + "maxLength": 2000 + }, + "verify": { + "type": "boolean", + "default": false, + "description": "Accept as verified (records a verification by the reviewer)" + } + } + }, + "Sources": { + "type": "object", + "properties": { + "memory_id": { + "type": "string" + }, + "revision": { + "type": "integer" + }, + "current_revision": { + "type": "integer" + }, + "from_candidate": { + "type": "string", + "nullable": true + }, + "evidence": { + "type": "array", + "items": { + "$ref": "#/components/schemas/EvidenceItem" + } + }, + "verifications": { + "type": "array", + "items": { + "type": "object", + "properties": { + "method": { + "type": "string" + }, + "result": { + "type": "string" + }, + "notes": { + "type": "string" + }, + "reviewer": { + "type": "string" + }, + "created_at": { + "type": "string" + } + } + } + } + } + }, + "FeedbackRequest": { + "type": "object", + "required": [ + "query_id", + "result_id", + "usefulness" + ], + "properties": { + "query_id": { + "type": "string", + "description": "query_id returned by recall, search or context" + }, + "result_id": { + "type": "string", + "format": "uuid", + "description": "Memory id or chunk id from that response" + }, + "usefulness": { + "type": "string", + "enum": [ + "useful", + "not_useful", + "incorrect", + "harmful" + ] + }, + "comment": { + "type": "string", + "maxLength": 2000 + } + } + }, + "Feedback": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "query_id": { + "type": "string" + }, + "target_kind": { + "type": "string", + "enum": [ + "memory", + "chunk" + ] + }, + "target_id": { + "type": "string" + }, + "target_revision": { + "type": "integer" + }, + "usefulness": { + "type": "string" + } + } + } + } + }, + "paths": { + "/remember": { + "post": { + "summary": "Create a memory", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Replays the stored response for an identical body; a different body with the same key is 409.", + "schema": { + "type": "string", + "maxLength": 200 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RememberRequest" + } + } + } + }, + "responses": { + "201": { + "description": "Created", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RememberResponse" + } + } + } + }, + "200": { + "description": "Exact duplicate (or idempotent replay of a 200)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RememberResponse" + } + } + } + }, + "400": { + "description": "Invalid JSON / body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Idempotency-Key reused with a different body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/memories": { + "get": { + "summary": "List memories (newest first)", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "namespace_id", + "in": "query", + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "type", + "in": "query", + "schema": { + "type": "string" + } + }, + { + "name": "status", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "active", + "retired", + "superseded", + "all" + ], + "default": "active" + } + }, + { + "name": "verification_status", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "unverified", + "verified", + "disputed", + "rejected" + ] + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 100, + "default": 20 + } + }, + { + "name": "cursor", + "in": "query", + "description": "next_cursor from the previous page", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Page of memories", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Memory" + } + }, + "next_cursor": { + "type": "string", + "nullable": true + } + } + } + } + } + }, + "400": { + "description": "Invalid cursor", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Invalid filter", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/memories/{id}": { + "get": { + "summary": "Get a memory (optionally an older revision)", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "revision", + "in": "query", + "schema": { + "type": "integer" + } + } + ], + "responses": { + "200": { + "description": "The memory", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Memory" + } + } + } + } + } + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "patch": { + "summary": "Correct a memory: creates the next revision, unverified", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + }, + { + "name": "If-Match", + "in": "header", + "required": false, + "description": "Current revision number (quoted ETag form accepted). Required unless expected_revision is in the body.", + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "title": { + "type": "string" + }, + "summary": { + "type": "string" + }, + "content": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "attributes": { + "type": "object" + }, + "confidence": { + "type": "number" + }, + "importance": { + "type": "number" + }, + "change_reason": { + "type": "string" + }, + "expected_revision": { + "type": "integer" + } + } + } + } + } + }, + "responses": { + "200": { + "description": "New revision", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RememberResponse" + } + } + } + }, + "400": { + "description": "Bad body / revision", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Memory is not active", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "412": { + "description": "Stale revision (ETag header carries the current one)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "428": { + "description": "If-Match missing", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + }, + "delete": { + "summary": "Forget: permanently delete the memory and its revisions (needs delete permission)", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "responses": { + "200": { + "description": "Deleted" + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } } } } - } - }, - "paths": { - "/remember": { + }, + "/memories/{id}/retire": { "post": { - "summary": "Create a memory", + "summary": "Retire: exclude from ordinary listing", "security": [ { "bearerAuth": [] @@ -637,49 +1611,158 @@ ], "parameters": [ { - "name": "Idempotency-Key", - "in": "header", - "required": false, - "description": "Replays the stored response for an identical body; a different body with the same key is 409.", + "name": "id", + "in": "path", + "required": true, "schema": { "type": "string", - "maxLength": 200 + "format": "uuid" } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RememberRequest" + "responses": { + "200": { + "description": "Retired" + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } } } } - }, + } + } + }, + "/memories/{id}/versions": { + "get": { + "summary": "Revision history, newest first", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], "responses": { - "201": { - "description": "Created", + "200": { + "description": "Revisions" + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RememberResponse" + "$ref": "#/components/schemas/Error" } } } }, - "200": { - "description": "Exact duplicate (or idempotent replay of a 200)", + "404": { + "description": "Not found or not visible to the caller", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RememberResponse" + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/sessions": { + "post": { + "summary": "Start a session", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Replays the stored response for an identical body; a different body with the same key is 409.", + "schema": { + "type": "string", + "maxLength": 200 + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "namespace_id", + "objective" + ], + "properties": { + "namespace_id": { + "type": "string", + "format": "uuid" + }, + "objective": { + "type": "string", + "maxLength": 2000 + } } } } + } + }, + "responses": { + "201": { + "description": "Started" }, - "400": { - "description": "Invalid JSON / body", + "422": { + "description": "Validation failed", "content": { "application/json": { "schema": { @@ -689,17 +1772,7 @@ } }, "409": { - "description": "Idempotency-Key reused with a different body", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "422": { - "description": "Validation failed", + "description": "Idempotency conflict", "content": { "application/json": { "schema": { @@ -741,9 +1814,9 @@ } } }, - "/memories": { + "/sessions/{id}/state": { "get": { - "summary": "List memories (newest first)", + "summary": "Restore the latest checkpoint (revision 0 / state null when none)", "security": [ { "bearerAuth": [] @@ -751,108 +1824,18 @@ ], "parameters": [ { - "name": "namespace_id", - "in": "query", + "name": "id", + "in": "path", + "required": true, "schema": { "type": "string", "format": "uuid" } - }, - { - "name": "type", - "in": "query", - "schema": { - "type": "string" - } - }, - { - "name": "status", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "active", - "retired", - "superseded", - "all" - ], - "default": "active" - } - }, - { - "name": "verification_status", - "in": "query", - "schema": { - "type": "string", - "enum": [ - "unverified", - "verified", - "disputed", - "rejected" - ] - } - }, - { - "name": "limit", - "in": "query", - "schema": { - "type": "integer", - "minimum": 1, - "maximum": 100, - "default": 20 - } - }, - { - "name": "cursor", - "in": "query", - "description": "next_cursor from the previous page", - "schema": { - "type": "string" - } } ], "responses": { "200": { - "description": "Page of memories", - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "data": { - "type": "array", - "items": { - "$ref": "#/components/schemas/Memory" - } - }, - "next_cursor": { - "type": "string", - "nullable": true - } - } - } - } - } - }, - "400": { - "description": "Invalid cursor", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "422": { - "description": "Invalid filter", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } + "description": "Checkpoint; ETag = revision" }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -885,11 +1868,9 @@ } } } - } - }, - "/memories/{id}": { - "get": { - "summary": "Get a memory (optionally an older revision)", + }, + "put": { + "summary": "Save a checkpoint (If-Match = current checkpoint revision, 0 for the first)", "security": [ { "bearerAuth": [] @@ -906,25 +1887,65 @@ } }, { - "name": "revision", - "in": "query", + "name": "If-Match", + "in": "header", + "required": false, + "description": "Current revision number (quoted ETag form accepted). Required unless expected_revision is in the body.", "schema": { - "type": "integer" + "type": "string" } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SaveStateRequest" + } + } + } + }, "responses": { "200": { - "description": "The memory", + "description": "Saved; ETag = new revision" + }, + "409": { + "description": "Session closed", "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "data": { - "$ref": "#/components/schemas/Memory" - } - } + "$ref": "#/components/schemas/Error" + } + } + } + }, + "412": { + "description": "Stale revision", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "428": { + "description": "If-Match missing", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" } } } @@ -960,9 +1981,11 @@ } } } - }, - "patch": { - "summary": "Correct a memory: creates the next revision, unverified", + } + }, + "/sessions/{id}/complete": { + "post": { + "summary": "Complete a session", "security": [ { "bearerAuth": [] @@ -977,53 +2000,18 @@ "type": "string", "format": "uuid" } - }, - { - "name": "If-Match", - "in": "header", - "required": false, - "description": "Current revision number (quoted ETag form accepted). Required unless expected_revision is in the body.", - "schema": { - "type": "string" - } } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "properties": { - "title": { - "type": "string" - }, - "summary": { - "type": "string" - }, - "content": { - "type": "string" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - } - }, - "attributes": { - "type": "object" - }, - "confidence": { - "type": "number" - }, - "importance": { - "type": "number" - }, - "change_reason": { - "type": "string" - }, - "expected_revision": { - "type": "integer" + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "outcome": { + "type": "string", + "maxLength": 4000 } } } @@ -1032,17 +2020,20 @@ }, "responses": { "200": { - "description": "New revision", + "description": "Completed" + }, + "409": { + "description": "Already closed", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/RememberResponse" + "$ref": "#/components/schemas/Error" } } } }, - "400": { - "description": "Bad body / revision", + "401": { + "description": "Missing, invalid, revoked or expired API key", "content": { "application/json": { "schema": { @@ -1051,8 +2042,8 @@ } } }, - "409": { - "description": "Memory is not active", + "404": { + "description": "Not found or not visible to the caller", "content": { "application/json": { "schema": { @@ -1061,8 +2052,8 @@ } } }, - "412": { - "description": "Stale revision (ETag header carries the current one)", + "500": { + "description": "Internal error", "content": { "application/json": { "schema": { @@ -1070,9 +2061,45 @@ } } } + } + } + } + }, + "/memories/{id}/verifications": { + "post": { + "summary": "Record a verification of the current revision (needs the verify permission)", + "security": [ + { + "bearerAuth": [] + } + ], + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" + } + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/VerifyRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Recorded; returns the new verification_status" }, - "422": { - "description": "Validation failed", + "409": { + "description": "Not the current revision", "content": { "application/json": { "schema": { @@ -1081,8 +2108,8 @@ } } }, - "428": { - "description": "If-Match missing", + "422": { + "description": "Validation failed", "content": { "application/json": { "schema": { @@ -1122,28 +2149,39 @@ } } } - }, - "delete": { - "summary": "Forget: permanently delete the memory and its revisions (needs delete permission)", + } + }, + "/recall": { + "post": { + "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": [ { "bearerAuth": [] } ], - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/RecallRequest" + } } } - ], + }, "responses": { "200": { - "description": "Deleted" + "description": "Ranked results with warnings" + }, + "422": { + "description": "Validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -1178,9 +2216,9 @@ } } }, - "/memories/{id}/retire": { + "/ingestion/jobs": { "post": { - "summary": "Retire: exclude from ordinary listing", + "summary": "Ingest a Markdown/text document (chunked, indexed)", "security": [ { "bearerAuth": [] @@ -1188,18 +2226,76 @@ ], "parameters": [ { - "name": "id", - "in": "path", - "required": true, + "name": "Idempotency-Key", + "in": "header", + "required": false, + "description": "Replays the stored response for an identical body; a different body with the same key is 409.", "schema": { "type": "string", - "format": "uuid" + "maxLength": 200 } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IngestRequest" + } + } + } + }, "responses": { + "201": { + "description": "Ingested (new document or new revision)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IngestResponse" + } + } + } + }, "200": { - "description": "Retired" + "description": "Unchanged or idempotent replay", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/IngestResponse" + } + } + } + }, + "400": { + "description": "Invalid JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "Idempotency-Key reused with a different body", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -1234,9 +2330,9 @@ } } }, - "/memories/{id}/versions": { + "/jobs/{id}": { "get": { - "summary": "Revision history, newest first", + "summary": "Ingestion job state", "security": [ { "bearerAuth": [] @@ -1255,7 +2351,7 @@ ], "responses": { "200": { - "description": "Revisions" + "description": "Job" }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -1290,9 +2386,9 @@ } } }, - "/sessions": { - "post": { - "summary": "Start a session", + "/documents/{id}": { + "get": { + "summary": "Document metadata (?include_content=true adds the normalized text)", "security": [ { "bearerAuth": [] @@ -1300,63 +2396,25 @@ ], "parameters": [ { - "name": "Idempotency-Key", - "in": "header", - "required": false, - "description": "Replays the stored response for an identical body; a different body with the same key is 409.", + "name": "id", + "in": "path", + "required": true, "schema": { "type": "string", - "maxLength": 200 + "format": "uuid" } - } - ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "type": "object", - "required": [ - "namespace_id", - "objective" - ], - "properties": { - "namespace_id": { - "type": "string", - "format": "uuid" - }, - "objective": { - "type": "string", - "maxLength": 2000 - } - } - } + }, + { + "name": "include_content", + "in": "query", + "schema": { + "type": "boolean" } } - }, + ], "responses": { - "201": { - "description": "Started" - }, - "422": { - "description": "Validation failed", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "409": { - "description": "Idempotency conflict", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } + "200": { + "description": "Document" }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -1391,9 +2449,9 @@ } } }, - "/sessions/{id}/state": { + "/chunks/{id}": { "get": { - "summary": "Restore the latest checkpoint (revision 0 / state null when none)", + "summary": "One chunk with heading path and source locator (character offsets into the normalized document text)", "security": [ { "bearerAuth": [] @@ -1412,7 +2470,7 @@ ], "responses": { "200": { - "description": "Checkpoint; ETag = revision" + "description": "Chunk" }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -1445,67 +2503,29 @@ } } } - }, - "put": { - "summary": "Save a checkpoint (If-Match = current checkpoint revision, 0 for the first)", + } + }, + "/search": { + "post": { + "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": [ { "bearerAuth": [] } ], - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - }, - { - "name": "If-Match", - "in": "header", - "required": false, - "description": "Current revision number (quoted ETag form accepted). Required unless expected_revision is in the body.", - "schema": { - "type": "string" - } - } - ], "requestBody": { "required": true, "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/SaveStateRequest" + "$ref": "#/components/schemas/SearchRequest" } } } }, "responses": { "200": { - "description": "Saved; ETag = new revision" - }, - "409": { - "description": "Session closed", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, - "412": { - "description": "Stale revision", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } + "description": "Ranked chunks with locators and content_trust" }, "422": { "description": "Validation failed", @@ -1517,16 +2537,6 @@ } } }, - "428": { - "description": "If-Match missing", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/Error" - } - } - } - }, "401": { "description": "Missing, invalid, revoked or expired API key", "content": { @@ -1560,47 +2570,60 @@ } } }, - "/sessions/{id}/complete": { + "/health/live": { + "get": { + "summary": "Liveness", + "responses": { + "200": { + "description": "Live" + } + } + } + }, + "/health/ready": { + "get": { + "summary": "Readiness (database reachable)", + "responses": { + "200": { + "description": "Ready" + }, + "503": { + "description": "Unavailable" + } + } + } + }, + "/context": { "post": { - "summary": "Complete a session", + "summary": "Assemble a token-budgeted task briefing: constraints by scope, working state, preferences, conflicts, hybrid matches and reference passages", "security": [ { "bearerAuth": [] } ], - "parameters": [ - { - "name": "id", - "in": "path", - "required": true, - "schema": { - "type": "string", - "format": "uuid" - } - } - ], "requestBody": { - "required": false, + "required": true, "content": { "application/json": { "schema": { - "type": "object", - "properties": { - "outcome": { - "type": "string", - "maxLength": 4000 - } - } + "$ref": "#/components/schemas/ContextRequest" } } } }, "responses": { "200": { - "description": "Completed" + "description": "Briefing", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContextResponse" + } + } + } }, - "409": { - "description": "Already closed", + "400": { + "description": "Empty body or invalid JSON", "content": { "application/json": { "schema": { @@ -1620,7 +2643,17 @@ } }, "404": { - "description": "Not found or not visible to the caller", + "description": "session_id not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed, unsupported_character (code points above U+FFFF), or context_budget_exceeded (the applicable constraints do not fit max_context_tokens; the error also carries required_tokens)", "content": { "application/json": { "schema": { @@ -1642,9 +2675,12 @@ } } }, - "/memories/{id}/verifications": { + "/sessions/{id}/events": { "post": { - "summary": "Record a verification of the current revision (needs the verify permission)", + "summary": "Record an experience (task, problem, action, result, outcome) in an active session", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] @@ -1659,6 +2695,16 @@ "type": "string", "format": "uuid" } + }, + { + "name": "Idempotency-Key", + "in": "header", + "required": false, + "schema": { + "type": "string", + "maxLength": 200 + }, + "description": "Replays the stored response for a repeated request; 409 if reused with a different body." } ], "requestBody": { @@ -1666,27 +2712,38 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/VerifyRequest" + "$ref": "#/components/schemas/ExperienceRequest" } } } }, "responses": { - "200": { - "description": "Recorded; returns the new verification_status" - }, - "409": { - "description": "Not the current revision", + "201": { + "description": "Recorded", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Error" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "session_id": { + "type": "string" + }, + "outcome": { + "type": "string" + }, + "created_at": { + "type": "string" + } + } } } } }, - "422": { - "description": "Validation failed", + "400": { + "description": "Empty body, invalid JSON or invalid Idempotency-Key", "content": { "application/json": { "schema": { @@ -1706,7 +2763,27 @@ } }, "404": { - "description": "Not found or not visible to the caller", + "description": "Session not found, or no write permission on its namespace", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "session_not_active (completed session) or idempotency_conflict", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed or unsupported_character", "content": { "application/json": { "schema": { @@ -1726,36 +2803,46 @@ } } } - } - }, - "/recall": { - "post": { - "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", + }, + "get": { + "summary": "List the experiences of a session, oldest first (max 200)", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RecallRequest" - } + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" } } - }, + ], "responses": { "200": { - "description": "Ranked results with warnings" - }, - "422": { - "description": "Validation failed", + "description": "Experiences", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Error" + "type": "object", + "properties": { + "session_id": { + "type": "string" + }, + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Experience" + } + } + } } } } @@ -1771,7 +2858,7 @@ } }, "404": { - "description": "Not found or not visible to the caller", + "description": "Session not found or not readable", "content": { "application/json": { "schema": { @@ -1793,9 +2880,12 @@ } } }, - "/ingestion/jobs": { + "/learn": { "post": { - "summary": "Ingest a Markdown/text document (chunked, indexed)", + "summary": "Propose knowledge as a learning candidate (a new memory, or a new revision of target_memory_id at base_revision), with evidence", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] @@ -1806,11 +2896,11 @@ "name": "Idempotency-Key", "in": "header", "required": false, - "description": "Replays the stored response for an identical body; a different body with the same key is 409.", "schema": { "type": "string", "maxLength": 200 - } + }, + "description": "Replays the stored response for a repeated request; 409 if reused with a different body." } ], "requestBody": { @@ -1818,34 +2908,44 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IngestRequest" - } - } - } - }, - "responses": { - "201": { - "description": "Ingested (new document or new revision)", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/IngestResponse" - } + "$ref": "#/components/schemas/LearnRequest" } } - }, - "200": { - "description": "Unchanged or idempotent replay", + } + }, + "responses": { + "201": { + "description": "Candidate proposed", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/IngestResponse" + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "state": { + "type": "string", + "enum": [ + "proposed" + ] + }, + "namespace_id": { + "type": "string" + }, + "type": { + "type": "string" + }, + "evidence_count": { + "type": "integer" + } + } } } } }, "400": { - "description": "Invalid JSON", + "description": "Empty body, invalid JSON or invalid Idempotency-Key", "content": { "application/json": { "schema": { @@ -1854,8 +2954,8 @@ } } }, - "409": { - "description": "Idempotency-Key reused with a different body", + "401": { + "description": "Missing, invalid, revoked or expired API key", "content": { "application/json": { "schema": { @@ -1864,8 +2964,8 @@ } } }, - "422": { - "description": "Validation failed", + "404": { + "description": "Namespace not found or no write permission", "content": { "application/json": { "schema": { @@ -1874,8 +2974,8 @@ } } }, - "401": { - "description": "Missing, invalid, revoked or expired API key", + "409": { + "description": "idempotency_conflict", "content": { "application/json": { "schema": { @@ -1884,8 +2984,8 @@ } } }, - "404": { - "description": "Not found or not visible to the caller", + "422": { + "description": "Validation failed (unknown type, bad target/base_revision, evidence that is unknown, in another tenant or not readable by the caller) or unsupported_character", "content": { "application/json": { "schema": { @@ -1907,9 +3007,12 @@ } } }, - "/jobs/{id}": { + "/candidates": { "get": { - "summary": "Ingestion job state", + "summary": "List learning candidates in namespaces the caller can read, newest first", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] @@ -1917,18 +3020,54 @@ ], "parameters": [ { - "name": "id", - "in": "path", - "required": true, + "name": "namespace_id", + "in": "query", "schema": { "type": "string", "format": "uuid" } + }, + { + "name": "state", + "in": "query", + "schema": { + "type": "string", + "enum": [ + "proposed", + "accepted", + "rejected" + ] + } + }, + { + "name": "limit", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1, + "maximum": 200, + "default": 50 + } } ], "responses": { "200": { - "description": "Job" + "description": "Candidates (without content)", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Candidate" + } + } + } + } + } + } }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -1940,8 +3079,8 @@ } } }, - "404": { - "description": "Not found or not visible to the caller", + "422": { + "description": "Bad state or namespace_id", "content": { "application/json": { "schema": { @@ -1963,9 +3102,12 @@ } } }, - "/documents/{id}": { + "/candidates/{id}": { "get": { - "summary": "Document metadata (?include_content=true adds the normalized text)", + "summary": "One candidate with content and evidence", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] @@ -1980,18 +3122,23 @@ "type": "string", "format": "uuid" } - }, - { - "name": "include_content", - "in": "query", - "schema": { - "type": "boolean" - } } ], "responses": { "200": { - "description": "Document" + "description": "Candidate", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "data": { + "$ref": "#/components/schemas/Candidate" + } + } + } + } + } }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -2004,7 +3151,7 @@ } }, "404": { - "description": "Not found or not visible to the caller", + "description": "Not found or not readable", "content": { "application/json": { "schema": { @@ -2026,9 +3173,12 @@ } } }, - "/chunks/{id}": { - "get": { - "summary": "One chunk with heading path and source locator (character offsets into the normalized document text)", + "/candidates/{id}/review": { + "post": { + "summary": "Accept or reject a proposed candidate. Needs verify permission; the author cannot review its own candidate without admin. Accepting creates the memory (an identical active memory is reused) or a new revision of the target, copies the evidence and, with verify true, records a verification by the reviewer.", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] @@ -2045,9 +3195,60 @@ } } ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ReviewRequest" + } + } + } + }, "responses": { "200": { - "description": "Chunk" + "description": "Reviewed", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "state": { + "type": "string", + "enum": [ + "accepted", + "rejected" + ] + }, + "resulting_memory_id": { + "type": "string" + }, + "resulting_revision": { + "type": "integer" + }, + "verification_status": { + "type": "string" + }, + "duplicate": { + "type": "boolean" + } + } + } + } + } + }, + "400": { + "description": "Empty body or invalid JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } }, "401": { "description": "Missing, invalid, revoked or expired API key", @@ -2059,8 +3260,38 @@ } } }, + "403": { + "description": "self_review_not_allowed", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, "404": { - "description": "Not found or not visible to the caller", + "description": "Candidate not found or no verify permission", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "candidate_already_reviewed, stale_candidate (target memory changed since base_revision), target_memory_missing or target_memory_not_active", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed", "content": { "application/json": { "schema": { @@ -2082,34 +3313,44 @@ } } }, - "/search": { - "post": { - "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", + "/memories/{id}/sources": { + "get": { + "summary": "Evidence and verifications behind a memory revision. Evidence the caller cannot read is listed with available false and no id.", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] } ], - "requestBody": { - "required": true, - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/SearchRequest" - } + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string", + "format": "uuid" } + }, + { + "name": "revision", + "in": "query", + "schema": { + "type": "integer", + "minimum": 1 + }, + "description": "Default: current revision" } - }, + ], "responses": { "200": { - "description": "Ranked chunks with locators and content_trust" - }, - "422": { - "description": "Validation failed", + "description": "Sources", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/Error" + "$ref": "#/components/schemas/Sources" } } } @@ -2125,7 +3366,17 @@ } }, "404": { - "description": "Not found or not visible to the caller", + "description": "Memory not found or not readable", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "revision out of range", "content": { "application/json": { "schema": { @@ -2147,32 +3398,12 @@ } } }, - "/health/live": { - "get": { - "summary": "Liveness", - "responses": { - "200": { - "description": "Live" - } - } - } - }, - "/health/ready": { - "get": { - "summary": "Readiness (database reachable)", - "responses": { - "200": { - "description": "Ready" - }, - "503": { - "description": "Unavailable" - } - } - } - }, - "/context": { + "/feedback": { "post": { - "summary": "Assemble a token-budgeted task briefing: constraints by scope, working state, preferences, conflicts, hybrid matches and reference passages", + "summary": "Rate one result of a recall, search or context call (by its query_id). One rating per principal, query and result; a new rating replaces the earlier one (200). Pinned to the revision that was returned.", + "tags": [ + "learning" + ], "security": [ { "bearerAuth": [] @@ -2183,18 +3414,28 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ContextRequest" + "$ref": "#/components/schemas/FeedbackRequest" } } } }, "responses": { "200": { - "description": "Briefing", + "description": "Updated", "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/ContextResponse" + "$ref": "#/components/schemas/Feedback" + } + } + } + }, + "201": { + "description": "Recorded", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Feedback" } } } @@ -2220,7 +3461,7 @@ } }, "404": { - "description": "session_id not found or not visible to the caller", + "description": "result_not_found: the result was not returned by that query, is gone, or is not readable", "content": { "application/json": { "schema": { @@ -2230,7 +3471,7 @@ } }, "422": { - "description": "Validation failed, unsupported_character (code points above U+FFFF), or context_budget_exceeded (the applicable constraints do not fit max_context_tokens; the error also carries required_tokens)", + "description": "Validation failed", "content": { "application/json": { "schema": { diff --git a/scripts/embed.asp b/scripts/embed.asp index 22c0202..db19bfe 100644 --- a/scripts/embed.asp +++ b/scripts/embed.asp @@ -1,6 +1,8 @@ <% ' Semantic index maintenance (see core/lib.Embeddings.asp). Run through scripts\embed.cmd, which sets EMBED_ACTION: -' status | run | reindex +' status | run | reindex | worker +' worker: one quiet pass for the embed-worker service in docker-compose.yml (pending rows and failed rows that +' still have attempts left; prints a line only when something was indexed or failed) ' The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site %> <!--#include file="../core/autoload_core.asp" --> @@ -78,6 +80,26 @@ Select Case action RunAll ShowStatus End If + Case "worker" + If Emb_Enabled() Then + Emb_LastError = "" + total = 0 + rounds = 0 + Do + n = Emb_ProcessPending("", 64) + total = total + n + rounds = rounds + 1 + If n = 0 Or rounds >= 20 Then + Exit Do + End If + Loop + If total > 0 Then + Response.Write Api_Now() & " indexed " & total & vbCrLf + End If + If Len(Emb_LastError) > 0 Then + Response.Write Api_Now() & " ERROR " & Emb_LastError & vbCrLf + End If + End If Case Else Response.Write "Usage: scripts\embed.cmd status|run|reindex" & vbCrLf End Select diff --git a/scripts/kb.sh b/scripts/kb.sh new file mode 100644 index 0000000..01c1c49 --- /dev/null +++ b/scripts/kb.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Use this repo's own knowledge base (the Agent Memory API running in docker-compose) while developing it. +# Settings and keys come from .amk.env at the repo root (git-ignored; created when the tenant was provisioned). +# +# bash scripts/kb.sh context "<task>" briefing for a task (constraints, lessons, references) +# bash scripts/kb.sh recall "<query>" [unverified] memories matching a query +# bash scripts/kb.sh search "<query>" passages from ingested documents +# bash scripts/kb.sh ingest <file.md> [title] ingest or re-ingest a Markdown file (source kb://repo/<file>) +# bash scripts/kb.sh learn <type> "<title>" "<content>" propose knowledge (lesson, decision, constraint, ...) +# bash scripts/kb.sh candidates open proposals +# bash scripts/kb.sh review <candidate_id> accept|reject [notes] owner only: accept (verified) or reject +# bash scripts/kb.sh feedback <query_id> <result_id> useful|not_useful|incorrect|harmful +set -eu +ROOT=$(cd "$(dirname "$0")/.." && pwd) +[ -f "$ROOT/.amk.env" ] || { echo "missing $ROOT/.amk.env (provision a tenant first, see AGENTS.md)" >&2; exit 2; } +# shellcheck disable=SC1091 +. <(tr -d '\r' < "$ROOT/.amk.env") +py() { python -I -c "import json,sys;a=sys.argv[1:];$1" "${@:2}"; } +call() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" -H 'Content-Type: application/json' "$@" "$AMK_URL$p"; echo; } +cmd=${1:-}; shift || true +case "$cmd" in + context) + call "$AMK_KEY" POST /context --data-binary "$(py 'print(json.dumps({"task":a[0],"namespace_ids":[a[1]]}))' "$1" "$AMK_NAMESPACE")" ;; + recall) + vf=verified_only; [ "${2:-}" = unverified ] && vf=include_unverified + call "$AMK_KEY" POST /recall --data-binary "$(py 'print(json.dumps({"query":a[0],"namespace_ids":[a[1]],"verification_filter":a[2]}))' "$1" "$AMK_NAMESPACE" "$vf")" ;; + search) + call "$AMK_KEY" POST /search --data-binary "$(py 'print(json.dumps({"query":a[0],"namespace_ids":[a[1]]}))' "$1" "$AMK_NAMESPACE")" ;; + ingest) + f=$1; rel=${f#"$ROOT"/} + # large files: the body goes through stdin (the Windows command line is too short for it) + py 'sys.stdout.buffer.write(json.dumps({"namespace_id":a[0],"title":a[1],"source_uri":"kb://repo/"+a[2],"format":"markdown","content":open(a[3],encoding="utf-8").read()}).encode())' "$AMK_NAMESPACE" "${2:-$rel}" "$rel" "$f" | call "$AMK_KEY" POST /ingestion/jobs --data-binary @- ;; + learn) + call "$AMK_KEY" POST /learn --data-binary "$(py 'print(json.dumps({"namespace_id":a[0],"type":a[1],"title":a[2],"content":a[3]}))' "$AMK_NAMESPACE" "$1" "$2" "$3")" ;; + candidates) + call "$AMK_KEY" GET "/candidates?state=proposed" ;; + review) + call "$AMK_OWNER_KEY" POST "/candidates/$1/review" --data-binary "$(py 'print(json.dumps({"decision":a[0],"notes":a[1],"verify":a[0]=="accept"}))' "$2" "${3:-}")" ;; + feedback) + call "$AMK_KEY" POST /feedback --data-binary "$(py 'print(json.dumps({"query_id":a[0],"result_id":a[1],"usefulness":a[2]}))' "$1" "$2" "$3")" ;; + *) + sed -n '2,14p' "$0"; exit 1 ;; +esac diff --git a/scripts/provision.asp b/scripts/provision.asp index d253fba..3e96e16 100644 --- a/scripts/provision.asp +++ b/scripts/provision.asp @@ -184,6 +184,12 @@ Select Case action ' vector points and their bookkeeping first (the store is outside the transaction; best effort) Emb_DeleteTenant a1 DAL().BeginTransaction + DAL().Execute "DELETE FROM feedback WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM retrieval_results WHERE query_id IN (SELECT id FROM retrieval_queries WHERE tenant_id = ?)", a1 + DAL().Execute "DELETE FROM retrieval_queries WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM evidence_links WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM learning_candidates WHERE tenant_id = ?", a1 + DAL().Execute "DELETE FROM experiences 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 verifications WHERE memory_id IN (SELECT id FROM memories WHERE tenant_id = ?)", a1 diff --git a/tests/phase3-learning.sh b/tests/phase3-learning.sh new file mode 100644 index 0000000..e0bc54e --- /dev/null +++ b/tests/phase3-learning.sh @@ -0,0 +1,204 @@ +#!/usr/bin/env bash +# Phase 3 learning loop checks (spec FR-012, FR-013, FR-014, FR-020, section 12, AC-08, AC-16, AC-18): session +# experiences, learning candidates and review (no self-approval, stale revision proposals, duplicates), evidence with +# pinned revisions and hidden unreadable sources, retrieval telemetry and feedback, forgetting linked data, +# isolation, validation, escaping and UTF-8. +# +# Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions two +# throw-away tenants and purges them at the end (even on failure). +# bash tests/phase3-learning.sh +set -u +BASE=${BASE:-http://localhost:8801/api/v1} +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' +} +field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } +jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; } +cleanup() { 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"; } +has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; } +jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)"; } # jq_ '<python expr on d>' (UTF-8 stdin on Windows) +js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; } # JSON string literal + +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; } +# learn <key> <json body> -> full response +learn() { body "$1" POST /learn -d "$2"; } +review() { body "$1" POST /candidates/$2/review -d "$3"; } + +# ---- setup ------------------------------------------------------------------------------------------------ +TA=$(prov tenant "p3l-A" | field tenant_id); TB=$(prov tenant "p3l-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 # proposes; also holds verify (self-review test) +mk "$TA" reviewer human; VID=$P_ID; VK=$P_KEY # reviews +mk "$TA" owner human; AID=$P_ID; AK=$P_KEY # admin on /kb and /secret +mk "$TA" reader agent; RID=$P_ID; RK=$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,verify" 1 >/dev/null +prov grant "$VID" /kb "read,verify" 1 >/dev/null +prov grant "$AID" /kb "admin" 1 >/dev/null +prov grant "$AID" /secret "admin" 1 >/dev/null +prov grant "$RID" /kb "read" 1 >/dev/null +prov grant "$BLID" /elsewhere "read" 1 >/dev/null +prov grant "$BID" /kb "read,write,verify" 1 >/dev/null +NS=$(prov namespace "$TA" /kb | field namespace_id); NSS=$(prov namespace "$TA" /secret | field namespace_id) +NSB=$(prov namespace "$TB" /kb | field namespace_id) +[ -n "$NS" ] && [ -n "$NSS" ] && [ -n "$NSB" ] && [ -n "$WK" ] && [ -n "$AK" ] || { echo "setup failed"; exit 2; } + +M0=$(remember "$WK" "$NS" semantic "Gadget port" "The quillfeather gadget listens on port 7100."); verify "$VK" "$M0" +MS=$(remember "$AK" "$NSS" semantic "Secret" "Quillfeather secret rotation key lives in vault seven.") +MB=$(remember "$BK" "$NSB" semantic "B fact" "Tenant B quillfeather fact.") +SID=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"Fix quillfeather\"}" | jget id) +[ -n "$M0" ] && [ -n "$MS" ] && [ -n "$MB" ] && [ -n "$SID" ] || { echo "data setup failed"; exit 2; } + +# ---- cold start: first request after a restart is an event POST --------------------------------------------- +docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done +EVB='{"task":"Deploy quillfeather","outcome":"failure","problem":"Port 7100 was taken","action":"Moved to 7101","result":"Deploy worked after the move","environment":{"os":"linux","attempt":2}}' +R=$(body "$WK" POST /sessions/$SID/events -H 'Idempotency-Key: ev-1' -d "$EVB") +EXP=$(echo "$R" | jget id) +check "cold: record event -> id" "yes" "$([ -n "$EXP" ] && echo yes || echo no)" +check "idempotent replay -> same id" "$EXP" "$(body "$WK" POST /sessions/$SID/events -H 'Idempotency-Key: ev-1' -d "$EVB" | jget id)" +check "idempotency key with other body -> 409" "409" "$(code "$WK" POST /sessions/$SID/events -H 'Idempotency-Key: ev-1' -d '{"task":"x","outcome":"success"}')" +R=$(body "$RK" GET /sessions/$SID/events) +check "events: one experience" "1" "$(echo "$R" | jq_ "len(d['data'])")" +check "events: environment round-trips as object" "2" "$(echo "$R" | jq_ "d['data'][0]['environment']['attempt']")" +check "events: outcome kept" "failure" "$(echo "$R" | jq_ "d['data'][0]['outcome']")" +check "event bad outcome -> 422" "422" "$(code "$WK" POST /sessions/$SID/events -d '{"task":"x","outcome":"great"}')" +check "event missing task -> 422" "422" "$(code "$WK" POST /sessions/$SID/events -d '{"outcome":"success"}')" +check "event environment not object -> 422" "422" "$(code "$WK" POST /sessions/$SID/events -d '{"task":"x","outcome":"success","environment":[1]}')" +check "event invalid JSON -> 400" "400" "$(code "$WK" POST /sessions/$SID/events -d '{"task":')" +check "event by reader (no write) -> 404" "404" "$(code "$RK" POST /sessions/$SID/events -d '{"task":"x","outcome":"success"}')" +check "event from other tenant -> 404" "404" "$(code "$BK" POST /sessions/$SID/events -d '{"task":"x","outcome":"success"}')" +check "events read by blind -> 404" "404" "$(code "$BLK" GET /sessions/$SID/events)" +check "event unknown session -> 404" "404" "$(code "$WK" POST /sessions/00000000-0000-4000-8000-000000000000/events -d '{"task":"x","outcome":"success"}')" +check "events wrong method -> 404 (router has no 405)" "404" "$(code "$WK" DELETE /sessions/$SID/events)" +SID2=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"done\"}" | jget id) +code "$WK" POST /sessions/$SID2/complete -d '{"outcome":"ok"}' >/dev/null +check "event on completed session -> 409" "409" "$(code "$WK" POST /sessions/$SID2/events -d '{"task":"x","outcome":"success"}')" + +# ---- learn --------------------------------------------------------------------------------------------------- +LB="{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Port clash\",\"content\":\"When quillfeather port 7100 is taken, move it to 7101.\",\"tags\":[\"ports\"],\"confidence\":0.8,\"evidence\":[{\"kind\":\"experience\",\"id\":\"$EXP\",\"role\":\"supports\",\"excerpt\":\"Moved to 7101\"},{\"kind\":\"memory\",\"id\":\"$M0\",\"role\":\"context\"}]}" +R=$(learn "$WK" "$LB") +C1=$(echo "$R" | jget id) +check "learn -> proposed" "proposed" "$(echo "$R" | jget state)" +check "learn -> evidence_count 2" "2" "$(echo "$R" | jq_ "d['evidence_count']")" +check "learn unknown type -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"gossip\",\"title\":\"t\",\"content\":\"c\"}")" +check "learn missing content -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\"}")" +check "learn confidence > 1 -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"confidence\":2}")" +check "learn target without base_revision -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"t\",\"content\":\"c\",\"target_memory_id\":\"$M0\"}")" +check "learn target of other type -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"target_memory_id\":\"$M0\",\"base_revision\":1}")" +check "evidence not an array -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"evidence\":{\"kind\":\"memory\"}}")" +check "evidence unknown kind -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"evidence\":[{\"kind\":\"rumour\",\"id\":\"$M0\"}]}")" +check "evidence unknown id -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"evidence\":[{\"kind\":\"memory\",\"id\":\"00000000-0000-4000-8000-000000000000\"}]}")" +check "evidence in other tenant -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"evidence\":[{\"kind\":\"memory\",\"id\":\"$MB\"}]}")" +check "evidence the caller cannot read -> 422" "422" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\",\"evidence\":[{\"kind\":\"memory\",\"id\":\"$MS\"}]}")" +check "learn by reader -> 404" "404" "$(code "$RK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\"}")" +check "learn in other tenant namespace -> 404" "404" "$(code "$WK" POST /learn -d "{\"namespace_id\":\"$NSB\",\"type\":\"lesson\",\"title\":\"t\",\"content\":\"c\"}")" +# escaping and UTF-8 (backslashes built at run time, see AGENTS.md) +BS=$(printf '%s' '\') +UB="{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"<script>alert(1)</script> ${BS}\"q${BS}\"\",\"content\":\"Gr${BS}u00fc${BS}u00dfe quillfeather ${BS}u65e5\"}" +C2=$(curl -s -X POST -H "Authorization: Bearer $WK" --data-binary "$UB" "$BASE/learn" | jget id) +R=$(body "$VK" GET /candidates/$C2) +check "candidate title escaped in JSON" "<script>alert(1)</script> \"q\"" "$(echo "$R" | jq_ "d['data']['title']")" +check "candidate UTF-8 round trip" "yes" "$(echo "$R" | jq_ "'yes' if d['data']['content']=='Gr'+chr(252)+chr(223)+'e quillfeather '+chr(0x65e5) else 'no'")" + +# ---- list and detail ----------------------------------------------------------------------------------------- +check "list proposed (reviewer) has C1" "yes" "$(body "$VK" GET "/candidates?state=proposed" | jq_ "'yes' if any(x['id']=='$C1' for x in d['data']) else 'no'")" +check "list content_trust proposed_knowledge" "proposed_knowledge" "$(body "$VK" GET /candidates | jq_ "d['data'][0]['content_trust']")" +check "list for blind is empty" "0" "$(body "$BLK" GET /candidates | jq_ "len(d['data'])")" +check "list for other tenant is empty" "0" "$(body "$BK" GET /candidates | jq_ "len(d['data'])")" +check "list bad state -> 422" "422" "$(code "$VK" GET "/candidates?state=maybe")" +R=$(body "$VK" GET /candidates/$C1) +check "detail evidence count" "2" "$(echo "$R" | jq_ "len(d['data']['evidence'])")" +check "detail evidence pins memory revision" "1" "$(echo "$R" | jq_ "[e for e in d['data']['evidence'] if e['kind']=='memory'][0]['revision']")" +check "detail by blind -> 404" "404" "$(code "$BLK" GET /candidates/$C1)" +check "detail unknown -> 404" "404" "$(code "$VK" GET /candidates/00000000-0000-4000-8000-000000000000)" + +# ---- review -------------------------------------------------------------------------------------------------- +check "self-review without admin -> 403" "403" "$(code "$WK" POST /candidates/$C1/review -d '{"decision":"accept"}')" +check "review by reader (no verify) -> 404" "404" "$(code "$RK" POST /candidates/$C1/review -d '{"decision":"accept"}')" +check "review bad decision -> 422" "422" "$(code "$VK" POST /candidates/$C1/review -d '{"decision":"maybe"}')" +check "review verify not boolean -> 422" "422" "$(code "$VK" POST /candidates/$C1/review -d '{"decision":"accept","verify":"yes"}')" +R=$(review "$VK" "$C1" '{"decision":"accept","notes":"checked the deploy log","verify":true}') +MEM1=$(echo "$R" | jget resulting_memory_id) +check "accept -> accepted" "accepted" "$(echo "$R" | jget state)" +check "accept with verify -> verified" "verified" "$(echo "$R" | jget verification_status)" +check "accept again -> 409" "409" "$(code "$VK" POST /candidates/$C1/review -d '{"decision":"reject"}')" +check "accepted memory readable" "lesson" "$(body "$RK" GET /memories/$MEM1 | jq_ "d['data']['type']")" +R=$(body "$RK" GET /memories/$MEM1/sources) +check "sources: from candidate" "$C1" "$(echo "$R" | jget from_candidate)" +check "sources: evidence copied" "2" "$(echo "$R" | jq_ "len(d['evidence'])")" +check "sources: verification recorded" "candidate_review" "$(echo "$R" | jq_ "d['verifications'][0]['method']")" +check "sources: experience evidence available" "True" "$(echo "$R" | jq_ "[e for e in d['evidence'] if e['kind']=='experience'][0]['available']")" +check "sources bad revision -> 422" "422" "$(code "$RK" GET "/memories/$MEM1/sources?revision=9")" +check "sources by blind -> 404" "404" "$(code "$BLK" GET /memories/$MEM1/sources)" +# reject +C3=$(learn "$WK" "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Wrong\",\"content\":\"Quillfeather never needs restarts.\"}" | jget id) +check "reject -> rejected" "rejected" "$(review "$VK" "$C3" '{"decision":"reject","notes":"contradicted by logs"}' | jget state)" +check "rejected candidate made no memory" "0" "$(body "$VK" POST /recall -d '{"query":"never needs restarts","verification_filter":"include_unverified"}' | jq_ "len(d['results'])")" +# duplicate of an existing memory: reuses it +C4=$(learn "$WK" "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Port clash\",\"content\":\"When quillfeather port 7100 is taken, move it to 7101.\"}" | jget id) +R=$(review "$VK" "$C4" '{"decision":"accept"}') +check "duplicate accept reuses memory" "$MEM1" "$(echo "$R" | jget resulting_memory_id)" +check "duplicate flagged" "True" "$(echo "$R" | jq_ "d['duplicate']")" +# revision proposals and stale base revision +C5=$(learn "$WK" "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"Gadget port\",\"content\":\"The quillfeather gadget listens on port 7101.\",\"target_memory_id\":\"$M0\",\"base_revision\":1}" | jget id) +C6=$(learn "$WK" "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"Gadget port\",\"content\":\"The quillfeather gadget listens on port 7200.\",\"target_memory_id\":\"$M0\",\"base_revision\":1}" | jget id) +R=$(review "$VK" "$C5" '{"decision":"accept"}') +check "revision accept -> revision 2" "2" "$(echo "$R" | jq_ "d['resulting_revision']")" +check "revision accept stays unverified without verify" "unverified" "$(echo "$R" | jget verification_status)" +check "memory now at revision 2" "2" "$(body "$RK" GET /memories/$M0 | jq_ "d['data']['current_revision']")" +check "stale proposal -> 409" "409" "$(code "$VK" POST /candidates/$C6/review -d '{"decision":"accept"}')" +check "stale proposal stays proposed" "proposed" "$(body "$VK" GET /candidates/$C6 | jq_ "d['data']['state']")" +# admin may approve its own candidate; evidence it can read but the reader cannot is hidden from the reader +C7=$(learn "$AK" "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Rotation\",\"content\":\"Rotate quillfeather keys monthly.\",\"evidence\":[{\"kind\":\"memory\",\"id\":\"$MS\"}]}" | jget id) +R=$(review "$AK" "$C7" '{"decision":"accept","verify":true}') +MEM7=$(echo "$R" | jget resulting_memory_id) +check "admin self-review -> accepted" "accepted" "$(echo "$R" | jget state)" +R=$(body "$RK" GET /memories/$MEM7/sources) +check "unreadable evidence -> available false" "False" "$(echo "$R" | jq_ "d['evidence'][0]['available']")" +check "unreadable evidence id hidden" "no" "$(has "$MS" "$R")" +check "admin sees the evidence id" "yes" "$(has "$MS" "$(body "$AK" GET /memories/$MEM7/sources)")" + +# ---- telemetry and feedback ---------------------------------------------------------------------------------- +R=$(body "$RK" POST /recall -d '{"query":"quillfeather port taken"}') +Q1=$(echo "$R" | jget query_id) +check "recall returns accepted lesson" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$MEM1' for x in d['results']) else 'no'")" +R=$(body "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}") +FB=$(echo "$R" | jget id) +check "feedback -> pinned revision" "1" "$(echo "$R" | jq_ "d['target_revision']")" +check "feedback again -> 200 same id" "200 $FB" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"not_useful\",\"comment\":\"stale\"}") $(body "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"not_useful\"}" | jget id)" +check "feedback by another principal -> 201" "201" "$(code "$VK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" +check "feedback on result not in query -> 404" "404" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MS\",\"usefulness\":\"useful\"}")" +check "feedback from other tenant -> 404" "404" "$(code "$BK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" +check "feedback bad usefulness -> 422" "422" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"meh\"}")" +check "feedback bad query id -> 422" "422" "$(code "$RK" POST /feedback -d "{\"query_id\":\"abc\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" +check "feedback wrong method -> 404 (router has no 405)" "404" "$(code "$RK" GET /feedback)" +curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \ + -d "{\"namespace_id\":\"$NS\",\"title\":\"Runbook\",\"source_uri\":\"kb://rb\",\"format\":\"markdown\",\"content\":\"# Runbook\n\nRestart the quillfeather daemon with the gentle flag.\"}" +R=$(body "$RK" POST /search -d '{"query":"quillfeather daemon gentle"}') +Q2=$(echo "$R" | jget query_id); CH=$(echo "$R" | jq_ "d['results'][0]['chunk_id']" 2>/dev/null) +check "feedback on a search chunk -> 201" "201" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q2\",\"result_id\":\"$CH\",\"usefulness\":\"harmful\"}")" +R=$(body "$RK" POST /context -d "{\"task\":\"quillfeather port\",\"namespace_ids\":[\"$NS\"]}") +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\"}")" + +# ---- 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)" +check "sources of forgotten memory -> 404" "404" "$(code "$RK" GET /memories/$MEM1/sources)" +check "feedback on forgotten result -> 404" "404" "$(code "$RK" POST /feedback -d "{\"query_id\":\"$Q1\",\"result_id\":\"$MEM1\",\"usefulness\":\"useful\"}")" +check "open proposal on forgotten memory rejected" "rejected" "$(body "$VK" GET /candidates/$C8 | jq_ "d['data']['state']")" +check "accepted candidate keeps its history" "accepted" "$(body "$VK" GET /candidates/$C1 | jq_ "d['data']['state']")" + +echo "passed: $PASS failed: $FAIL" +for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done +[ "$FAIL" -eq 0 ]