Browse Source

Merge branch 'phase3-context': documents, context, semantic retrieval, learning loop, export/import, backup/restore, observability

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
graph-relationships
Daniel Covington 19 hours ago
parent
commit
7c14810328
43 changed files with 8751 additions and 752 deletions
  1. +9
    -0
      .gitignore
  2. +35
    -2
      AGENTS.md
  3. +27
    -6
      README.md
  4. +849
    -0
      app/controllers/ApiContextController.asp
  5. +40
    -22
      app/controllers/ApiDocumentsController.asp
  6. +137
    -5
      app/controllers/ApiHealthController.asp
  7. +946
    -0
      app/controllers/ApiLearningController.asp
  8. +51
    -21
      app/controllers/ApiMemoriesController.asp
  9. +1042
    -0
      app/controllers/ApiPortabilityController.asp
  10. +26
    -1
      app/controllers/ErrorController.asp
  11. +3
    -0
      app/controllers/autoload_controllers.asp
  12. +3
    -0
      core/autoload_core.asp
  13. +119
    -45
      core/lib.Api.asp
  14. +3
    -0
      core/lib.ControllerRegistry.asp
  15. +716
    -0
      core/lib.Embeddings.asp
  16. +281
    -194
      core/lib.JsonLite.asp
  17. +284
    -0
      core/lib.Learning.asp
  18. +142
    -0
      core/lib.Observability.asp
  19. +29
    -0
      core/lib.Router.asp
  20. +25
    -6
      core/lib.Search.asp
  21. +1
    -0
      core/mvc.asp
  22. +33
    -0
      db/migrations/20261205110945_create_embedding_index_table.asp
  23. +120
    -0
      db/migrations/20261205113137_create_learning_and_feedback_tables.asp
  24. +44
    -1
      docker-compose.yml
  25. +18
    -0
      public/Default.asp
  26. +2308
    -444
      public/api/memory-v1.openapi.json
  27. +21
    -0
      public/web.config
  28. +286
    -0
      scripts/backup.asp
  29. +18
    -0
      scripts/backup.cmd
  30. +107
    -0
      scripts/embed.asp
  31. +12
    -0
      scripts/embed.cmd
  32. +43
    -0
      scripts/kb.sh
  33. +40
    -0
      scripts/ops.sh
  34. +8
    -0
      scripts/provision.asp
  35. +29
    -0
      scripts/restore.cmd
  36. +12
    -3
      scripts/templates/Api.tpl.asp
  37. +106
    -0
      tests/backup-restore.sh
  38. +99
    -0
      tests/observability.sh
  39. +17
    -2
      tests/phase1-api.sh
  40. +168
    -0
      tests/phase3-context.sh
  41. +222
    -0
      tests/phase3-learning.sh
  42. +145
    -0
      tests/phase3-portability.sh
  43. +127
    -0
      tests/phase3-semantic.sh

+ 9
- 0
.gitignore View File

@@ -8,3 +8,12 @@

# Notes for porting changes upstream (local only)
/UPSTREAM-TODO.txt

# Local knowledge base keys (scripts/kb.sh)
/.amk*.env

# Database backups (scripts/backup.cmd); keep copies somewhere else too
/db/backups/

# Compose variables (AMK_METRICS_TOKEN); local only
/.env

+ 35
- 2
AGENTS.md View File

@@ -35,6 +35,23 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w
- Controllers `ApiMemoriesController`, `ApiSessionsController`, `ApiHealthController` are hand-written (the generators cover one-table CRUD only); routes under `/api/v1/...` are in `public/Default.asp`.
- 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; it also applies usefulness feedback on the current revision, see `ApplyFeedback`). Write paths call `Emb_MarkPending`/`Emb_MarkDelete*` inside their transaction and `Emb_AfterWrite` after commit; new write paths that change memory or chunk text must do the same. `scripts\embed.cmd status|run|reindex`. Regression suite: `bash tests/phase3-semantic.sh`. The `embed-worker` container runs `scripts/embed.asp` (`EMBED_ACTION=worker`) every 30 seconds to retry pending/failed items.
- Learning loop: `ApiLearningController` (session events, `POST /learn`, candidates, review, `GET /memories/:id/sources`, `POST /feedback`) with helpers in `core/lib.Learning.asp`: `Evidence_Class` (validate, resolve and pin evidence), `Mem_Create`/`Mem_Revise`/`Mem_Verify` (memory writes shared with review; inside a transaction), `Mem_ForgetLinked` (called by forget), and `Tel_*` (retrieval telemetry: recall/search/context must record the `query_id` they return and the revision of each result, or feedback cannot reference them). Review needs `verify` and is refused to the author without `admin`. New tenant-scoped tables must also be deleted by `provision purge`. Regression suite: `bash tests/phase3-learning.sh`.
- Portability: `ApiPortabilityController` (`POST /exports`, `POST /imports`). The export format (`agent-memory-export`, `schema_version` 1) is a contract: a new canonical table or column means a new schema version (and an importer for the old one), and the import must keep ids, revisions, timestamps and principal ids, rebuild derived data (content hashes, FTS, `Emb_MarkPending`) and stay all-or-nothing. Regression suite: `bash tests/phase3-portability.sh`.
- Backup/restore: `scripts\backup.cmd backup|verify` and `scripts\restore.cmd <file>` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead.
- Observability: `core/lib.Observability.asp` (included before `lib.Api.asp`). `Api_Send` calls `Obs_Record` once per response (access-log line via `console.log`, counters in `Application`); `MVC_InvokeAction` sets `Obs_Action`, so metric labels are controller actions, never raw paths. A response written without `Api_Send` must call `Obs_Record status` itself (as `ApiHealthController.Metrics` does). Never log bodies, query strings or keys. `GET /api/v1/metrics` needs `AMK_METRICS_TOKEN` (`.env`, git-ignored). Regression suite: `bash tests/observability.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 eight suites (`tests/*.sh`).

### This repo's own knowledge base (dogfooding)

This repo's knowledge base lives on the **production server** (a separate VM running this app; its URL is `AMK_URL` in `.amk.env`), tenant for this repo, namespace `/projects/agent-memory`. Store memories, lessons and documents there. The local container (`localhost:8801`) is for development and the test suites only; do not keep knowledge in it. Settings and keys are in `.amk.env` (git-ignored, local only; never print or commit the keys). Deployment details are a document in the knowledge base (`kb.sh search "deployment VM"`). Use `bash scripts/kb.sh` from Git Bash:

- At the start of a task: `kb.sh context "<task>"` (verified lessons/decisions plus passages from the ingested docs), or `kb.sh search "<question>"` for a quick lookup before reading whole files.
- After learning something non-obvious (a new gotcha, a decision): `kb.sh learn lesson|decision|constraint "<title>" "<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.
- On the Linux server use `bash scripts/ops.sh migrate|provision|embed|backup|verify|restore` (the `.cmd` scripts are Windows-only). Changes reach it by pushing a branch the server then pulls; the server's operator runs the commands there.

### Adding a table end to end (the workflow that was verified)

@@ -156,7 +173,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`).
- **405 and API 404s come from the router.** `Router_Class.Resolve` returns `ErrorController.MethodNotAllowed` (with an `Allow` header) when the path is routed for other methods; `ErrorController` answers `/api/...` requests with the JSON error format and no layout. Routing happens before authentication, so a wrong method is 405 even without a key.
- **`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).
@@ -164,7 +184,20 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o
- **Migrator: one migration per process.** `migrate.cmd up` with two or more pending migrations failed on the second one (`Runtime error: Migrator '800A0002'`; an AxonASP VM panic "assignment to entry in nil map" when reproduced in a plain script). Run `migrate.cmd up` once per pending migration. Even a successful apply/rollback currently ends with `Object required` from `core/helpers.asp` and exit code 1 (reproduced on the original unmodified framework, so not caused by local changes); check `migrate.cmd status` rather than the exit code.
- **Close a result set before running another statement.** Running a query inside a loop over an open G3DB result set hung the request (script timeout), and a write executed while a result set was still open was silently lost (the `provision key` action created no key). Copy the values you need, `rs.Close`, then query/write.
- **G3DB takes at most 8 parameters per statement** ("Too many parameters (12); the maximum is 8"). Split wide INSERTs into an INSERT plus an UPDATE inside one transaction (see `InsertRevision` in `ApiMemoriesController.asp`).
- **Non-BMP characters:** AxonASP strings hold whole code points. `ChrW(128512)` is one character; building it from a UTF-16 surrogate pair stores two U+FFFD. `Api_Utf8Decode` and `JsonLite` (for surrogate-pair `\u` escapes) combine accordingly.
- **Characters above U+FFFF (emoji) cannot be held** on the pinned build (CLI v2.3.42): `ChrW(128512)` raises "Invalid procedure call" (older builds returned one character), and `ChrW(55357) & ChrW(56832)` is written out as CESU-8 (`ED A0 BD ...`), which is invalid UTF-8. `Api_Utf8Decode` and JsonLite therefore flag such code points (raw 4-byte UTF-8 or escaped surrogate pairs) and `Api_ReadBody` answers 422 `unsupported_character`; the generator template does the same. Do not store them as U+FFFD silently.
- **Calling HTTP services from a request works alongside G3DB** (verified with `MSXML2.ServerXMLHTTP` to Ollama and Qdrant, reads and writes before and after, cold first request). Set `SetTimeouts` so a dead service cannot hang the request, never let an HTTP failure fail a database write, and keep large JSON (vectors) as text: slice it with `InStr`/`Split` instead of parsing it with JsonLite.
- **A busy embedding provider must not stall requests.** On the 2-vCPU production VM, a small ingest right after a 312-chunk import hit the 60 s script timeout. The write had committed, but the post-commit indexing kept embedding the tenant's pending backlog while the worker loaded Ollama, so the client got error 4011 for a successful write. Inside web requests each provider/store call now waits at most `EmbeddingTimeoutMs` (10 s) and `Emb_AfterWrite` stops starting batches after `EmbeddingWriteBudgetMs` (8 s), leaving rows pending without using up attempts. Only the CLI worker waits 60 s. Test slow-provider behaviour with `docker pause ollama` (connections hang) as well as `docker stop ollama` (connections refused).
- **Embedding similarity thresholds are model-specific.** With `nomic-embed-text` (and its `search_query: `/`search_document: ` prefixes) relevant pairs scored 0.61-0.67 and unrelated ones up to 0.58, hence `EmbeddingMinScore` 0.6. Re-measure before changing the model, and remember the memory title is part of the embedded (and FTS-indexed) text.
- **`AscW` is signed:** characters U+8000..U+FFFF give negative values, so `AscW(c) > 127` misses them (fixed in `Search_FtsQuery`). The same applies to `CLng("&H" & hex)` for 4-digit hex.
- **`content_hash` is not a content hash.** `memory_revisions.content_hash` is SHA-256 of `namespace|type|title|content` (used for duplicate detection in one namespace). To dedupe the same text across namespaces compare the content itself (as `ApiContextController` does).
- **Agent tooling can rewrite escape sequences.** In this repo's sessions, `\uXXXX` written in a tool command or file edit was sometimes decoded to the real character before bash/curl ran (curl then sent `??`), which looked like a server bug. Produce backslashes at run time in tests (`printf '%su00fc' '\'`, Python `chr(92)`), check test files for unintended non-ASCII bytes, and confirm what curl sends with `--trace-ascii -` before blaming the runtime. The same happened to `\r`, `\b` and `\a` inside Bash heredocs (they became CR, backspace and bell bytes in the written file, for example `db\backups` in Markdown): after scripted edits, check for control bytes with `LC_ALL=C grep -c $'[\x01-\x08\x0b-\x1f]' <file>`, and in shell code prefer `tr -d '[:cntrl:]'`-style classes or octal escapes.
- **Builtins cost time proportional to the string length.** On this build `Len`, `Mid`, `InStr` and friends take time that grows with the length of the string they get (`Len` of 200 KB about 0.4 ms, `InStr` about 5 ms), so a per-character loop over a large string is quadratic and hit the 60 s script timeout (JSON parsing of an import). Process large text in bulk: `VBScript.RegExp` (`Execute` over 450 KB took 30 ms), `Replace`, `Split`, and `G3STRINGBUILDER` (`Append`/`ToString`) instead of `s = s & x` in loops. `core/lib.JsonLite.asp` tokenizes with one RegExp and `Api_Utf8Decode` works on byte runs for this reason.
- **A request that times out keeps running.** After the script timeout the client gets its error, but the script goroutine is detached and carries on, possibly holding an open G3DB transaction; later requests then fail or wait. Restart the container after a timeout during development, and keep long work (imports, rebuilds) well under the limit.
- **RegExp quirks.** `Match.FirstIndex`/`Length` are byte offsets into the UTF-8 text, not character positions (contrary to the manual), so do not `Mid` with them on non-ASCII strings; use `Execute` results' `Value` or `Replace`/`Split` instead. A literal backslash or bracket inside a character class (`[^"\\]`) fails in AxonASP's pattern translation: write `\x5C`, `\x5B`, `\x5D`.
- **`G3AXON.FUNCTIONS` `AxUrlDecode` also turns `+` into a space.** It is used to decode percent-encoded UTF-8 byte runs that cannot contain `+`; do not feed it raw text.
- **Fixed-size array members fail.** `Private m_cnt(7)` in a Class gave "Subscript out of range" when used; declare `Private m_cnt()` and `ReDim m_cnt(7)` in a method.
- **`console.log` lines are decorated.** In the HTTP server they go to stdout (`docker logs`) with ANSI colour codes, a date/time and a marker before the text, and end with the text plus a newline. Write one JSON object per call and extract it with `grep -o '{"log":.*'`. `WScript.Shell` `ExpandEnvironmentStrings` reads the container's environment in the HTTP server too.
- **`VACUUM INTO` works through G3DB** and gives a consistent copy while the server is running (`scripts/backup.asp`). There is no `sqlite3` binary in the image; use the CLI with G3DB for database maintenance. `PRAGMA foreign_keys` is off, so check `PRAGMA foreign_key_check` (the backup verification fails on violations).
- **Run CLI tools as the server user.** The HTTP server runs as `axonasp`; a database file first created by a root `docker exec` was read-only to it ("attempt to write a readonly database"). `gen.cmd`, `migrate.cmd` and `provision.cmd` use `docker exec -u axonasp`.
- **PowerShell splits `read,write` into two arguments.** Quote lists passed to `provision.cmd grant`: `'"read,write"'`.
- **Class member vs local name clash.** Avoid a local `Dim controllerName` inside a class that also has a `ControllerName` property.


+ 27
- 6
README.md View File

@@ -56,21 +56,42 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec
**Done**
- Phase 1: tenants, principals, hashed API keys, namespaces, grants (read/write/delete/verify/admin); memories with revisions, correction (If-Match), retire/forget, idempotency keys, duplicate detection, audit events; sessions with checkpoints; health.
- Phase 2: Markdown/text ingestion with chunking and source locators (`core/lib.Search.asp`), documents/chunks/jobs, lexical search over chunks (FTS5), `POST /recall` over memories, verification (`POST /memories/:id/verifications`), `content_trust` labelling.
- Phase 3 (part): `POST /context` assembles a task briefing under a token budget: constraints loaded by scope (required; 422 `context_budget_exceeded` when they do not fit), working state from a session checkpoint, preferences, disputed items as conflicts, decisions/lessons/knowledge and reference passages by hybrid match, optional unverified items; deduplicated and trust-labelled.
- Phase 3 (part): semantic retrieval. Embeddings from a local Ollama model (`nomic-embed-text`), vectors in Qdrant, both as containers in `docker-compose.yml`. `/recall`, `/search` and `/context` fuse lexical and vector ranks (reciprocal rank fusion) and fall back to lexical with a warning when the provider is off or down. SQLite stays the source of truth: `embedding_index` tracks model, dimensions, revision and status per memory/chunk, writes index after commit (never failing the write), and `scripts\embed.cmd status|run|reindex` catches up or rebuilds. Common English stopwords are dropped from lexical queries. The `embed-worker` container retries pending/failed items every 30 seconds; `GET /health/ready` reports `degraded` (still 200) and the backlog when the provider or vector store is down.
- Phase 3 (part): learning loop. Agents record experiences in a session (`POST /sessions/:id/events`) and propose knowledge with evidence (`POST /learn`: a new memory, or a new revision of `target_memory_id` at `base_revision`). Another principal with `verify` reviews it (`POST /candidates/:id/review`); the author cannot approve its own candidate without `admin`. Accepting creates the memory (an identical active one is reused), or revises the target if it has not changed meanwhile (else 409 `stale_candidate`), copies the evidence with pinned target revisions and, with `"verify": true`, records a verification. `GET /memories/:id/sources` shows evidence and verifications per revision (evidence the caller cannot read is shown as `available: false`, without its id). Recall, search and context return a `query_id` and record the returned results and revisions (the query text is kept only as a hash); `POST /feedback` rates one result (useful, not_useful, incorrect, harmful). Ratings on a result's current revision adjust its rank in recall, search and context (useful raises it, incorrect/harmful halve its score per rating); results show their `feedback` counts and a warning names demoted results. A corrected memory starts without feedback. Forgetting a memory removes its evidence, verifications, feedback and telemetry rows.
- Portability: `POST /exports` writes a canonical JSON document (`format` `agent-memory-export`, `schema_version` 1, SHA-256 `integrity.digest` over the exact `data` text) with every namespace the caller can read, or the `namespace_ids` asked for: memories with all revisions and verifications, documents with revisions and chunks, and evidence links (links to targets the caller cannot read are left out and counted). Ids, revision numbers, timestamps and principal ids are kept. `POST /imports` takes that document unchanged (max 8 MiB): it needs `admin` on every target namespace (matched by path; they must exist), rebuilds content hashes and lexical indexes and queues embeddings, and is all-or-nothing (409 `import_conflict` when an id exists, 422 for a wrong format, `unsupported_schema_version` or `integrity_mismatch`). Re-exporting imported data gives the same `data`. Not in version 1: sessions, experiences, candidates, feedback, telemetry, audit events.
- Backup and restore: `scripts\backup.cmd` (see Operations below).
- Observability: every API response carries `X-Request-Id` (a caller's own `X-Request-Id` of 8-64 characters `[A-Za-z0-9._:-]` is kept for correlation; it also appears in error bodies and audit events) and writes one JSON access-log line to stdout: request id, method, controller action, status, duration, tenant and principal ids. Bodies, query strings and keys are never logged. `GET /api/v1/metrics` serves Prometheus text: request counters and a latency histogram per action (in process memory, reset by a restart), and installation-wide counts of memories, candidates, jobs, embedding index states, retrieval calls (with empty results and total time) and feedback. It needs the `AMK_METRICS_TOKEN` bearer token and answers 404 while that is unset.

**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).

**Tooling**
- `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`.
- `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`).
- Tests (container must be running): `bash tests/phase1-api.sh` (71 checks), `bash tests/phase2-api.sh` (45 checks). Both create and purge their own tenants.
- `scripts/ops.sh`: the same tools for a Linux server (migrate, provision, embed, backup, verify, restore).
- `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model).
- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (44), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802), `bash tests/observability.sh` (25; restarts the container; the metrics checks need `AMK_METRICS_TOKEN`). Each creates and purges its own tenants.

**Next (not started)**
1. Context assembly (`/context`): budgeted, deduplicated, trust-labelled bundle for an agent.
2. Embeddings and hybrid retrieval (needs a decision on the embedding provider).
3. Experiences, candidates and review; feedback (AC-18).
4. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`).
1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`).
2. Management endpoints for namespaces, principals and grants (today only via `provision.cmd`).

## Operations: backup and restore

SQLite (`db/app.sqlite`) is the only source of truth. The Qdrant vectors are derived and rebuilt from it; the Ollama model is downloaded again with `ollama pull`.

- **Backup** (server keeps running): `scripts\backup.cmd backup` writes `db\backups\app-YYYYMMDD-HHMMSS.sqlite` with SQLite `VACUUM INTO` (a consistent, compacted copy), then checks it (`integrity_check`, `foreign_key_check`, latest migration) and compares row counts per table with the live database. The last line is `RESULT: ok` or `RESULT: failed`; trust that line, not the exit code. `db/backups/` is git-ignored and lives on the same disk, so copy the files elsewhere (another disk or machine, object storage) and keep several generations.
- **Verify** a stored copy: `scripts\backup.cmd verify db/backups/<file>.sqlite`.
- **Restore**: `scripts\restore.cmd db/backups/<file>.sqlite`. It stops `axonasp` and `embed-worker`, verifies the backup (nothing changes if that fails), keeps the current database as `db\backups\pre-restore-<timestamp>.sqlite`, copies the backup into place, starts both containers and runs `scripts\embed.cmd reindex`. If the backup is older than the code's schema, run `scripts\migrate.cmd up` afterwards (once per pending migration).
- **Recovery objectives**: the recovery point (RPO) is the backup interval; schedule `scripts\backup.cmd backup` (for example hourly with Task Scheduler or cron) to match the loss you can accept. The recovery time (RTO) is the restore plus the reindex. The drill `bash tests/backup-restore.sh` restores a fresh backup into an isolated container (own db folder, port 8802; the live database is not touched), checks that the restored server returns the same export as the live one, and fails if it takes longer than `RTO_SECONDS` (default 120). Measured here: about 70 to 100 seconds, almost all of it the first start of a new container; `restore.cmd` restarts the existing containers instead. The reindex time grows with the data and does not block reads: lexical retrieval works at once, semantic ranking catches up.
- An export (`POST /exports`) is a portable copy per caller and namespace, not a full backup: it leaves out tenants, principals, keys, grants, sessions, feedback and audit events.

## Configuration

- `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings.
- `public/web.config`: `ConnectionString` (`sqlite:/opt/axonasp/site/db/app.sqlite`), environment and UI settings, and the `Embedding*` / `VectorStoreUrl` settings (`EmbeddingProvider` `none` turns semantic retrieval off). Settings are cached per process: `docker restart axonasp` after editing.
- First start of the semantic stack: `docker compose up -d`, then `docker exec ollama ollama pull nomic-embed-text` once (the model lives in the `ollama-models` volume). The ollama image is about 6 GB.
- Metrics: put `AMK_METRICS_TOKEN=<random, 16+ characters>` in a `.env` file in the repo root (git-ignored; compose reads it), then `docker compose up -d`. Scrape `http://<host>:8801/api/v1/metrics` with `Authorization: Bearer <token>`. Access logs: `docker logs axonasp 2>&1 | grep -o '{"log":"access".*'` (each line has a runtime timestamp prefix); `ApiAccessLog` in `web.config` turns them off.
- `/opt/axonasp/config/axonasp.toml` (inside the container): server settings; any key can be overridden with an environment variable (see `docker-compose.yml`).

## Rules for developers and AI agents


+ 849
- 0
app/controllers/ApiContextController.asp View File

@@ -0,0 +1,849 @@
<%
' ApiContextController: task briefing assembly (spec FR-010, section 9.3, section 10, AC-05, AC-16).
' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (FTS query).
'
' POST /api/v1/context
' {"task", "namespace_ids":[], "session_id", "include":["constraints","preferences","decisions","lessons","knowledge",
' "references","working_state"], "verification_filter":"verified_only|include_unverified",
' "detail_level":"full|summary", "max_context_tokens":100..32000, "max_items":1..50, "max_references":0..20,
' "format":"structured"}
'
' Matching is hybrid (lexical fused with vector similarity, core/lib.Embeddings.asp) when configured, else lexical.
' Assembly (all filtered to active, currently valid memories in namespaces the caller can read):
' constraints every constraint memory in scope, by importance: loaded by scope, not by similarity, and required.
' If they do not fit the budget the request fails with 422 context_budget_exceeded.
' working_state latest checkpoint of session_id (404 when the session is not visible)
' preferences every preference memory in scope, by importance
' conflicts disputed memories among the above and the task matches (always reported, labelled)
' decisions / lessons / knowledge matches of the task (hybrid or lexical), by type
' references matches over current document chunks (untrusted reference content)
' unverified unverified matches, only with verification_filter include_unverified
' The budget is filled in that order; an item that does not fit is skipped and counted. Memories with identical
' content (same text, ignoring case and outer whitespace) appear once. Token counts are estimates (characters / 4) of the included text, not of
' the JSON envelope. Constraints are always returned in full, also with detail_level summary.
Const CTX_CONSTRAINTS = 0
Const CTX_PREFERENCES = 1
Const CTX_CONFLICTS = 2
Const CTX_DECISIONS = 3
Const CTX_LESSONS = 4
Const CTX_KNOWLEDGE = 5
Const CTX_REFERENCES = 6
Const CTX_UNVERIFIED = 7
Const CTX_SECTION_COUNT = 8
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_cTel(), m_cN, m_spec
Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok, m_strategy, m_rankWarning, m_demoted

Public Property Get useLayout()
useLayout = False
End Property

Public Property Let useLayout(v)
End Property

Public Property Get Title()
Title = "Context API"
End Property

'---------------------------------------------------------------
' POST /api/v1/context
'---------------------------------------------------------------
Public Sub Assemble()
Dim body, input, task, fts, budget, maxItems, maxRefs, detail, vf, fmt, requested, allowed, sessionId
Dim incPrefs, incDecisions, incLessons, incKnowledge, incRefs, incState
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, qid, t0

t0 = Timer
If Not Api_Authenticate() Then Exit Sub
body = Api_ReadBody()
If IsEmpty(body) Then Exit Sub
Set input = JsonLite_Parse(body)

'--- validation -----------------------------------------------
m_errs = ""
task = ReqString(input, "task", 2000)
budget = OptInt(input, "max_context_tokens", 4000, 100, 32000)
maxItems = OptInt(input, "max_items", 10, 1, 50)
maxRefs = OptInt(input, "max_references", 5, 0, 20)
detail = LCase("" & OptStringDefault(input, "detail_level", 20, "full"))
If detail <> "full" And detail <> "summary" Then
AddErr "detail_level must be full or summary."
End If
vf = LCase("" & OptStringDefault(input, "verification_filter", 30, "verified_only"))
If vf <> "verified_only" And vf <> "include_unverified" Then
AddErr "verification_filter must be verified_only or include_unverified."
End If
fmt = LCase("" & OptStringDefault(input, "format", 20, "structured"))
If fmt <> "structured" Then
AddErr "format must be structured."
End If
sessionId = OptStringDefault(input, "session_id", 64, "")
If Len(sessionId) > 0 Then
If Not Api_IsId(sessionId) Then
AddErr "session_id must be a valid id."
End If
End If
requested = IdListSql(input, "namespace_ids")

incPrefs = True
incDecisions = True
incLessons = True
incKnowledge = True
incRefs = True
incState = True
If input.HasRaw("include") Then
Dim incArr, inc
incArr = JsonLite_ParseStringArray(input.Raw("include"))
If IsNull(incArr) Then
AddErr "include must be an array of section names."
Else
incPrefs = False
incDecisions = False
incLessons = False
incKnowledge = False
incRefs = False
incState = False
For i = 0 To UBound(incArr)
inc = LCase(Trim(incArr(i)))
Select Case inc
Case "constraints"
' always included
Case "preferences"
incPrefs = True
Case "decisions"
incDecisions = True
Case "lessons"
incLessons = True
Case "knowledge"
incKnowledge = True
Case "references"
incRefs = True
Case "working_state"
incState = True
Case Else
AddErr "include contains an unknown section: " & Left(inc, 40) & "."
End Select
Next
End If
ElseIf input.Exists("include") Then
If Not IsNull(input.Item("include")) Then
AddErr "include must be an array of section names."
End If
End If
If Len(m_errs) > 0 Then
Api_Invalid Split(m_errs, Chr(30))
Exit Sub
End If

fts = Search_FtsQuery(task)
If Len(fts) = 0 Then
Api_Invalid Array("task must contain at least one word.")
Exit Sub
End If

'--- session (checked before any retrieval: an invisible session is a 404) ---
stateJson = "null"
stateTok = 0
If Len(sessionId) > 0 Then
Set rs = DAL().Query("SELECT namespace_id, status, objective FROM sessions WHERE id = ? AND tenant_id = ?", Array(sessionId, Api_TenantId))
If rs.EOF Then
rs.Close
Api_Error 404, "session_not_found", "Session not found."
Exit Sub
End If
sessNs = "" & rs(0)
sessStatus = "" & rs(1)
sessObjective = "" & rs(2)
rs.Close
If Not Api_CanAccessNamespace(sessNs, "read") Then
Api_Error 404, "session_not_found", "Session not found."
Exit Sub
End If
If incState Then
curRev = 0
Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", sessionId)
If Not rs.EOF Then
If Not IsNull(rs(0)) Then
curRev = CLng(rs(0))
End If
End If
rs.Close
txt = "null"
savedAt = "null"
If curRev > 0 Then
Set rs = DAL().Query("SELECT state, created_at FROM checkpoints WHERE session_id = ? AND revision = ?", Array(sessionId, curRev))
If Not rs.EOF Then
txt = "" & rs(0)
savedAt = JsonLite_Quote("" & rs(1))
End If
rs.Close
End If
stateTok = Tokens(sessObjective & vbLf & txt)
stateJson = "{""session_id"":" & JsonLite_Quote(sessionId) & ",""status"":" & JsonLite_Quote(sessStatus) & _
",""objective"":" & JsonLite_Quote(sessObjective) & ",""revision"":" & curRev & ",""state"":" & txt & _
",""saved_at"":" & savedAt & ",""token_estimate"":" & stateTok & "}"
End If
End If

allowed = Api_AllowedNamespaceIds("read")
If Len(allowed) > 0 And Len(requested) > 0 Then
allowed = IntersectIds(allowed, requested)
End If

m_cN = 0
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 = ""
m_demoted = 0
m_dupes = 0
m_unverifiedExcluded = 0
policiesCapped = False
now_ = Api_Now()

If Len(allowed) > 0 Then
'--- 1. policies: constraints and preferences, by scope ------------------
sql = CtxMemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
"AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _
"AND r.verification_status <> 'rejected' AND m.type IN ('constraint','preference') " & _
"ORDER BY CASE m.type WHEN 'constraint' THEN 0 ELSE 1 END, COALESCE(r.importance, 0) DESC, m.updated_at DESC LIMIT " & (CTX_MAX_POLICIES + 1)
Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
policyCount = 0
Do While Not rs.EOF
policyCount = policyCount + 1
If policyCount > CTX_MAX_POLICIES Then
policiesCapped = True
Exit Do
End If
If "" & rs(2) = "constraint" Then
AddMemory rs, CTX_CONSTRAINTS, vf, "full", 0
ElseIf incPrefs Then
AddMemory rs, CTX_PREFERENCES, vf, detail, 0
End If
rs.MoveNext
Loop
rs.Close

'--- 2. memory matches (lexical, fused with semantic when configured) ----------
If incDecisions Or incLessons Or incKnowledge Then
Set ranker = New Ranker_Class
ranker.Run "memory", fts, task, Api_TenantId, allowed
NoteRanker ranker
n = ranker.Count
If n > 0 Then
ReDim ids(n - 1)
ReDim scores(n - 1)
For i = 0 To n - 1
ids(i) = ranker.IdAt(i)
scores(i) = -ranker.ScoreAt(i)
Next
End If
idList = IdSqlList(ids, n)
If Len(idList) > 0 Then
' Read the canonical rows (closing the result set), then add them in rank order.
sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _
"AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _
"AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')"
Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_))
Dim rowsTmp
rowsTmp = Empty
If Not rs.EOF Then
rowsTmp = rs.GetRows()
End If
rs.Close
If Not IsEmpty(rowsTmp) Then
' GetRows is (column, row); walk the ranks and pick the matching row
For i = 0 To n - 1
For j = 0 To UBound(rowsTmp, 2)
If "" & rowsTmp(0, j) = ids(i) Then
sec = TypeSection("" & rowsTmp(2, j))
If sec = CTX_DECISIONS And Not incDecisions Then
sec = -1
ElseIf sec = CTX_LESSONS And Not incLessons Then
sec = -1
ElseIf sec = CTX_KNOWLEDGE And Not incKnowledge Then
sec = -1
End If
If sec >= 0 Then
AddMemoryRow rowsTmp, j, sec, vf, detail, -CDbl(scores(i))
End If
Exit For
End If
Next
Next
End If
End If
End If

'--- 3. reference passages ------------------------------------------------
If incRefs And maxRefs > 0 Then
Set ranker = New Ranker_Class
ranker.Run "chunk", fts, task, Api_TenantId, allowed
NoteRanker ranker
n = ranker.Count
If n > 0 Then
ReDim ids(n - 1)
ReDim scores(n - 1)
For i = 0 To n - 1
ids(i) = ranker.IdAt(i)
scores(i) = -ranker.ScoreAt(i)
Next
End If
idList = IdSqlList(ids, n)
If Len(idList) > 0 Then
Dim chunkRows
chunkRows = Empty
sql = "SELECT c.id, c.document_id, c.document_revision, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, d.namespace_id, d.title, d.source_uri " & _
"FROM chunks c JOIN documents d ON d.id = c.document_id 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)
If Not rs.EOF Then
chunkRows = rs.GetRows()
End If
rs.Close
If Not IsEmpty(chunkRows) Then
refSeen = Chr(31)
cap = 0
For i = 0 To n - 1
If cap >= maxRefs Then
Exit For
End If
For j = 0 To UBound(chunkRows, 2)
If "" & chunkRows(0, j) = ids(i) Then
txt = "" & chunkRows(4, j)
If InStr(refSeen, Chr(31) & txt & Chr(31)) > 0 Then
m_dupes = m_dupes + 1
Else
refSeen = refSeen & txt & Chr(31)
json = RefJson(chunkRows, j, detail, -CDbl(scores(i)))
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
End If
Next
Next
End If
End If
End If
End If

'--- budget ---------------------------------------------------------------------
requiredTok = 0
For i = 0 To m_cN - 1
If m_cSec(i) = CTX_CONSTRAINTS Then
requiredTok = requiredTok + m_cTok(i)
End If
Next
If requiredTok > budget Then
Api_Audit "context.assemble", "context", "", "budget_exceeded"
Api_Send 422, "{""error"":{""code"":""context_budget_exceeded"",""message"":" & _
JsonLite_Quote("The applicable constraints need about " & requiredTok & " tokens, more than max_context_tokens (" & budget & "). Raise the budget or narrow namespace_ids.") & _
",""required_tokens"":" & requiredTok & ",""max_context_tokens"":" & budget & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}"
Exit Sub
End If

ReDim outSec(CTX_SECTION_COUNT - 1)
ReDim cnt(CTX_SECTION_COUNT - 1)
For i = 0 To CTX_SECTION_COUNT - 1
outSec(i) = ""
cnt(i) = 0
Next
used = requiredTok
omittedBudget = 0
omittedLimit = 0
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

warnings = ""
If stateTok > 0 Then
If used + stateTok <= budget Then
used = used + stateTok
Else
stateJson = "null"
omittedBudget = omittedBudget + 1
AddWarning warnings, "working_state did not fit the budget and was left out; restore it with GET /sessions/{id}/state"
End If
End If

For sec = CTX_PREFERENCES To CTX_SECTION_COUNT - 1
If sec = CTX_PREFERENCES Then
cap = 50
ElseIf sec = CTX_REFERENCES Then
cap = maxRefs
Else
cap = maxItems
End If
For i = 0 To m_cN - 1
If m_cSec(i) = sec Then
If cnt(sec) >= cap Then
omittedLimit = omittedLimit + 1
ElseIf used + m_cTok(i) > budget Then
omittedBudget = omittedBudget + 1
Else
used = used + m_cTok(i)
AppendTo outSec, cnt, sec, m_cJson(i)
AddTel i
End If
End If
Next
Next

complete = True
If policiesCapped Then
complete = False
AddWarning warnings, "more than " & CTX_MAX_POLICIES & " constraint/preference memories are in scope; only the most important were considered, so the briefing is incomplete. Narrow namespace_ids."
End If
truncated = (omittedBudget > 0)
If omittedBudget > 0 Then
AddWarning warnings, omittedBudget & " item(s) left out to fit max_context_tokens"
End If
If m_unverifiedExcluded > 0 Then
AddWarning warnings, m_unverifiedExcluded & " unverified item(s) excluded; use verification_filter include_unverified to see them"
End If
If cnt(CTX_CONFLICTS) > 0 Then
AddWarning warnings, cnt(CTX_CONFLICTS) & " disputed item(s) included under conflicts; do not rely on them without checking"
End If
If Len(allowed) = 0 Then
AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty"
End If
If m_demoted > 0 Then
AddWarning warnings, m_demoted & " matched item(s) ranked lower because of negative feedback on their current revision"
End If
If Len(m_rankWarning) > 0 Then
AddWarning warnings, m_rankWarning
End If

' 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)) & "}" & _
",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}"
out = out & ",""constraints"":[" & outSec(CTX_CONSTRAINTS) & "]"
If incState Then
out = out & ",""working_state"":" & stateJson
End If
If incPrefs Then
out = out & ",""preferences"":[" & outSec(CTX_PREFERENCES) & "]"
End If
out = out & ",""conflicts"":[" & outSec(CTX_CONFLICTS) & "]"
If incDecisions Then
out = out & ",""decisions"":[" & outSec(CTX_DECISIONS) & "]"
End If
If incLessons Then
out = out & ",""lessons"":[" & outSec(CTX_LESSONS) & "]"
End If
If incKnowledge Then
out = out & ",""knowledge"":[" & outSec(CTX_KNOWLEDGE) & "]"
End If
If incRefs Then
out = out & ",""references"":[" & outSec(CTX_REFERENCES) & "]"
End If
If vf = "include_unverified" Then
out = out & ",""unverified"":[" & outSec(CTX_UNVERIFIED) & "]"
End If
out = out & ",""warnings"":[" & warnings & "]}"

Api_Audit "context.assemble", "context", "", "ok"
Api_Send 200, out
End Sub

'===============================================================
' Helpers
'===============================================================
' Columns relied on by AddMemory / AddMemoryRow:
' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance,
' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until
' Strategy/warning of the last ranking (hybrid unless semantic retrieval was unavailable for any section)
Private Sub NoteRanker(r)
m_demoted = m_demoted + r.Demoted
If Len(r.Warning) > 0 Then
m_rankWarning = r.Warning
m_strategy = "lexical"
ElseIf Len(m_rankWarning) = 0 Then
m_strategy = r.Strategy
End If
End Sub

Private Function CtxMemorySelect()
CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _
"r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _
"FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision"
End Function

Private Function TypeSection(t)
Select Case t
Case "decision"
TypeSection = CTX_DECISIONS
Case "lesson"
TypeSection = CTX_LESSONS
Case Else
TypeSection = CTX_KNOWLEDGE
End Select
End Function

' Copies one result-set row into an array and hands it to AddMemoryRow (single code path for both sources).
Private Sub AddMemory(rs, sec, vf, detail, score)
Dim row(14, 0), k
For k = 0 To 14
row(k, 0) = rs(k)
Next
AddMemoryRow row, 0, sec, vf, detail, score
End Sub

' rows is GetRows-shaped (column, row). Sorts the memory into its section by verification state and dedupes by content.
Private Sub AddMemoryRow(rows, j, sec, vf, detail, score)
Dim st, key, json, target
st = "" & rows(10, j)
target = sec
If st = "disputed" Then
target = CTX_CONFLICTS
ElseIf st <> "verified" Then
If vf = "include_unverified" Then
target = CTX_UNVERIFIED
Else
m_unverifiedExcluded = m_unverifiedExcluded + 1
Exit Sub
End If
End If
' The stored content_hash also covers namespace, type and title, so the same text in two namespaces has two
' hashes. Dedupe on the normalized content instead.
key = LCase(Trim("" & rows(6, j)))
If InStr(m_seen, Chr(31) & key & Chr(31)) > 0 Then
m_dupes = m_dupes + 1
Exit Sub
End If
m_seen = m_seen & key & Chr(31)
json = MemJson(rows, j, detail, score, st, (sec = CTX_CONSTRAINTS))
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)
Dim s, bodyText, trust
If detail = "summary" Then
If IsNull(rows(5, j)) Then
bodyText = "" & rows(6, j)
If Len(bodyText) > 240 Then
bodyText = Left(bodyText, 240) & "..."
End If
Else
bodyText = "" & rows(5, j)
End If
Else
bodyText = "" & rows(6, j)
End If
m_lastTok = Tokens("" & rows(4, j) & vbLf & bodyText)
Select Case st
Case "verified"
trust = "verified_memory"
Case "disputed"
trust = "disputed_memory"
Case Else
trust = "unverified_memory"
End Select
s = "{""id"":" & JsonLite_Quote("" & rows(0, j)) & ",""revision"":" & CLng(rows(3, j)) & ",""type"":" & JsonLite_Quote("" & rows(2, j)) & _
",""namespace_id"":" & JsonLite_Quote("" & rows(1, j)) & ",""title"":" & JsonLite_Quote("" & rows(4, j))
If detail = "summary" Then
s = s & ",""summary"":" & JsonLite_Quote(bodyText)
Else
s = s & ",""content"":" & JsonLite_Quote(bodyText)
End If
s = s & ",""verification_status"":" & JsonLite_Quote(st) & ",""content_trust"":" & JsonLite_Quote(trust)
If isPolicy Then
If st = "verified" Then
s = s & ",""authority"":""policy"""
End If
End If
s = s & ",""tags"":" & JRaw(rows(7, j), "[]") & ",""confidence"":" & JNum(rows(8, j)) & ",""importance"":" & JNum(rows(9, j))
If score <> 0 Then
s = s & ",""relevance_score"":" & JsonLite_Num(score)
End If
s = s & ",""valid_until"":" & JStr(rows(14, j)) & ",""provenance"":{""created_by"":" & JsonLite_Quote("" & rows(12, j)) & _
",""updated_at"":" & JsonLite_Quote("" & rows(13, j)) & "},""token_estimate"":" & m_lastTok & "}"
MemJson = s
End Function

' Chunk row columns: 0 id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end,
' 8 namespace id, 9 title, 10 source uri
Private Function RefJson(rows, j, detail, score)
Dim txt, s
txt = "" & rows(4, j)
If detail = "summary" Then
If Len(txt) > 240 Then
txt = Left(txt, 240) & "..."
End If
End If
m_lastTok = Tokens(txt)
s = "{""chunk_id"":" & JsonLite_Quote("" & rows(0, j)) & ",""document_id"":" & JsonLite_Quote("" & rows(1, j)) & _
",""document_title"":" & JsonLite_Quote("" & rows(9, j)) & ",""source_uri"":" & JStr(rows(10, j)) & _
",""document_revision"":" & CLng(rows(2, j)) & ",""ordinal"":" & CLng(rows(3, j)) & ",""heading_path"":" & JStr(rows(5, j)) & _
",""locator"":{""start"":" & CLng(rows(6, j)) & ",""end"":" & CLng(rows(7, j)) & "},""namespace_id"":" & JsonLite_Quote("" & rows(8, j)) & _
",""relevance_score"":" & JsonLite_Num(score) & ",""content"":" & JsonLite_Quote(txt) & _
",""content_trust"":""untrusted_reference"",""token_estimate"":" & m_lastTok & "}"
RefJson = s
End Function

' 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) & ","
End If
outSec(sec) = outSec(sec) & json
cnt(sec) = cnt(sec) + 1
End Sub

Private Sub AddWarning(warnings, text)
If Len(warnings) > 0 Then
warnings = warnings & ","
End If
warnings = warnings & JsonLite_Quote(text)
End Sub

' Token estimate for included text: characters / 4, rounded up (declared as estimate_chars_div_4)
Private Function Tokens(text)
Tokens = Int((Len(text) + 3) / 4)
End Function

' 'id1','id2' for the first n valid ids
Private Function IdSqlList(ids, n)
Dim i, out
out = ""
For i = 0 To n - 1
If Api_IsId(ids(i)) Then
If Len(out) > 0 Then
out = out & ","
End If
out = out & "'" & ids(i) & "'"
End If
Next
IdSqlList = out
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

' Optional string with a default when absent or null
Private Function OptStringDefault(input, name, maxLen, dflt)
Dim v
OptStringDefault = dflt
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
OptStringDefault = v
End Function

' Optional whole number in lo..hi with a default when absent or null
Private Function OptInt(input, name, dflt, lo, hi)
Dim v
OptInt = dflt
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."
Exit Function
End If
If v <> Int(v) Or v < lo Or v > hi Then
AddErr name & " must be a whole number between " & lo & " and " & hi & "."
Exit Function
End If
OptInt = CLng(v)
End Function

Private Function IdListSql(input, name)
Dim arr, i, out
IdListSql = ""
If Not input.HasRaw(name) Then
If input.Exists(name) Then
If Not IsNull(input.Item(name)) Then
AddErr name & " must be an array of ids."
End If
End If
Exit Function
End If
arr = JsonLite_ParseStringArray(input.Raw(name))
If IsNull(arr) Then
AddErr name & " must be an array of ids."
Exit Function
End If
out = ""
For i = 0 To UBound(arr)
If Not Api_IsId(arr(i)) Then
AddErr name & " must contain valid ids."
Exit Function
End If
If Len(out) > 0 Then
out = out & ","
End If
out = out & "'" & arr(i) & "'"
Next
If Len(out) = 0 Then
AddErr name & " must not be empty when given."
End If
IdListSql = out
End Function

Private Function IntersectIds(allowed, requested)
Dim a, i, out
a = Split(allowed, ",")
out = ""
For i = 0 To UBound(a)
If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then
If Len(out) > 0 Then
out = out & ","
End If
out = out & a(i)
End If
Next
IntersectIds = out
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 "assemble" : Assemble
Case Else
Err.Raise 438, "ApiContextController_Class", "Action '" & actionName & "' not found"
End Select
End Sub

End Class

Dim ApiContextController_Class__Singleton
Function ApiContextController()
If IsEmpty(ApiContextController_Class__Singleton) Then
Set ApiContextController_Class__Singleton = New ApiContextController_Class
End If
Set ApiContextController = ApiContextController_Class__Singleton
End Function

' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller)
Sub ApiContextController_Invoke(actionName, args)
ApiContextController().Invoke actionName, args
End Sub
%>

+ 40
- 22
app/controllers/ApiDocumentsController.asp View File

@@ -140,6 +140,7 @@ Class ApiDocumentsController_Class
End If
Else
DAL().Execute "DELETE FROM chunks_fts WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(docId, curRev)
Emb_MarkDeleteChunks docId, curRev
End If
DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & revNo & ", ?, ?, " & Len(norm) & ", " & Chunk_Count & ", ?, ?)", _
Array(Api_NewId(), docId, hash, norm, Api_PrincipalId, ts)
@@ -149,6 +150,7 @@ Class ApiDocumentsController_Class
Array(chunkId, docId, Chunk_Text(i), HeadingOrNull(Chunk_Heading(i)), ts)
DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", _
Array(Chunk_Text(i), chunkId, Api_TenantId, nsId)
Emb_MarkPending "chunk", chunkId, Api_TenantId, nsId, revNo
Next
If revNo > 1 Then
DAL().Execute "UPDATE documents SET current_revision = " & revNo & ", title = ?, format = ?, updated_at = ? WHERE id = ?", Array(title, fmt, ts, docId)
@@ -172,6 +174,7 @@ Class ApiDocumentsController_Class
End If
On Error GoTo 0

Emb_AfterWrite Api_TenantId, 64
Api_Audit "document.ingest", "document", docId, "ok"
Response.AddHeader "Location", "/api/v1/documents/" & docId
Api_Send 201, resp
@@ -297,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
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
@@ -333,33 +337,34 @@ 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

' Step 1: ranked candidate chunk ids from the index (tenant filtered); step 2: join canonical rows, apply
' the namespace and current-revision filters. The first result set is closed before the second query.
Set rs = DAL().Query("SELECT chunk_id, bm25(chunks_fts) FROM chunks_fts WHERE chunks_fts MATCH ? AND tenant_id = ? ORDER BY bm25(chunks_fts) LIMIT 300", Array(fts, Api_TenantId))
n = 0
ReDim ids(63)
ReDim scores(63)
Do While Not rs.EOF
If n > UBound(ids) Then
ReDim Preserve ids(n * 2)
ReDim Preserve scores(n * 2)
End If
ids(n) = "" & rs(0)
scores(n) = rs(1)
n = n + 1
rs.MoveNext
Loop
rs.Close

' Step 1: ranked candidate chunk ids (lexical, fused with semantic when configured; tenant filtered);
' step 2: join canonical rows, apply the namespace and current-revision filters.
Set ranker = New Ranker_Class
ranker.Run "chunk", fts, query, Api_TenantId, allowed
n = ranker.Count
warnJson = ""
If Len(ranker.Warning) > 0 Then
warnJson = JsonLite_Quote(ranker.Warning)
End If
If n = 0 Then
Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[],""warnings"":[]}"
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)
ReDim scores(n - 1)
For i = 0 To n - 1
ids(i) = ranker.IdAt(i)
scores(i) = -ranker.ScoreAt(i) ' ChunkJson negates again
Next

idList = ""
For i = 0 To n - 1
@@ -371,10 +376,15 @@ 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))
If Len(ranker.FeedbackAt(j)) > 0 Then
rowJson(j) = Left(rowJson(j), Len(rowJson(j)) - 1) & ",""feedback"":" & ranker.FeedbackAt(j) & "}"
End If
revs(j) = CLng(rs(2))
Exit For
End If
Next
@@ -390,10 +400,18 @@ 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
If ranker.Demoted > 0 Then
If Len(warnJson) > 0 Then
warnJson = warnJson & ","
End If
warnJson = warnJson & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback")
End If
Tel_Record qid, "search", ranker.Strategy, query, spec, t0
Api_Audit "document.search", "search", "", "ok"
Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[]}"
Api_Send 200, "{""query_id"":" & JsonLite_Quote(qid) & ",""strategy"":" & JsonLite_Quote(ranker.Strategy) & ",""content_trust"":""untrusted_reference"",""results"":[" & out & "],""warnings"":[" & warnJson & "]}"
End Sub

'===============================================================


+ 137
- 5
app/controllers/ApiHealthController.asp View File

@@ -2,7 +2,13 @@
' 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
' GET /api/v1/metrics Metrics Prometheus text: request counters and latency (lib.Observability.asp) plus
' installation-wide gauges (memories, candidates, jobs, embedding index,
' retrieval and feedback totals; counts only, never content or ids). Needs
' Authorization: Bearer <AMK_METRICS_TOKEN> (environment variable of the
' container, 16+ characters); while it is unset the endpoint answers 404.
Class ApiHealthController_Class
Public Property Get useLayout()
useLayout = False
@@ -19,9 +25,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,19 +39,141 @@ 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

Public Sub Metrics()
Dim sh, token, auth, out, msg
Set sh = CreateObject("WScript.Shell")
token = sh.ExpandEnvironmentStrings("%AMK_METRICS_TOKEN%")
If token = "%AMK_METRICS_TOKEN%" Then
token = ""
End If
If Len(token) < 16 Then
Api_NotFound
Exit Sub
End If
auth = "" & Request.ServerVariables("HTTP_AUTHORIZATION")
' Compare digests, so the time taken does not depend on how much of the token matched.
If Api_Sha256(auth) <> Api_Sha256("Bearer " & token) Then
Response.AddHeader "WWW-Authenticate", "Bearer"
Api_Error 401, "unauthorized", "A valid metrics token is required."
Exit Sub
End If

out = Obs_RequestMetrics()
On Error Resume Next
out = out & Gauge("amk_memories", "Memories by lifecycle status.", "gauge", _
"SELECT lifecycle_status, COUNT(*) FROM memories GROUP BY 1", "status")
out = out & Gauge("amk_learning_candidates", "Learning candidates by state.", "gauge", _
"SELECT state, COUNT(*) FROM learning_candidates GROUP BY 1", "state")
out = out & Gauge("amk_jobs", "Ingestion jobs by state.", "gauge", _
"SELECT state, COUNT(*) FROM jobs GROUP BY 1", "state")
out = out & Gauge("amk_embedding_index", "Embedding index entries by status.", "gauge", _
"SELECT status, COUNT(*) FROM embedding_index GROUP BY 1", "status")
out = out & Gauge("amk_retrieval_queries_total", "Recorded retrieval calls by operation and strategy.", "counter", _
"SELECT operation, strategy, COUNT(*) FROM retrieval_queries GROUP BY 1, 2", "operation,strategy")
out = out & Gauge("amk_retrieval_empty_total", "Recorded retrieval calls that returned no results.", "counter", _
"SELECT operation, COUNT(*) FROM retrieval_queries WHERE result_count = 0 GROUP BY 1", "operation")
out = out & Gauge("amk_retrieval_duration_ms_sum", "Total recorded retrieval time in milliseconds.", "counter", _
"SELECT operation, SUM(duration_ms) FROM retrieval_queries GROUP BY 1", "operation")
out = out & Gauge("amk_feedback_total", "Usefulness feedback by rating.", "counter", _
"SELECT usefulness, COUNT(*) FROM feedback GROUP BY 1", "usefulness")
If Err.Number <> 0 Then
msg = Err.Description
Err.Clear
On Error GoTo 0
Api_Error 500, "internal_error", "Metrics query failed: " & msg
Exit Sub
End If
On Error GoTo 0

Response.Clear
Response.Status = "200 OK"
Response.ContentType = "text/plain; version=0.0.4"
Response.Charset = "utf-8"
Response.AddHeader "X-Request-Id", Api_RequestId()
Response.AddHeader "Cache-Control", "no-store"
Response.Write out
Obs_Record 200
End Sub

' One metric family from a grouped query: the label columns first, the value last.
Private Function Gauge(name, help, kind, sql, labelNames)
Dim rs, rows, names, i, r, out, labels, v
names = Split(labelNames, ",")
Set rs = DAL().Query(sql, Empty)
rows = Empty
If Not rs.EOF Then
rows = rs.GetRows()
End If
rs.Close
out = "# HELP " & name & " " & help & vbLf & "# TYPE " & name & " " & kind & vbLf
If IsArray(rows) Then
For r = 0 To UBound(rows, 2)
labels = ""
For i = 0 To UBound(names)
If i > 0 Then
labels = labels & ","
End If
labels = labels & names(i) & "=""" & Obs_Label(rows(i, r)) & """"
Next
v = rows(UBound(names) + 1, r)
If IsNull(v) Then
v = 0
End If
out = out & name & "{" & labels & "} " & v & vbLf
Next
End If
Gauge = out
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 "live" : Live
Case "ready" : Ready
Case "metrics" : Metrics
Case Else
Err.Raise 438, "ApiHealthController_Class", "Action '" & actionName & "' not found"
End Select


+ 946
- 0
app/controllers/ApiLearningController.asp View File

@@ -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
%>

+ 51
- 21
app/controllers/ApiMemoriesController.asp View File

@@ -103,6 +103,7 @@ Class ApiMemoriesController_Class
"VALUES (?, ?, ?, ?, 1, 'active', ?, ?, ?)", Array(memId, Api_TenantId, nsId, memType, Api_PrincipalId, ts, ts)
InsertRevision revId, memId, 1, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, "created", ts
Search_IndexMemory memId, 1, Api_TenantId, nsId, title, content, tagsRaw
Emb_MarkPending "memory", memId, Api_TenantId, nsId, 1
resp = "{""id"":" & JsonLite_Quote(memId) & ",""revision"":1,""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed"",""duplicate"":false}"
StoreIdem idemKey, reqHash, 201, resp
If Err.Number <> 0 Then
@@ -119,6 +120,7 @@ Class ApiMemoriesController_Class
End If
On Error GoTo 0

Emb_AfterWrite Api_TenantId, 8
Api_Audit "memory.remember", "memory", memId, "ok"
Response.AddHeader "Location", "/api/v1/memories/" & memId
Api_Send 201, resp
@@ -379,6 +381,7 @@ Class ApiMemoriesController_Class
DAL().BeginTransaction
InsertRevision Api_NewId(), id, newRev, title, summary, content, attrRaw, tagsRaw, confidence, importance, hash, reason, ts
Search_IndexMemory id, newRev, Api_TenantId, nsId, title, content, tagsRaw
Emb_MarkPending "memory", id, Api_TenantId, nsId, newRev
DAL().Execute "UPDATE memories SET current_revision = ?, updated_at = ? WHERE id = ? AND tenant_id = ? AND current_revision = ?", _
Array(newRev, ts, id, Api_TenantId, curRev)
If Err.Number <> 0 Then
@@ -395,6 +398,7 @@ Class ApiMemoriesController_Class
End If
On Error GoTo 0

Emb_AfterWrite Api_TenantId, 8
Api_Audit "memory.correct", "memory", id, "ok"
Response.AddHeader "ETag", """" & newRev & """"
resp = "{""id"":" & JsonLite_Quote(id) & ",""revision"":" & newRev & ",""status"":""active"",""verification_status"":""unverified"",""indexing_status"":""lexical_indexed""}"
@@ -429,6 +433,8 @@ Class ApiMemoriesController_Class
On Error Resume Next
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
@@ -440,6 +446,7 @@ Class ApiMemoriesController_Class
DAL().CommitTransaction
On Error GoTo 0

Emb_AfterWrite Api_TenantId, 8
Api_Audit "memory.forget", "memory", id, "ok"
Api_Send 200, "{""deleted"":true,""id"":" & JsonLite_Quote(id) & "}"
End Sub
@@ -599,13 +606,15 @@ Class ApiMemoriesController_Class
'---------------------------------------------------------------
' POST /api/v1/recall
' {"query","types":[],"namespace_ids":[],"verification_filter":"verified_only|include_unverified","max_results","detail_level":"full|summary"}
' Lexical (FTS5/bm25) retrieval over active memories the caller can read. Trusted retrieval is the default, so
' Hybrid retrieval (FTS5/bm25 fused with vector similarity when configured, see core/lib.Embeddings.asp) over
' active memories the caller can read. Trusted retrieval is the default, so
' unverified memories are left out unless asked for (they are labelled when included).
'---------------------------------------------------------------
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
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
@@ -646,26 +655,30 @@ 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

Set rs = DAL().Query("SELECT memory_id, bm25(memories_fts) FROM memories_fts WHERE memories_fts MATCH ? AND tenant_id = ? ORDER BY bm25(memories_fts) LIMIT 300", Array(fts, Api_TenantId))
n = 0
ReDim ids(63)
ReDim scores(63)
Do While Not rs.EOF
If n > UBound(ids) Then
ReDim Preserve ids(n * 2)
ReDim Preserve scores(n * 2)
End If
ids(n) = "" & rs(0)
scores(n) = rs(1)
n = n + 1
rs.MoveNext
Loop
rs.Close
' Lexical + (when configured) semantic candidates, fused; scores are negated here to match the output below
Set ranker = New Ranker_Class
ranker.Run "memory", fts, query, Api_TenantId, allowed
n = ranker.Count
If n > 0 Then
ReDim ids(n - 1)
ReDim scores(n - 1)
For i = 0 To n - 1
ids(i) = ranker.IdAt(i)
scores(i) = -ranker.ScoreAt(i)
Next
End If
warnings = ""
If Len(ranker.Warning) > 0 Then
warnings = JsonLite_Quote(ranker.Warning)
End If

out = ""
count = 0
@@ -684,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
@@ -693,7 +707,12 @@ Class ApiMemoriesController_Class
If ids(j) = "" & rs(0) Then
v = MemoryJson(rs, (detail = "summary"))
If detail = "summary" Then v = SummaryOnly(v, rs)
rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j))) & "}"
rowJson(j) = Left(v, Len(v) - 1) & ",""relevance_score"":" & JsonLite_Num(-CDbl(scores(j)))
If Len(ranker.FeedbackAt(j)) > 0 Then
rowJson(j) = rowJson(j) & ",""feedback"":" & ranker.FeedbackAt(j)
End If
rowJson(j) = rowJson(j) & "}"
revs(j) = CLng(rs(10))
Exit For
End If
Next
@@ -707,14 +726,25 @@ 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
If excluded > 0 Then
warnings = "[""semantic retrieval is not configured; results are lexical only"",""" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them""]"
If Len(warnings) > 0 Then
warnings = warnings & ","
End If
warnings = warnings & """" & excluded & " unverified match(es) excluded; use verification_filter include_unverified to see them"""
End If
If ranker.Demoted > 0 Then
If Len(warnings) > 0 Then
warnings = warnings & ","
End If
warnings = warnings & JsonLite_Quote(ranker.Demoted & " result(s) ranked lower because of negative feedback on their current revision")
End If
Tel_Record qid, "recall", ranker.Strategy, query, spec, t0
Api_Audit "memory.recall", "search", "", "ok"
Api_Send 200, "{""query_id"":" & JsonLite_Quote("qry-" & Api_NewId()) & ",""strategy"":""lexical"",""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

'===============================================================


+ 1042
- 0
app/controllers/ApiPortabilityController.asp
File diff suppressed because it is too large
View File


+ 26
- 1
app/controllers/ErrorController.asp View File

@@ -6,10 +6,19 @@ Class ErrorController_Class
m_useLayout = True
End Sub

' JSON API requests (/api/...) get JSON errors without the HTML layout
Public Property Get useLayout
useLayout = m_useLayout
If IsApiRequest() Then
useLayout = False
Else
useLayout = m_useLayout
End If
End Property

Private Function IsApiRequest()
IsApiRequest = (LCase(Left(GetRequestPath(), 5)) = "/api/")
End Function

Public Property Let useLayout(v)
m_useLayout = v
End Property
@@ -19,18 +28,34 @@ Class ErrorController_Class
End Sub

Public Sub NotFound()
If IsApiRequest() Then
Api_Error 404, "not_found", "No such endpoint."
Exit Sub
End If
Response.Status = "404 Not Found"
%>
<!--#include file="../views/Error/NotFound.asp" -->
<%
End Sub

' The path exists, but not for this HTTP method (resolved by Router_Class.AllowedMethods)
Public Sub MethodNotAllowed(allow)
If IsApiRequest() Then
Api_Error 405, "method_not_allowed", "Use one of: " & allow & "."
Else
Response.Status = "405 Method Not Allowed"
Response.Write "<p>Method not allowed. Use one of: " & Server.HTMLEncode(allow) & ".</p>"
End If
Response.AddHeader "Allow", allow
End Sub

' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls),
' called through <Name>Controller_Invoke at the bottom of this file.
Public Sub Invoke(actionName, args)
Select Case LCase(actionName)
Case "index" : Index
Case "notfound" : NotFound
Case "methodnotallowed" : MethodNotAllowed args(0)
Case Else
Err.Raise 438, "ErrorController_Class", "Action '" & actionName & "' not found"
End Select


+ 3
- 0
app/controllers/autoload_controllers.asp View File

@@ -5,3 +5,6 @@
<!--#include file="ApiSessionsController.asp" -->
<!--#include file="ApiHealthController.asp" -->
<!--#include file="ApiDocumentsController.asp" -->
<!--#include file="ApiContextController.asp" -->
<!--#include file="ApiLearningController.asp" -->
<!--#include file="ApiPortabilityController.asp" -->

+ 3
- 0
core/autoload_core.asp View File

@@ -16,8 +16,11 @@
<!--#include file="../core/lib.crypto.helper.asp"-->
<!--#include file="../core/lib.Enumerable.asp"-->
<!--#include file="../core/lib.JsonLite.asp"-->
<!--#include file="../core/lib.Observability.asp"-->
<!--#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"-->

+ 119
- 45
core/lib.Api.asp View File

@@ -40,8 +40,17 @@ Function Api_Now()
End Function

Function Api_RequestId()
Dim re, h
If Len(Api_RequestIdValue) = 0 Then
Api_RequestIdValue = "req-" & Api_NewId()
' A caller's X-Request-Id is kept for correlation when it is a plain token; otherwise a new id is made.
h = "" & Request.ServerVariables("HTTP_X_REQUEST_ID")
Set re = New RegExp
re.Pattern = "^[A-Za-z0-9._:-]{8,64}$"
If re.Test(h) Then
Api_RequestIdValue = h
Else
Api_RequestIdValue = "req-" & Api_NewId()
End If
End If
Api_RequestId = Api_RequestIdValue
End Function
@@ -77,6 +86,7 @@ Function Api_StatusLine(status)
Case 405: Api_StatusLine = "405 Method Not Allowed"
Case 409: Api_StatusLine = "409 Conflict"
Case 412: Api_StatusLine = "412 Precondition Failed"
Case 413: Api_StatusLine = "413 Payload Too Large"
Case 422: Api_StatusLine = "422 Unprocessable Entity"
Case 428: Api_StatusLine = "428 Precondition Required"
Case 500: Api_StatusLine = "500 Internal Server Error"
@@ -93,6 +103,7 @@ Sub Api_Send(status, jsonText)
Response.AddHeader "X-Request-Id", Api_RequestId()
Response.AddHeader "Cache-Control", "no-store"
Response.Write jsonText
Obs_Record status
End Sub

Sub Api_Error(status, code, message)
@@ -133,73 +144,136 @@ End Function

' Request body as UTF-8 text, or Empty after sending a 400.
Function Api_ReadBody()
Api_ReadBody = Api_ReadBodyMax(1048576)
End Function

' Same with a caller-chosen size limit in bytes (imports accept more than ordinary writes).
Function Api_ReadBodyMax(maxBytes)
Dim n, text
Api_ReadBody = Empty
Api_ReadBodyMax = Empty
n = Request.TotalBytes
If n = 0 Then
Api_Error 400, "empty_body", "Request body is empty. Send a JSON object."
Exit Function
End If
If n > 1048576 Then
Api_Error 400, "body_too_large", "Request body exceeds 1 MiB."
If n > maxBytes Then
Api_Error 413, "body_too_large", "Request body exceeds " & (maxBytes \ 1048576) & " MiB."
Exit Function
End If
Api_Utf8Unsupported = False
text = Api_Utf8Decode(CStr(Request.BinaryRead(n)))
If JsonLite_Parse(text) Is Nothing Then
Api_Error 400, "invalid_json", "Body must be a valid JSON object."
Exit Function
End If
Api_ReadBody = text
' Reject rather than store damaged text (see Api_Utf8Decode)
If Api_Utf8Unsupported Or JsonLite_SurrogateSeen Then
Api_Error 422, "unsupported_character", "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them."
Exit Function
End If
Api_ReadBodyMax = text
End Function

Dim Api_Utf8Unsupported
Api_Utf8Unsupported = False

' Decodes a string holding raw UTF-8 bytes (one byte per character, as AxonASP BinaryRead returns) into Unicode text.
' The bytes are split into alternating ASCII / non-ASCII runs with ONE call to the RegExp engine (character loops over a
' large body were quadratic on AxonASP and timed out). ASCII runs are copied; a strictly valid non-ASCII run is
' decoded natively (percent-encoded, then G3AXON AxUrlDecode); a run with invalid bytes, encoded surrogates or 4-byte
' sequences goes through Api_Utf8DecodeRun (U+FFFD, and Api_Utf8Unsupported for characters above U+FFFF).
' Match.FirstIndex is not used: on this build it is a byte offset into the runtime's UTF-8 string, not a character index.
Function Api_Utf8Decode(ByVal s)
Dim i, n, c, cp, extra, out, k, ok, b
n = Len(s)
out = ""
Dim re, ms, m, sb, reOk, ax, v, enc, n
Set re = Server.CreateObject("VBScript.RegExp")
re.Global = True
re.Pattern = "[\x00-\x7F]+|[\x80-\xFF]+"
Set ms = re.Execute(s)
If ms.Count <= 1 Then
If ms.Count = 0 Then
Api_Utf8Decode = s
Exit Function
End If
If AscW(Left(s, 1)) < 128 Then
If AscW(Left(s, 1)) >= 0 Then
Api_Utf8Decode = s ' pure ASCII
Exit Function
End If
End If
End If
' well-formed UTF-8 of code points up to U+FFFF, excluding surrogates and overlong forms
Set reOk = Server.CreateObject("VBScript.RegExp")
reOk.Global = True
reOk.Pattern = "[\xC2-\xDF][\x80-\xBF]|\xE0[\xA0-\xBF][\x80-\xBF]|[\xE1-\xEC\xEE\xEF][\x80-\xBF][\x80-\xBF]|\xED[\x80-\x9F][\x80-\xBF]"
Set ax = Server.CreateObject("G3AXON.FUNCTIONS")
Set sb = Server.CreateObject("G3STRINGBUILDER")
For Each m In ms
v = m.Value
n = AscW(Left(v, 1))
If n >= 0 And n < 128 Then
sb.Append v
ElseIf Len(reOk.Replace(v, "")) = 0 Then
enc = v
For n = 128 To 255
enc = Replace(enc, ChrW(n), "%" & Hex(n))
Next
sb.Append ax.AxUrlDecode(enc)
Else
Api_Utf8DecodeRun v, sb
End If
Next
Api_Utf8Decode = sb.ToString()
Set sb = Nothing
End Function

' Decodes one run of bytes >= 0x80 byte by byte (the slow path for runs that are not plain valid UTF-8). A sequence cut
' short at the end of the run is followed by an ASCII byte, so it is invalid there as well: U+FFFD, one byte at a time.
Sub Api_Utf8DecodeRun(run, sb)
Dim i, n, c, cp, extra, k, ok, b
n = Len(run)
i = 1
Do While i <= n
c = AscW(Mid(s, i, 1)) And 255
If c < 128 Then
out = out & Chr(c)
i = i + 1
Else
extra = -1
cp = 0
If c >= 240 And c <= 247 Then
extra = 3
cp = c And 7
ElseIf c >= 224 And c <= 239 Then
extra = 2
cp = c And 15
ElseIf c >= 194 And c <= 223 Then
extra = 1
cp = c And 31
End If
ok = (extra > 0 And i + extra <= n)
If ok Then
For k = 1 To extra
b = AscW(Mid(s, i + k, 1)) And 255
If b < 128 Or b > 191 Then
ok = False
Else
cp = cp * 64 + (b And 63)
End If
Next
End If
If ok And cp <= 1114111 Then
' AxonASP strings hold whole code points: ChrW(cp) works above U+FFFF, while a UTF-16
' surrogate pair would be stored as two U+FFFD characters.
out = out & ChrW(cp)
i = i + extra + 1
c = AscW(Mid(run, i, 1)) And 255
extra = -1
cp = 0
If c >= 240 And c <= 247 Then
extra = 3
cp = c And 7
ElseIf c >= 224 And c <= 239 Then
extra = 2
cp = c And 15
ElseIf c >= 194 And c <= 223 Then
extra = 1
cp = c And 31
End If
ok = (extra > 0 And i + extra <= n)
If ok Then
For k = 1 To extra
b = AscW(Mid(run, i + k, 1)) And 255
If b < 128 Or b > 191 Then
ok = False
Else
cp = cp * 64 + (b And 63)
End If
Next
End If
If ok And cp <= 1114111 Then
' On the pinned AxonASP build ChrW(cp > 65535) raises "Invalid procedure call" and a surrogate pair
' is written out as CESU-8, so code points above U+FFFF (and encoded surrogates) cannot be held.
' They become U+FFFD and set Api_Utf8Unsupported; Api_ReadBody then answers 422.
If cp > 65535 Or (cp >= 55296 And cp <= 57343) Then
Api_Utf8Unsupported = True
sb.Append ChrW(65533)
Else
out = out & ChrW(65533)
i = i + 1
sb.Append ChrW(cp)
End If
i = i + extra + 1
Else
sb.Append ChrW(65533)
i = i + 1
End If
Loop
Api_Utf8Decode = out
End Function
End Sub

Function Api_ToInt(v, dflt, lo, hi)
Dim s


+ 3
- 0
core/lib.ControllerRegistry.asp View File

@@ -15,6 +15,9 @@ Class ControllerRegistry_Class
' Format: m_controllers.Add "controllername", True
RegisterController "homecontroller"
RegisterController "errorcontroller"
RegisterController "apicontextcontroller"
RegisterController "apilearningcontroller"
RegisterController "apiportabilitycontroller"
RegisterController "apidocumentscontroller"
RegisterController "apihealthcontroller"
RegisterController "apisessionscontroller"


+ 716
- 0
core/lib.Embeddings.asp View File

@@ -0,0 +1,716 @@
<%
'=======================================================================================================================
' Semantic retrieval: embeddings (Ollama) + vector index (Qdrant) + hybrid ranking (spec FR-008, FR-009, section 10).
'
' SQLite is the source of truth. Table embedding_index records, per memory/chunk, what the vector store should hold
' (status pending | indexed | failed | delete, model, dimensions, revision). Write paths only mark rows inside their
' transaction (Emb_MarkPending / Emb_MarkDelete*); after commit they call Emb_AfterWrite, which indexes a bounded batch
' and never fails the request. scripts\embed.cmd processes everything left over or rebuilds the index.
'
' Vectors are never parsed in VBScript: Ollama's JSON array text is passed straight into the Qdrant request body.
' Qdrant points use the memory/chunk id as point id and carry tenant_id, namespace_id, kind and revision as payload.
' Search filters by tenant, kind and the caller's readable namespaces in Qdrant, and callers then re-check every hit
' against the canonical tables (namespace, lifecycle, validity, current revision), as for lexical hits.
'
' Settings (web.config appSettings):
' EmbeddingProvider ollama | none (default none: lexical only, with a warning)
' EmbeddingUrl http://ollama:11434
' EmbeddingModel nomic-embed-text
' EmbeddingDimensions 768
' EmbeddingDocumentPrefix "search_document: " (model-specific task prefixes; empty for models without them)
' EmbeddingQueryPrefix "search_query: "
' EmbeddingMinScore cosine similarity below which a semantic hit is ignored (default 0.6; model-specific: for
' nomic-embed-text relevant pairs scored 0.61-0.67, unrelated ones up to 0.58)
' VectorStoreUrl http://qdrant:6333
' EmbeddingTimeoutMs receive timeout per provider/store call inside a web request (default 10000), so a busy
' provider makes recall/search/context fall back to lexical instead of stalling the request.
' scripts/embed.asp (CLI, worker) uses 60000.
' EmbeddingWriteBudgetMs time Emb_AfterWrite may spend indexing after a commit (default 8000): no new batch starts
' after it, and rows it could not index stay pending for the worker (no attempt is used up).
' The Qdrant collection is amk_<model>_<dimensions>, so changing the model starts a new collection (run embed reindex).
' No native object is held across calls: each HTTP call creates and releases its own MSXML2.ServerXMLHTTP.
'=======================================================================================================================
Const EMB_RRF_K = 60
Const EMB_BATCH = 16
Const EMB_MAX_ATTEMPTS = 5
Const EMB_MAX_TEXT = 8000

Dim Emb_LastError, Emb_TimeoutMs, Emb_BudgetMs, Emb_BudgetStart
Emb_LastError = ""
Emb_TimeoutMs = 0 ' 0: EmbeddingTimeoutMs setting; scripts/embed.asp sets 60000
Emb_BudgetMs = 0 ' > 0 only while Emb_AfterWrite runs

Function Emb_CallTimeoutMs()
Dim v
If Emb_TimeoutMs > 0 Then
Emb_CallTimeoutMs = Emb_TimeoutMs
Exit Function
End If
v = Emb_Setting("EmbeddingTimeoutMs", "10000")
If Not IsNumeric(v) Then
v = "10000"
End If
Emb_CallTimeoutMs = CLng(v)
End Function

' True when Emb_AfterWrite's time budget is spent (Timer wraps at midnight).
Function Emb_OverBudget()
Dim d
Emb_OverBudget = False
If Emb_BudgetMs <= 0 Then
Exit Function
End If
d = Timer - Emb_BudgetStart
If d < 0 Then
d = d + 86400
End If
Emb_OverBudget = (d * 1000 >= Emb_BudgetMs)
End Function

Function Emb_Setting(key, dflt)
Dim v
v = "" & GetAppSetting(key)
If Len(v) = 0 Then
v = dflt
End If
Emb_Setting = v
End Function

Function Emb_Enabled()
Emb_Enabled = (LCase(Emb_Setting("EmbeddingProvider", "none")) = "ollama")
End Function

Function Emb_Model()
Emb_Model = Emb_Setting("EmbeddingModel", "nomic-embed-text")
End Function

Function Emb_Dims()
Emb_Dims = CLng(Emb_Setting("EmbeddingDimensions", "768"))
End Function

Function Emb_MinScore()
Emb_MinScore = CDbl(Replace(Emb_Setting("EmbeddingMinScore", "0.6"), ".", Mid(CStr(1.5), 2, 1)))
End Function

Function Emb_Collection()
Dim m, i, c, out
m = LCase(Emb_Model())
out = ""
For i = 1 To Len(m)
c = Mid(m, i, 1)
If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Then
out = out & c
Else
out = out & "_"
End If
Next
Emb_Collection = "amk_" & out & "_" & Emb_Dims()
End Function

' One HTTP call. Returns the response text; status 0 and Emb_LastError on a transport failure.
Function Emb_Http(method, url, body, ByRef status)
Dim http, text
Emb_Http = ""
status = 0
On Error Resume Next
Set http = Server.CreateObject("MSXML2.ServerXMLHTTP")
http.SetTimeouts 2000, 2000, 10000, Emb_CallTimeoutMs()
http.Open method, url, False
If Len(body) > 0 Then
http.SetRequestHeader "Content-Type", "application/json"
http.Send body
Else
http.Send
End If
If Err.Number <> 0 Then
Emb_LastError = method & " " & url & ": " & Err.Description
Err.Clear
Set http = Nothing
Exit Function
End If
status = http.Status
text = "" & http.ResponseText
Set http = Nothing
On Error GoTo 0
If status < 200 Or status > 299 Then
Emb_LastError = method & " " & url & ": HTTP " & status & " " & Left(text, 200)
End If
Emb_Http = text
End Function

' Embeds texts (array of strings) with the given task prefix. Returns an array of raw JSON vectors ("[0.1,...]"),
' one per text, or Empty on failure (Emb_LastError says why).
Function Emb_EmbedTexts(texts, prefix)
Dim body, i, resp, status, p, q, inner, vecs, marker
Emb_EmbedTexts = Empty
body = ""
For i = 0 To UBound(texts)
If i > 0 Then
body = body & ","
End If
body = body & JsonLite_Quote(prefix & Left("" & texts(i), EMB_MAX_TEXT))
Next
body = "{""model"":" & JsonLite_Quote(Emb_Model()) & ",""truncate"":true,""input"":[" & body & "]}"
resp = Emb_Http("POST", Emb_Setting("EmbeddingUrl", "http://ollama:11434") & "/api/embed", body, status)
If status <> 200 Then
Exit Function
End If
' {"model":"...","embeddings":[[...],[...]],...}: vectors hold only numbers, so "]]" ends the list
marker = """embeddings"":[["
p = InStr(resp, marker)
If p = 0 Then
Emb_LastError = "embedding response without embeddings"
Exit Function
End If
p = p + Len(marker)
q = InStr(p, resp, "]]")
If q = 0 Then
Emb_LastError = "embedding response is truncated"
Exit Function
End If
inner = Replace(Replace(Mid(resp, p, q - p), " ", ""), vbLf, "")
vecs = Split(inner, "],[")
If UBound(vecs) <> UBound(texts) Then
Emb_LastError = "embedding count mismatch (" & (UBound(vecs) + 1) & " for " & (UBound(texts) + 1) & " texts)"
Exit Function
End If
For i = 0 To UBound(vecs)
If UBound(Split(vecs(i), ",")) + 1 <> Emb_Dims() Then
Emb_LastError = "model returned " & (UBound(Split(vecs(i), ",")) + 1) & " dimensions, EmbeddingDimensions is " & Emb_Dims()
Exit Function
End If
vecs(i) = "[" & vecs(i) & "]"
Next
Emb_EmbedTexts = vecs
End Function

' Creates the collection (cosine, configured size) and keyword payload indexes once per process.
Function Emb_EnsureCollection()
Dim name, base, status, resp, f
name = Emb_Collection()
Emb_EnsureCollection = False
If Application("emb_ok_" & name) = True Then
Emb_EnsureCollection = True
Exit Function
End If
base = Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & name
resp = Emb_Http("GET", base, "", status)
If status = 404 Then
resp = Emb_Http("PUT", base, "{""vectors"":{""size"":" & Emb_Dims() & ",""distance"":""Cosine""}}", status)
If status <> 200 Then
Exit Function
End If
For Each f In Array("tenant_id", "namespace_id", "kind")
resp = Emb_Http("PUT", base & "/index?wait=true", "{""field_name"":""" & f & """,""field_schema"":""keyword""}", status)
Next
ElseIf status <> 200 Then
Exit Function
End If
Application.Lock
Application("emb_ok_" & name) = True
Application.Unlock
Emb_EnsureCollection = True
End Function

'-----------------------------------------------------------------------------------------------------------------------
' Bookkeeping (call inside the write transaction)
'-----------------------------------------------------------------------------------------------------------------------
Sub Emb_MarkPending(kind, targetId, tenantId, namespaceId, revision)
DAL().Execute "INSERT INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _
"VALUES (?, ?, ?, ?, ?, 'pending', 0, ?) ON CONFLICT(target_kind, target_id) DO UPDATE SET status = 'pending', " & _
"revision = excluded.revision, namespace_id = excluded.namespace_id, attempts = 0, error = NULL, updated_at = excluded.updated_at", _
Array(kind, targetId, tenantId, namespaceId, CLng(revision), Api_Now())
End Sub

Sub Emb_MarkDelete(kind, targetId)
DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), kind, targetId)
End Sub

' Old revision's chunks of a document leave the vector index
Sub Emb_MarkDeleteChunks(documentId, revision)
DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = 'chunk' AND target_id IN " & _
"(SELECT id FROM chunks WHERE document_id = ? AND document_revision = ?)", Array(Api_Now(), documentId, CLng(revision))
End Sub

' After commit: index a bounded batch for this tenant. Never raises; a failure leaves rows pending/failed for later.
Sub Emb_AfterWrite(tenantId, maxItems)
Dim n
If Not Emb_Enabled() Then
Exit Sub
End If
Dim b
b = Emb_Setting("EmbeddingWriteBudgetMs", "8000")
If Not IsNumeric(b) Then
b = "8000"
End If
Emb_BudgetStart = Timer
Emb_BudgetMs = CLng(b)
On Error Resume Next
n = Emb_ProcessPending(tenantId, maxItems)
If Err.Number <> 0 Then
Emb_LastError = "process: " & Err.Description
Err.Clear
End If
On Error GoTo 0
Emb_BudgetMs = 0
End Sub

' Processes deletions and up to maxItems pending/failed rows (tenantId "" = all tenants). Returns rows indexed.
Function Emb_ProcessPending(tenantId, maxItems)
Dim rs, sql, ids, n, idList, status, resp, rows, i, j, k, cnt, texts(), kinds(), tids(), tens(), nss(), revs(), text, rev, ok
Dim batchStart, batchEnd, bt(), vecs, body, done, ts
Emb_ProcessPending = 0
If Not Emb_Enabled() Then
Exit Function
End If
If Not Emb_EnsureCollection() Then
Exit Function
End If

'--- deletions ------------------------------------------------------------------------------------------------
sql = "SELECT target_id FROM embedding_index WHERE status = 'delete'"
If Len(tenantId) > 0 Then
sql = sql & " AND tenant_id = ?"
Set rs = DAL().Query(sql & " LIMIT 256", tenantId)
Else
Set rs = DAL().Query(sql & " LIMIT 256", Empty)
End If
idList = ""
ids = ""
Do While Not rs.EOF
If Api_IsId("" & rs(0)) Then
If Len(idList) > 0 Then
idList = idList & ","
ids = ids & ","
End If
idList = idList & "'" & rs(0) & "'"
ids = ids & """" & rs(0) & """"
End If
rs.MoveNext
Loop
rs.Close
If Len(idList) > 0 Then
resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _
"{""points"":[" & ids & "]}", status)
If status = 200 Then
DAL().Execute "DELETE FROM embedding_index WHERE status = 'delete' AND target_id IN (" & idList & ")", Empty
Else
Exit Function
End If
End If

'--- pending and retryable failures ---------------------------------------------------------------------------
sql = "SELECT target_kind, target_id, tenant_id, namespace_id, revision FROM embedding_index WHERE (status = 'pending' OR (status = 'failed' AND attempts < " & EMB_MAX_ATTEMPTS & "))"
If Len(tenantId) > 0 Then
Set rs = DAL().Query(sql & " AND tenant_id = ? ORDER BY updated_at LIMIT " & CLng(maxItems), tenantId)
Else
Set rs = DAL().Query(sql & " ORDER BY updated_at LIMIT " & CLng(maxItems), Empty)
End If
rows = Empty
If Not rs.EOF Then
rows = rs.GetRows()
End If
rs.Close
If IsEmpty(rows) Then
Exit Function
End If

' Load the text to embed for every row (each query closed before the next)
cnt = UBound(rows, 2) + 1
ReDim texts(cnt - 1)
ReDim kinds(cnt - 1)
ReDim tids(cnt - 1)
ReDim tens(cnt - 1)
ReDim nss(cnt - 1)
ReDim revs(cnt - 1)
k = 0
For i = 0 To cnt - 1
text = ""
rev = 0
If "" & rows(0, i) = "memory" Then
Set rs = DAL().Query("SELECT r.title, r.content, m.current_revision, m.namespace_id FROM memories m JOIN memory_revisions r " & _
"ON r.memory_id = m.id AND r.revision = m.current_revision WHERE m.id = ?", "" & rows(1, i))
If Not rs.EOF Then
text = "" & rs(0) & vbLf & rs(1)
rev = CLng(rs(2))
rows(3, i) = "" & rs(3)
End If
rs.Close
Else
Set rs = DAL().Query("SELECT content, document_revision FROM chunks WHERE id = ?", "" & rows(1, i))
If Not rs.EOF Then
text = "" & rs(0)
rev = CLng(rs(1))
End If
rs.Close
End If
If Len(text) = 0 Then
' the source is gone: drop the row (and any point)
DAL().Execute "UPDATE embedding_index SET status = 'delete', updated_at = ? WHERE target_kind = ? AND target_id = ?", Array(Api_Now(), "" & rows(0, i), "" & rows(1, i))
Else
texts(k) = text
kinds(k) = "" & rows(0, i)
tids(k) = "" & rows(1, i)
tens(k) = "" & rows(2, i)
nss(k) = "" & rows(3, i)
revs(k) = rev
k = k + 1
End If
Next

done = 0
batchStart = 0
Do While batchStart < k
If batchStart > 0 And Emb_OverBudget() Then
Exit Do ' request time budget spent: the worker indexes the rest
End If
batchEnd = batchStart + EMB_BATCH - 1
If batchEnd > k - 1 Then
batchEnd = k - 1
End If
ReDim bt(batchEnd - batchStart)
For j = batchStart To batchEnd
bt(j - batchStart) = texts(j)
Next
vecs = Emb_EmbedTexts(bt, Emb_Setting("EmbeddingDocumentPrefix", ""))
ok = Not IsEmpty(vecs)
If ok Then
body = ""
For j = batchStart To batchEnd
If j > batchStart Then
body = body & ","
End If
body = body & "{""id"":""" & tids(j) & """,""vector"":" & vecs(j - batchStart) & ",""payload"":{""tenant_id"":""" & tens(j) & _
""",""namespace_id"":""" & nss(j) & """,""kind"":""" & kinds(j) & """,""revision"":" & revs(j) & "}}"
Next
resp = Emb_Http("PUT", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points?wait=true", _
"{""points"":[" & body & "]}", status)
ok = (status = 200)
End If
If Not ok And Emb_BudgetMs > 0 Then
Exit Do ' inside a request: leave the rows pending for the worker, do not use up their attempts
End If
ts = Api_Now()
For j = batchStart To batchEnd
If ok Then
DAL().Execute "UPDATE embedding_index SET status = 'indexed', model = ?, dimensions = ?, revision = ?, attempts = 0, error = NULL, updated_at = ? " & _
"WHERE target_kind = ? AND target_id = ? AND status <> 'delete'", Array(Emb_Model(), Emb_Dims(), revs(j), ts, kinds(j), tids(j))
done = done + 1
Else
DAL().Execute "UPDATE embedding_index SET status = 'failed', attempts = attempts + 1, error = ?, updated_at = ? WHERE target_kind = ? AND target_id = ?", _
Array(Left(Emb_LastError, 500), ts, kinds(j), tids(j))
End If
Next
If Not ok Then
Exit Do ' provider or store down: leave the rest for later
End If
batchStart = batchEnd + 1
Loop
Emb_ProcessPending = done
End Function

' Removes a whole tenant from the vector store and the bookkeeping (provision purge). Best effort for the store.
Sub Emb_DeleteTenant(tenantId)
Dim status, resp
If Emb_Enabled() Then
If Emb_EnsureCollection() Then
resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/delete?wait=true", _
"{""filter"":{""must"":[{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}]}}", status)
End If
End If
DAL().Execute "DELETE FROM embedding_index WHERE tenant_id = ?", tenantId
End Sub

'-----------------------------------------------------------------------------------------------------------------------
' Hybrid ranking. Lexical (FTS5/bm25) and, when configured, semantic (Qdrant cosine) candidate lists are merged with
' reciprocal rank fusion (raw scores of the two engines are not comparable). Without semantic retrieval the order and
' scores are the lexical ones (negated bm25). Callers still apply the canonical filters to every id.
' Set r = New Ranker_Class : r.Run "memory"|"chunk", ftsQuery, queryText, tenantId, allowedSqlList
' r.Count, r.IdAt(i), r.ScoreAt(i), r.Strategy ("lexical"|"hybrid"), r.Warning ("" or a sentence)
' Feedback (POST /feedback) on the CURRENT revision of a result then scales its score: x(1 + 0.1 per useful, max 5),
' x0.9 per not_useful (max 5), x0.5 per incorrect/harmful (max 3), and the list is re-sorted.
' r.FeedbackAt(i) ("" or a JSON object of counts), r.Demoted (results with more negative than useful ratings)
'-----------------------------------------------------------------------------------------------------------------------
Class Ranker_Class
Private m_ids(), m_scores(), m_n, m_strategy, m_warning, m_fb(), m_demoted
Private m_lex(), m_lexScore(), m_lexN, m_sem(), m_semN

Private Sub Class_Initialize()
m_n = 0
ReDim m_ids(0)
ReDim m_scores(0)
m_strategy = "lexical"
m_warning = ""
m_demoted = 0
ReDim m_fb(0)
End Sub

Public Function FeedbackAt(i)
FeedbackAt = "" & m_fb(i)
End Function

Public Property Get Demoted()
Demoted = m_demoted
End Property

Public Property Get Count()
Count = m_n
End Property

Public Function IdAt(i)
IdAt = m_ids(i)
End Function

Public Function ScoreAt(i)
ScoreAt = m_scores(i)
End Function

Public Property Get Strategy()
Strategy = m_strategy
End Property

Public Property Get Warning()
Warning = m_warning
End Property

Public Sub Run(kind, fts, queryText, tenantId, allowed)
Dim rs, tbl, col, i
If kind = "memory" Then
tbl = "memories_fts"
col = "memory_id"
Else
tbl = "chunks_fts"
col = "chunk_id"
End If
m_lexN = 0
ReDim m_lex(63)
ReDim m_lexScore(63)
If Len(fts) > 0 Then
Set rs = DAL().Query("SELECT " & col & ", bm25(" & tbl & ") FROM " & tbl & " WHERE " & tbl & " MATCH ? AND tenant_id = ? ORDER BY bm25(" & tbl & ") LIMIT 300", Array(fts, tenantId))
Do While Not rs.EOF
If m_lexN > UBound(m_lex) Then
ReDim Preserve m_lex(m_lexN * 2)
ReDim Preserve m_lexScore(m_lexN * 2)
End If
m_lex(m_lexN) = "" & rs(0)
m_lexScore(m_lexN) = -CDbl(rs(1))
m_lexN = m_lexN + 1
rs.MoveNext
Loop
rs.Close
End If

m_semN = 0
ReDim m_sem(0)
If Not Emb_Enabled() Then
m_warning = "semantic retrieval is not configured; results are lexical only"
ElseIf Len(allowed) = 0 Then
m_strategy = "hybrid"
ElseIf SemanticSearch(kind, queryText, tenantId, allowed) Then
m_strategy = "hybrid"
Else
m_warning = "semantic retrieval is unavailable; results are lexical only"
End If

If m_strategy = "hybrid" Then
Fuse
Else
m_n = m_lexN
ReDim m_ids(m_n)
ReDim m_scores(m_n)
For i = 0 To m_lexN - 1
m_ids(i) = m_lex(i)
m_scores(i) = m_lexScore(i)
Next
End If
ApplyFeedback kind, tenantId
End Sub

' Usefulness feedback of the tenant on the current revision of each candidate (top 300) adjusts its score.
Private Sub ApplyFeedback(kind, tenantId)
Dim i, j, idList, lim, sql, rs, rows, u, nu, neg, f, t, ts, tf
ReDim m_fb(m_n)
If m_n = 0 Then
Exit Sub
End If
lim = m_n
If lim > 300 Then
lim = 300
End If
idList = ""
For i = 0 To lim - 1
If Api_IsId(m_ids(i)) Then
If Len(idList) > 0 Then
idList = idList & ","
End If
idList = idList & "'" & m_ids(i) & "'"
End If
Next
If Len(idList) = 0 Then
Exit Sub
End If
sql = "SELECT f.target_id, SUM(CASE WHEN f.usefulness = 'useful' THEN 1 ELSE 0 END), SUM(CASE WHEN f.usefulness = 'not_useful' THEN 1 ELSE 0 END), " & _
"SUM(CASE WHEN f.usefulness IN ('incorrect','harmful') THEN 1 ELSE 0 END) FROM feedback f "
If kind = "memory" Then
sql = sql & "JOIN memories m ON m.id = f.target_id AND m.current_revision = f.target_revision "
End If
sql = sql & "WHERE f.tenant_id = ? AND f.target_kind = '" & kind & "' AND f.target_id IN (" & idList & ") GROUP BY f.target_id"
Set rs = DAL().Query(sql, tenantId)
rows = Empty
If Not rs.EOF Then
rows = rs.GetRows()
End If
rs.Close
If IsEmpty(rows) Then
Exit Sub
End If
For j = 0 To UBound(rows, 2)
u = CLng(rows(1, j))
nu = CLng(rows(2, j))
neg = CLng(rows(3, j))
For i = 0 To lim - 1
If m_ids(i) = "" & rows(0, j) Then
f = (1 + 0.1 * Min_(u, 5)) * (0.9 ^ Min_(nu, 5)) * (0.5 ^ Min_(neg, 3))
m_scores(i) = m_scores(i) * f
m_fb(i) = "{""useful"":" & u & ",""not_useful"":" & nu & ",""incorrect_or_harmful"":" & neg & "}"
If neg > u Then
m_demoted = m_demoted + 1
End If
Exit For
End If
Next
Next
' re-sort (stable insertion sort, descending)
For i = 1 To m_n - 1
t = m_ids(i)
ts = m_scores(i)
tf = m_fb(i)
j = i - 1
Do While j >= 0
If m_scores(j) >= ts Then
Exit Do
End If
m_ids(j + 1) = m_ids(j)
m_scores(j + 1) = m_scores(j)
m_fb(j + 1) = m_fb(j)
j = j - 1
Loop
m_ids(j + 1) = t
m_scores(j + 1) = ts
m_fb(j + 1) = tf
Next
End Sub

Private Function Min_(a, b)
If a < b Then
Min_ = a
Else
Min_ = b
End If
End Function

' Embeds the query and asks Qdrant for the closest points of this kind in the tenant's allowed namespaces.
Private Function SemanticSearch(kind, queryText, tenantId, allowed)
Dim vecs, body, resp, status, p, q, id, sc, minScore
SemanticSearch = False
If Not Emb_EnsureCollection() Then
Exit Function
End If
vecs = Emb_EmbedTexts(Array(queryText), Emb_Setting("EmbeddingQueryPrefix", ""))
If IsEmpty(vecs) Then
Exit Function
End If
body = "{""query"":" & vecs(0) & ",""limit"":100,""with_payload"":false,""filter"":{""must"":[" & _
"{""key"":""tenant_id"",""match"":{""value"":" & JsonLite_Quote(tenantId) & "}}," & _
"{""key"":""kind"",""match"":{""value"":""" & kind & """}}," & _
"{""key"":""namespace_id"",""match"":{""any"":[" & Replace(allowed, "'", """") & "]}}]}}"
resp = Emb_Http("POST", Emb_Setting("VectorStoreUrl", "http://qdrant:6333") & "/collections/" & Emb_Collection() & "/points/query", body, status)
If status <> 200 Then
Exit Function
End If
minScore = Emb_MinScore()
' {"result":{"points":[{"id":"...","version":n,"score":0.8},...]},...}: scan id/score pairs in order
p = InStr(resp, """id"":""")
Do While p > 0
p = p + 6
q = InStr(p, resp, """")
id = Mid(resp, p, q - p)
p = InStr(q, resp, """score"":")
If p = 0 Then
Exit Do
End If
p = p + 8
q = p
Do While q <= Len(resp)
If InStr("0123456789.-+eE", Mid(resp, q, 1)) = 0 Then
Exit Do
End If
q = q + 1
Loop
sc = CDbl(Replace(Mid(resp, p, q - p), ".", Mid(CStr(1.5), 2, 1)))
If sc >= minScore Then
If m_semN > UBound(m_sem) Then
ReDim Preserve m_sem(m_semN * 2 + 1)
End If
m_sem(m_semN) = id
m_semN = m_semN + 1
End If
p = InStr(q, resp, """id"":""")
Loop
SemanticSearch = True
End Function

' Reciprocal rank fusion over the top 100 of each list, sorted by fused score (descending)
Private Sub Fuse()
Dim i, j, lim, found, t, ts
m_n = 0
ReDim m_ids(200)
ReDim m_scores(200)
lim = m_lexN
If lim > 100 Then
lim = 100
End If
For i = 0 To lim - 1
m_ids(m_n) = m_lex(i)
m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
m_n = m_n + 1
Next
lim = m_semN
If lim > 100 Then
lim = 100
End If
For i = 0 To lim - 1
found = -1
For j = 0 To m_n - 1
If m_ids(j) = m_sem(i) Then
found = j
Exit For
End If
Next
If found >= 0 Then
m_scores(found) = m_scores(found) + 1 / (EMB_RRF_K + i + 1)
Else
m_ids(m_n) = m_sem(i)
m_scores(m_n) = 1 / (EMB_RRF_K + i + 1)
m_n = m_n + 1
End If
Next
' insertion sort, stable for equal scores (lexical order first)
For i = 1 To m_n - 1
t = m_ids(i)
ts = m_scores(i)
j = i - 1
Do While j >= 0
If m_scores(j) >= ts Then
Exit Do
End If
m_ids(j + 1) = m_ids(j)
m_scores(j + 1) = m_scores(j)
j = j - 1
Loop
m_ids(j + 1) = t
m_scores(j + 1) = ts
Next
End Sub
End Class
%>

+ 281
- 194
core/lib.JsonLite.asp View File

@@ -1,6 +1,6 @@
<%
'=======================================================================================================================
' JsonLite: tiny pure-VBScript JSON reader/encoder for flat request bodies.
' JsonLite: small pure-VBScript JSON reader/encoder for request bodies.
'
' Why not G3JSON? Under the AxonASP HTTP server, G3JSON.Parse results and G3DB interfered with each other: parsing before the
' first database open made the first INSERT silently do nothing, and opening the database first made Parse return empty
@@ -10,9 +10,20 @@
' obj.Exists("Name"), obj.Item("Name")
' JsonLite_Quote(s) ' "text" with JSON escaping
' JsonLite_Num(n) ' locale-independent number literal
' JsonLite_SurrogateSeen ' True after JsonLite_Parse met a backslash-u escape for a UTF-16 surrogate
'
' Speed: on AxonASP every builtin call costs time in proportion to the length of the string it is given (Len, Mid and
' InStr on a 200K string take 0.4-5 ms each), so character loops over a large body are quadratic and timed out. The text
' is therefore split into tokens with ONE call to the AxonASP RegExp engine (JsonLite_Tokens) and the parser walks the
' token array; string tokens are decoded on their own (one Split on the backslash when they contain escapes).
'
' Characters above U+FFFF: on the pinned AxonASP build ChrW(cp > 65535) raises "Invalid procedure call" and a
' surrogate pair is written out as CESU-8 (invalid UTF-8). Surrogate escapes therefore decode to U+FFFD and set
' JsonLite_SurrogateSeen; Api_ReadBody rejects such requests with 422 instead of storing damaged text.
'
' Values: String, Double (numbers), Boolean, Null. Nested objects/arrays are parsed and stored as Null, but the raw
' text of top-level ones is kept: obj.HasRaw(k) / obj.Raw(k); JsonLite_ParseStringArray(raw) reads an array of strings.
' text of top-level ones is kept: obj.HasRaw(k) / obj.Raw(k) (tokens joined without whitespace);
' JsonLite_ParseStringArray(raw) reads an array of strings, JsonLite_SplitObjectArray(raw) an array of objects.
'=======================================================================================================================
Class JsonLite_Object
Private m_keys(), m_vals(), m_count
@@ -100,135 +111,150 @@ Class JsonLite_Object
End Function
End Class

' Tokens of a JSON text, in order: strings (with their quotes and escapes), numbers, true/false/null, punctuation, and
' any other single non-whitespace character (which the parser then rejects). Whitespace between tokens is dropped.
' Returns Empty when there is no token. In the pattern the backslash is written \x5C: AxonASP's pattern translation
' rejected a literal backslash inside a character class.
Function JsonLite_Tokens(text)
Dim re, ms, m, arr, i
JsonLite_Tokens = Empty
Set re = Server.CreateObject("VBScript.RegExp")
re.Global = True
re.Pattern = """(?:[^""\x5C]|\x5C.)*""|-?[0-9]+(?:[.][0-9]+)?(?:[eE][+-]?[0-9]+)?|true|false|null|[{}:,]|\x5B|\x5D|[^ \t\r\n]"
Set ms = re.Execute("" & text)
If ms.Count = 0 Then
Exit Function
End If
ReDim arr(ms.Count - 1)
i = 0
For Each m In ms
arr(i) = m.Value
i = i + 1
Next
JsonLite_Tokens = arr
End Function

' Raw text of tokens a..b (joined without whitespace)
Function JsonLite_JoinTokens(t, a, b)
Dim arr, i
If b < a Then
JsonLite_JoinTokens = ""
Exit Function
End If
ReDim arr(b - a)
For i = a To b
arr(i - a) = t(i)
Next
JsonLite_JoinTokens = Join(arr, "")
End Function

Class JsonLite_Parser
Private m_s, m_pos, m_len, m_ok
Private m_t, m_n, m_i, m_ok, m_sur

Public Property Get SurrogateSeen()
SurrogateSeen = (m_sur = True)
End Property

Private Function Load(text)
m_sur = False
m_ok = True
m_i = 0
m_t = JsonLite_Tokens(text)
If IsEmpty(m_t) Then
m_n = 0
Load = False
Else
m_n = UBound(m_t) + 1
Load = True
End If
End Function

Private Function Peek()
If m_i < m_n Then
Peek = m_t(m_i)
Else
Peek = ""
End If
End Function

Public Function Run(text)
Dim obj
m_s = "" & text
m_len = Len(m_s)
m_pos = 1
m_ok = True
Set Run = Nothing
SkipWs
If m_pos > m_len Then Exit Function
If Mid(m_s, m_pos, 1) <> "{" Then Exit Function
If Not Load(text) Then Exit Function
If m_t(0) <> "{" Then Exit Function
Set obj = ReadObject()
If Not m_ok Then Exit Function
SkipWs
If m_pos <= m_len Then Exit Function ' trailing garbage
If m_i < m_n Then Exit Function ' trailing garbage
Set Run = obj
End Function

' Parses text that must be a JSON array of strings. Returns an array of strings, or Null if it is anything else.
Public Function RunStringArray(text)
Dim items(), n, c, v
m_s = "" & text
m_len = Len(m_s)
m_pos = 1
m_ok = True
Dim items(), n, tok
RunStringArray = Null
If Not Load(text) Then Exit Function
If m_t(0) <> "[" Then Exit Function
m_i = 1
n = 0
ReDim items(-1)
SkipWs
If m_pos > m_len Then Exit Function
If Mid(m_s, m_pos, 1) <> "[" Then Exit Function
m_pos = m_pos + 1
SkipWs
If m_pos <= m_len Then
If Mid(m_s, m_pos, 1) = "]" Then
m_pos = m_pos + 1
SkipWs
If m_pos <= m_len Then Exit Function
RunStringArray = items
Exit Function
End If
If Peek() = "]" Then
m_i = m_i + 1
If m_i < m_n Then Exit Function
RunStringArray = items
Exit Function
End If
Do
SkipWs
If m_pos > m_len Then Exit Function
If Mid(m_s, m_pos, 1) <> """" Then Exit Function
v = ReadString()
If Not m_ok Then Exit Function
tok = Peek()
If Left(tok, 1) <> """" Then Exit Function
ReDim Preserve items(n)
items(n) = v
items(n) = DecodeString(tok)
If Not m_ok Then Exit Function
n = n + 1
SkipWs
If m_pos > m_len Then Exit Function
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = "]" Then Exit Do
If c <> "," Then Exit Function
m_i = m_i + 1
tok = Peek()
m_i = m_i + 1
If tok = "]" Then Exit Do
If tok <> "," Then Exit Function
Loop
SkipWs
If m_pos <= m_len Then Exit Function
If m_i < m_n Then Exit Function
RunStringArray = items
End Function

Private Sub SkipWs()
Dim c
Do While m_pos <= m_len
c = Mid(m_s, m_pos, 1)
If c = " " Or c = vbTab Or c = vbCr Or c = vbLf Then
m_pos = m_pos + 1
Else
Exit Do
End If
Loop
End Sub

Private Function ReadObject()
Dim obj, k, v, c, rawStart, c0
Dim obj, k, v, tok, rawStart, c0
Set obj = New JsonLite_Object
Set ReadObject = obj
m_pos = m_pos + 1 ' {
SkipWs
If m_pos <= m_len Then
If Mid(m_s, m_pos, 1) = "}" Then
m_pos = m_pos + 1
Exit Function
End If
m_i = m_i + 1 ' {
If Peek() = "}" Then
m_i = m_i + 1
Exit Function
End If
Do
SkipWs
If m_pos > m_len Then
tok = Peek()
If Left(tok, 1) <> """" Then
m_ok = False
Exit Function
End If
If Mid(m_s, m_pos, 1) <> """" Then
m_ok = False
Exit Function
End If
k = ReadString()
k = DecodeString(tok)
If Not m_ok Then Exit Function
SkipWs
If m_pos > m_len Then
m_i = m_i + 1
If Peek() <> ":" Then
m_ok = False
Exit Function
End If
If Mid(m_s, m_pos, 1) <> ":" Then
m_ok = False
Exit Function
End If
m_pos = m_pos + 1
SkipWs
rawStart = m_pos
c0 = Mid(m_s, m_pos, 1)
m_i = m_i + 1
rawStart = m_i
c0 = Peek()
v = ReadValue()
If Not m_ok Then Exit Function
obj.Add k, v
If c0 = "{" Or c0 = "[" Then
obj.AddRaw k, Mid(m_s, rawStart, m_pos - rawStart)
obj.AddRaw k, JsonLite_JoinTokens(m_t, rawStart, m_i - 1)
End If
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Function
End If
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = "}" Then Exit Function
If c <> "," Then
tok = Peek()
m_i = m_i + 1
If tok = "}" Then Exit Function
If tok <> "," Then
m_ok = False
Exit Function
End If
@@ -237,33 +263,32 @@ Class JsonLite_Parser

' Reads any value; returns String, Double, Boolean or Null (nested containers are consumed and returned as Null)
Private Function ReadValue()
Dim c, t, start, lit, dummy
Dim tok, c, dummy, lit
ReadValue = Null
SkipWs
If m_pos > m_len Then
tok = Peek()
If Len(tok) = 0 Then
m_ok = False
Exit Function
End If
c = Mid(m_s, m_pos, 1)
c = Left(tok, 1)
If c = """" Then
ReadValue = ReadString()
ReadValue = DecodeString(tok)
m_i = m_i + 1
ElseIf c = "{" Then
Set dummy = ReadObject()
ElseIf c = "[" Then
SkipArray
ElseIf c = "-" Or (c >= "0" And c <= "9") Then
start = m_pos
Do While m_pos <= m_len
t = Mid(m_s, m_pos, 1)
If (t >= "0" And t <= "9") Or t = "-" Or t = "+" Or t = "." Or t = "e" Or t = "E" Then
m_pos = m_pos + 1
Else
Exit Do
End If
Loop
lit = Mid(m_s, start, m_pos - start)
ElseIf tok = "true" Then
ReadValue = True
m_i = m_i + 1
ElseIf tok = "false" Then
ReadValue = False
m_i = m_i + 1
ElseIf tok = "null" Then
m_i = m_i + 1
ElseIf (c = "-" And Len(tok) > 1) Or (c >= "0" And c <= "9") Then
' CDbl uses the locale's decimal separator, JSON always uses "."
lit = Replace(UCase(lit), ".", Mid(CStr(1.5), 2, 1))
lit = Replace(UCase(tok), ".", Mid(CStr(1.5), 2, 1))
On Error Resume Next
ReadValue = CDbl(lit)
If Err.Number <> 0 Then
@@ -271,102 +296,112 @@ Class JsonLite_Parser
m_ok = False
End If
On Error GoTo 0
m_i = m_i + 1
Else
If LCase(Mid(m_s, m_pos, 4)) = "true" Then
ReadValue = True
m_pos = m_pos + 4
ElseIf LCase(Mid(m_s, m_pos, 5)) = "false" Then
ReadValue = False
m_pos = m_pos + 5
ElseIf LCase(Mid(m_s, m_pos, 4)) = "null" Then
ReadValue = Null
m_pos = m_pos + 4
Else
m_ok = False
End If
m_ok = False
End If
End Function

Private Sub SkipArray()
Dim c, v
m_pos = m_pos + 1 ' [
SkipWs
If m_pos <= m_len Then
If Mid(m_s, m_pos, 1) = "]" Then
m_pos = m_pos + 1
Exit Sub
End If
Dim tok, v
m_i = m_i + 1 ' [
If Peek() = "]" Then
m_i = m_i + 1
Exit Sub
End If
Do
v = ReadValue()
If Not m_ok Then Exit Sub
SkipWs
If m_pos > m_len Then
m_ok = False
Exit Sub
End If
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = "]" Then Exit Sub
If c <> "," Then
tok = Peek()
m_i = m_i + 1
If tok = "]" Then Exit Sub
If tok <> "," Then
m_ok = False
Exit Sub
End If
Loop
End Sub

Private Function ReadString()
Dim out, c, e, h, cu, h2, lo
out = ""
m_pos = m_pos + 1 ' opening quote
Do While m_pos <= m_len
c = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
If c = """" Then
ReadString = out
Exit Function
ElseIf c = "\" Then
If m_pos > m_len Then Exit Do
e = Mid(m_s, m_pos, 1)
m_pos = m_pos + 1
' Decodes one string token (with its quotes). Without escapes this is a single Mid. With escapes the content is split
' on the backslash: every part after the first starts with an escape character, except that "\\" gives an empty
' part (the escaped backslash), after which the next part is plain text.
Private Function DecodeString(tok)
Dim inner, parts, out(), i, p, e, h, cu, h2, lo, ub
inner = Mid(tok, 2, Len(tok) - 2)
If InStr(inner, "\") = 0 Then
DecodeString = inner
Exit Function
End If
DecodeString = ""
parts = Split(inner, "\")
ub = UBound(parts)
ReDim out(ub)
For i = 0 To ub
out(i) = ""
Next
out(0) = parts(0)
i = 1
Do While i <= ub
p = parts(i)
If Len(p) = 0 Then
out(i) = "\"
If i + 1 > ub Then
m_ok = False ' a lone trailing backslash
Exit Function
End If
out(i + 1) = parts(i + 1)
i = i + 2
Else
e = Left(p, 1)
Select Case e
Case """": out = out & """"
Case "\": out = out & "\"
Case "/": out = out & "/"
Case "b": out = out & Chr(8)
Case "f": out = out & Chr(12)
Case "n": out = out & vbLf
Case "r": out = out & vbCr
Case "t": out = out & vbTab
Case """": out(i) = """" & Mid(p, 2)
Case "/": out(i) = "/" & Mid(p, 2)
Case "b": out(i) = Chr(8) & Mid(p, 2)
Case "f": out(i) = Chr(12) & Mid(p, 2)
Case "n": out(i) = vbLf & Mid(p, 2)
Case "r": out(i) = vbCr & Mid(p, 2)
Case "t": out(i) = vbTab & Mid(p, 2)
Case "u"
h = Mid(m_s, m_pos, 4)
h = Mid(p, 2, 4)
If Len(h) < 4 Or Not IsHex(h) Then
m_ok = False
Exit Function
End If
cu = CLng("&H" & h)
m_pos = m_pos + 4
' A UTF-16 surrogate pair (backslash-u D83D, backslash-u DE00) is one code point; AxonASP strings need it combined.
If cu >= 55296 And cu <= 56319 And Mid(m_s, m_pos, 2) = "\u" Then
h2 = Mid(m_s, m_pos + 2, 4)
If Len(h2) = 4 And IsHex(h2) Then
lo = CLng("&H" & h2)
If lo >= 56320 And lo <= 57343 Then
cu = 65536 + (cu - 55296) * 1024 + (lo - 56320)
m_pos = m_pos + 6
' "&H8000".."&HFFFF" are read as signed 16-bit (e.g. D83D -> -10179)
If cu < 0 Then
cu = cu + 65536
End If
' A UTF-16 surrogate pair (backslash-u D83D, backslash-u DE00) is one code point above U+FFFF,
' which this runtime cannot hold (see header): consume the pair, flag it, emit U+FFFD.
If cu >= 55296 And cu <= 56319 And Len(p) = 5 And i + 1 <= ub Then
If Left(parts(i + 1), 1) = "u" Then
h2 = Mid(parts(i + 1), 2, 4)
If Len(h2) = 4 And IsHex(h2) Then
lo = CLng("&H" & h2)
If lo < 0 Then
lo = lo + 65536
End If
If lo >= 56320 And lo <= 57343 Then
i = i + 1
p = "u" & h & Mid(parts(i), 6)
End If
End If
End If
End If
out = out & ChrW(cu)
If cu >= 55296 And cu <= 57343 Then
m_sur = True
cu = 65533
End If
out(i) = ChrW(cu) & Mid(p, 6)
Case Else
m_ok = False
Exit Function
End Select
Else
out = out & c
i = i + 1
End If
Loop
m_ok = False ' unterminated string
DecodeString = Join(out, "")
End Function

Private Function IsHex(h)
@@ -389,37 +424,89 @@ 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 is tracked (strings are single tokens).
Function JsonLite_SplitObjectArray(text)
Dim t, n, i, tok, depth, start, items(), cnt
JsonLite_SplitObjectArray = Null
t = JsonLite_Tokens(text)
If IsEmpty(t) Then
Exit Function
End If
n = UBound(t) + 1
If n < 2 Then
Exit Function
End If
If t(0) <> "[" Or t(n - 1) <> "]" Then
Exit Function
End If
cnt = 0
ReDim items(7)
depth = 0
start = 0
For i = 1 To n - 2
tok = t(i)
If tok = "{" Or tok = "[" Then
If depth = 0 Then
If tok = "[" Then
Exit Function ' a nested array element
End If
start = i
End If
depth = depth + 1
ElseIf tok = "}" Or tok = "]" Then
depth = depth - 1
If depth = 0 Then
If cnt > UBound(items) Then
ReDim Preserve items(cnt * 2)
End If
items(cnt) = JsonLite_JoinTokens(t, start, i)
cnt = cnt + 1
End If
ElseIf depth = 0 Then
If tok <> "," Then
Exit Function ' a string/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

Function JsonLite_Parse(text)
Dim p
Set p = New JsonLite_Parser
Set JsonLite_Parse = p.Run(text)
JsonLite_SurrogateSeen = p.SurrogateSeen
End Function

' "text" with JSON escaping (non-ASCII is left as is; the response is UTF-8)
' Built from native Replace calls: a per-character loop with string concatenation was quadratic (seconds per 100 KB).
Function JsonLite_Quote(s)
Dim t, i, c, n, out
t = "" & s
out = ""
For i = 1 To Len(t)
c = Mid(t, i, 1)
n = AscW(c)
If c = """" Then
out = out & "\"""
ElseIf c = "\" Then
out = out & "\\"
ElseIf n = 10 Then
out = out & "\n"
ElseIf n = 13 Then
out = out & "\r"
ElseIf n = 9 Then
out = out & "\t"
ElseIf n < 32 And n >= 0 Then
out = out & "\u" & Right("0000" & Hex(n), 4)
Else
out = out & c
Dim t, n
t = Replace("" & s, "\", "\\")
t = Replace(t, """", "\""")
t = Replace(t, ChrW(10), "\n")
t = Replace(t, ChrW(13), "\r")
t = Replace(t, ChrW(9), "\t")
For n = 0 To 31
If n <> 9 Then
If n <> 10 Then
If n <> 13 Then
t = Replace(t, ChrW(n), "\u" & Right("0000" & Hex(n), 4))
End If
End If
End If
Next
JsonLite_Quote = """" & out & """"
JsonLite_Quote = """" & t & """"
End Function

' Locale-independent number literal (CStr uses the locale's decimal separator)


+ 284
- 0
core/lib.Learning.asp View File

@@ -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
%>

+ 142
- 0
core/lib.Observability.asp View File

@@ -0,0 +1,142 @@
<%
' Observability for the JSON API (spec NFR-004, FR-019): one structured access-log line per API response and
' in-process request metrics, exposed with database gauges by GET /api/v1/metrics (ApiHealthController.Metrics).
'
' - Obs_Start is taken when this file runs (start of the request); MVC_InvokeAction sets Obs_Action to
' "<Controller>.<Action>", so metric labels stay bounded (no raw paths or ids).
' - Api_Send calls Obs_Record once per response. The log line is JSON written with console.log (stdout, so
' `docker logs axonasp`); 5xx go through console.error (stderr and the runtime's error.log). Each line has a
' timestamp/marker prefix from the runtime: extract the JSON with grep -o '{"log":.*'. No bodies, query strings
' or keys are logged. web.config ApiAccessLog = "false" turns the lines off (metrics are kept).
' - Counters live in Application (one process, reset on restart; Prometheus treats that as a counter reset).
' Requests whose action fails inside the dispatcher (empty 200, see AGENTS.md section 8) are not counted.
' Include before lib.Api.asp.
Dim Obs_Start, Obs_Action, Obs_Done
Obs_Start = Timer
Obs_Action = ""
Obs_Done = False

' Upper bounds (ms) of the latency histogram buckets; +Inf is implied.
Const OBS_BUCKETS = "5,10,25,50,100,250,500,1000,2500,5000,10000"

' Milliseconds since the request started (Timer wraps at midnight).
Function Obs_ElapsedMs()
Dim d
d = Timer - Obs_Start
If d < 0 Then
d = d + 86400
End If
Obs_ElapsedMs = Round(d * 1000, 1)
End Function

' Adds v to an Application counter and remembers the key in a registry list. Caller holds Application.Lock.
Sub Obs_Add(registry, key, v)
Dim cur
cur = Application(key)
If IsEmpty(cur) Then
Application(registry) = Application(registry) & key & vbLf
cur = 0
End If
Application(key) = cur + v
End Sub

Sub Obs_Record(status)
Dim ms, action, method, b, i, line, setting
If Obs_Done Then
Exit Sub
End If
Obs_Done = True
ms = Obs_ElapsedMs()
action = Obs_Action
If action = "" Then
action = "unrouted"
End If
method = UCase(Request.ServerVariables("REQUEST_METHOD"))

b = Split(OBS_BUCKETS, ",")
Application.Lock
If IsEmpty(Application("obs|since")) Then
Application("obs|since") = DateDiff("s", #1970-01-01#, Now())
End If
Obs_Add "obs|keys|req", "obs|req|" & action & "|" & method & "|" & status, 1
Obs_Add "obs|keys|act", "obs|n|" & action, 1
Application("obs|sum|" & action) = Application("obs|sum|" & action) + ms
For i = 0 To UBound(b)
If ms <= CDbl(b(i)) Then
Application("obs|b|" & action & "|" & i) = Application("obs|b|" & action & "|" & i) + 1
End If
Next
Application.Unlock

setting = LCase("" & GetAppSetting("ApiAccessLog"))
If setting = "false" Then
Exit Sub
End If
line = "{""log"":""access"",""request_id"":" & JsonLite_Quote(Api_RequestId()) & _
",""method"":" & JsonLite_Quote(method) & ",""action"":" & JsonLite_Quote(action) & _
",""status"":" & status & ",""duration_ms"":" & JsonLite_Num(ms) & _
",""tenant_id"":" & Obs_JStr(Api_TenantId) & ",""principal_id"":" & Obs_JStr(Api_PrincipalId) & "}"
If status >= 500 Then
console.error line
Else
console.log line
End If
End Sub

Function Obs_JStr(v)
If IsEmpty(v) Or IsNull(v) Then
Obs_JStr = "null"
ElseIf "" & v = "" Then
Obs_JStr = "null"
Else
Obs_JStr = JsonLite_Quote("" & v)
End If
End Function

' Prometheus label value escaping (backslash, quote, newline).
Function Obs_Label(s)
Obs_Label = Replace(Replace(Replace("" & s, "\", "\\"), """", "\"""), vbLf, "\n")
End Function

' Request metrics in Prometheus text format (counters and the latency histogram).
Function Obs_RequestMetrics()
Dim keys, parts, i, j, out, act, b, cum, n
out = "# HELP amk_http_requests_total API responses by action, method and status since process start." & vbLf & _
"# TYPE amk_http_requests_total counter" & vbLf
Application.Lock
keys = Split("" & Application("obs|keys|req"), vbLf)
For i = 0 To UBound(keys)
If keys(i) <> "" Then
parts = Split(keys(i), "|")
out = out & "amk_http_requests_total{action=""" & Obs_Label(parts(2)) & """,method=""" & parts(3) & _
""",status=""" & parts(4) & """} " & Application(keys(i)) & vbLf
End If
Next
out = out & "# HELP amk_http_request_duration_ms API response time in milliseconds, by action." & vbLf & _
"# TYPE amk_http_request_duration_ms histogram" & vbLf
b = Split(OBS_BUCKETS, ",")
keys = Split("" & Application("obs|keys|act"), vbLf)
For i = 0 To UBound(keys)
If keys(i) <> "" Then
act = Mid(keys(i), Len("obs|n|") + 1)
n = Application(keys(i))
For j = 0 To UBound(b)
cum = Application("obs|b|" & act & "|" & j)
If IsEmpty(cum) Then
cum = 0
End If
out = out & "amk_http_request_duration_ms_bucket{action=""" & Obs_Label(act) & """,le=""" & b(j) & """} " & cum & vbLf
Next
out = out & "amk_http_request_duration_ms_bucket{action=""" & Obs_Label(act) & """,le=""+Inf""} " & n & vbLf
out = out & "amk_http_request_duration_ms_sum{action=""" & Obs_Label(act) & """} " & _
Replace(CStr(Application("obs|sum|" & act)), ",", ".") & vbLf
out = out & "amk_http_request_duration_ms_count{action=""" & Obs_Label(act) & """} " & n & vbLf
End If
Next
out = out & "# HELP amk_process_start_time_seconds Unix time when the counters started." & vbLf & _
"# TYPE amk_process_start_time_seconds gauge" & vbLf & _
"amk_process_start_time_seconds " & Application("obs|since") & vbLf
Application.Unlock
Obs_RequestMetrics = out
End Function
%>

+ 29
- 0
core/lib.Router.asp View File

@@ -90,10 +90,39 @@ Public Function Resolve(method, path)
End If
Next

' The path exists for other methods: 405 with the allowed methods (Allow header)
Dim allow
allow = AllowedMethods(path)
If Len(allow) > 0 Then
Resolve = Array("ErrorController", "MethodNotAllowed", Array(allow))
Exit Function
End If

' 404 fallback
Resolve = Array("ErrorController", "NotFound", emptyParams)
End Function

'------------------------------------------------------------
' AllowedMethods(path) -> "GET, POST" (methods routed for this path), or ""
'------------------------------------------------------------
Public Function AllowedMethods(path)
Dim r, routeMethod, routePattern, dummy, out
out = ""
For Each r In routes.Keys
routeMethod = Split(r, ":")(0)
routePattern = Mid(r, Len(routeMethod) + 2)
If IsMatch(LCase(path), routePattern, dummy) Then
If InStr(", " & out & ",", ", " & routeMethod & ",") = 0 Then
If Len(out) > 0 Then
out = out & ", "
End If
out = out & routeMethod
End If
End If
Next
AllowedMethods = out
End Function

'------------------------------------------------------------
' INTERNAL IsMatch(requestPath, routePattern, values())
' Returns True/False and fills values() with parameters


+ 25
- 6
core/lib.Search.asp View File

@@ -12,13 +12,19 @@
' ---------------------------------------------------------------------------------------------------------------------
' Turns free text into a safe FTS5 expression: up to 16 word tokens, each double-quoted, joined with OR so bm25 ranks
' partial matches. Returns "" when the text has no usable word. Letters/digits of any script are kept.
' Common English stopwords are left out (with OR they would match nearly everything, which matters for natural-language
' tasks in /context), unless the text has nothing else.
Const SEARCH_STOPWORDS = " a an and are as at be but by can do does for from how i if in into is it its me my no not of on or our so than that the their them then there these they this to us was we were what when where which who why will with would you your "

Function Search_FtsQuery(text)
Dim t, i, c, n, tok, out, count, code
Dim t, i, c, n, tok, out, count, code, outAll, countAll
t = "" & text
n = Len(t)
tok = ""
out = ""
count = 0
outAll = ""
countAll = 0
For i = 1 To n + 1
If i <= n Then
c = Mid(t, i, 1)
@@ -27,21 +33,34 @@ Function Search_FtsQuery(text)
c = " "
code = 32
End If
If (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (c >= "0" And c <= "9") Or c = "_" Or code > 127 Then
' AscW is negative for U+8000..U+FFFF, which are word characters too
If (c >= "a" And c <= "z") Or (c >= "A" And c <= "Z") Or (c >= "0" And c <= "9") Or c = "_" Or code > 127 Or code < 0 Then
tok = tok & c
Else
If Len(tok) > 0 Then
If countAll < 16 Then
If Len(outAll) > 0 Then
outAll = outAll & " OR "
End If
outAll = outAll & """" & Left(tok, 64) & """"
countAll = countAll + 1
End If
If count < 16 Then
If Len(out) > 0 Then
out = out & " OR "
If InStr(SEARCH_STOPWORDS, " " & LCase(tok) & " ") = 0 Then
If Len(out) > 0 Then
out = out & " OR "
End If
out = out & """" & Left(tok, 64) & """"
count = count + 1
End If
out = out & """" & Left(tok, 64) & """"
count = count + 1
End If
tok = ""
End If
End If
Next
If Len(out) = 0 Then
out = outAll
End If
Search_FtsQuery = out
End Function



+ 1
- 0
core/mvc.asp View File

@@ -6,6 +6,7 @@ Function MVC_GetController(controllerName)
End Function
' Calls <Controller>_Invoke(actionName, args), defined at the bottom of each controller file.
Sub MVC_InvokeAction(controllerName, actionName, args)
Obs_Action = controllerName & "." & actionName
Dim entry : Set entry = GetRef(controllerName & "_Invoke")
entry actionName, args
End Sub


+ 33
- 0
db/migrations/20261205110945_create_embedding_index_table.asp View File

@@ -0,0 +1,33 @@
<%
'=======================================================================================================================
' MIGRATION: create_embedding_index_table
'=======================================================================================================================
' Bookkeeping for semantic (vector) indexing (spec FR-008): one row per indexed memory or chunk. The vectors live in
' the vector store (Qdrant, derived data); this table records what should be there, for which revision, with which
' model/dimensions, and whether it succeeded, so a failed or stale index can always be rebuilt from SQLite.
' status: pending (needs embedding), indexed, failed (attempts counts retries), delete (point must be removed)
'-----------------------------------------------------------------------------------------------------------------------
Sub Migration_Up(migration)
migration.ExecuteSQL "CREATE TABLE embedding_index (" & _
"target_kind TEXT NOT NULL CHECK (target_kind IN ('memory','chunk')), " & _
"target_id TEXT NOT NULL, " & _
"tenant_id TEXT NOT NULL, " & _
"namespace_id TEXT NOT NULL, " & _
"revision INTEGER NOT NULL, " & _
"status TEXT NOT NULL CHECK (status IN ('pending','indexed','failed','delete')), " & _
"model TEXT, " & _
"dimensions INTEGER, " & _
"attempts INTEGER NOT NULL DEFAULT 0, " & _
"error TEXT, " & _
"updated_at TEXT NOT NULL, " & _
"PRIMARY KEY (target_kind, target_id))"
migration.CreateIndex "idx_embedding_index_status", "embedding_index", "status, tenant_id"
migration.CreateIndex "idx_embedding_index_tenant", "embedding_index", "tenant_id"
End Sub

Sub Migration_Down(migration)
migration.DropIndex "idx_embedding_index_tenant", "embedding_index"
migration.DropIndex "idx_embedding_index_status", "embedding_index"
migration.DropTable "embedding_index"
End Sub
%>

+ 120
- 0
db/migrations/20261205113137_create_learning_and_feedback_tables.asp View File

@@ -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
%>

+ 44
- 1
docker-compose.yml View File

@@ -1,6 +1,8 @@
services:
axonasp:
image: ghcr.io/guimaraeslucas/axonasp:latest
# Pinned (AxonASP v2.3.42, tested with tests/*.sh). ":latest" changed behaviour under us once
# (ChrW above U+FFFF started to fail); bump the digest deliberately and rerun the suites.
image: ghcr.io/guimaraeslucas/axonasp@sha256:39f582e2fcdb067d0141f94896e30bbe414e6c79db274077c653b543d519a741
container_name: axonasp
ports:
- "8801:8801"
@@ -10,6 +12,47 @@ services:
# /opt/axonasp/site/db/app.sqlite. The generators (scripts/gen.cmd) and the
# migrator (scripts/migrate.cmd) also expect this layout.
SERVER_WEB_ROOT: /opt/axonasp/site/public
# GET /api/v1/metrics is enabled when this is set (16+ characters); put it in a git-ignored .env file
AMK_METRICS_TOKEN: ${AMK_METRICS_TOKEN:-}
volumes:
- .:/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:
image: ollama/ollama:0.13.0
container_name: ollama
volumes:
- ollama-models:/root/.ollama
restart: unless-stopped

# Vector index (derived data; SQLite stays the source of truth and can rebuild it).
# Reached from axonasp as http://qdrant:6333.
qdrant:
image: qdrant/qdrant:v1.16.0
container_name: qdrant
volumes:
- qdrant-data:/qdrant/storage
restart: unless-stopped

volumes:
ollama-models:
qdrant-data:

+ 18
- 0
public/Default.asp View File

@@ -30,6 +30,7 @@
' Health probes
router.AddRoute "GET", "/api/v1/health/live", "ApiHealthController", "Live"
router.AddRoute "GET", "/api/v1/health/ready", "ApiHealthController", "Ready"
router.AddRoute "GET", "/api/v1/metrics", "ApiHealthController", "Metrics"

' Documents, ingestion and search
router.AddRoute "POST", "/api/v1/ingestion/jobs", "ApiDocumentsController", "Ingest"
@@ -38,6 +39,23 @@
router.AddRoute "GET", "/api/v1/chunks/:id", "ApiDocumentsController", "Chunk"
router.AddRoute "POST", "/api/v1/search", "ApiDocumentsController", "Search"

' 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"

' Export and import of canonical records (Phase 3)
router.AddRoute "POST", "/api/v1/exports", "ApiPortabilityController", "Export"
router.AddRoute "POST", "/api/v1/imports", "ApiPortabilityController", "Import"

' 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()


+ 2308
- 444
public/api/memory-v1.openapi.json
File diff suppressed because it is too large
View File


+ 21
- 0
public/web.config View File

@@ -38,6 +38,27 @@

<!-- Cache-bust parameter name (default: "v") -->
<add key="CacheBustParamName" value="v" />

<!--
Semantic retrieval (core/lib.Embeddings.asp). EmbeddingProvider "none" = lexical only.
The ollama and qdrant services come from docker-compose.yml. Pull the model once:
docker exec ollama ollama pull nomic-embed-text
Changing the model or dimensions starts a new vector collection: run scripts\embed.cmd reindex.
-->
<!-- One JSON access-log line per API response on stdout (docker logs axonasp); "false" turns it off. -->
<add key="ApiAccessLog" value="true" />
<add key="EmbeddingProvider" value="ollama" />
<add key="EmbeddingUrl" value="http://ollama:11434" />
<add key="EmbeddingModel" value="nomic-embed-text" />
<add key="EmbeddingDimensions" value="768" />
<add key="EmbeddingDocumentPrefix" value="search_document: " />
<add key="EmbeddingQueryPrefix" value="search_query: " />
<add key="EmbeddingMinScore" value="0.6" />
<add key="VectorStoreUrl" value="http://qdrant:6333" />
<!-- Inside web requests: per-call wait for the provider/store, and the time spent indexing after a commit.
Slow hosts fall back to lexical retrieval and leave indexing to the embed-worker instead of timing out. -->
<add key="EmbeddingTimeoutMs" value="10000" />
<add key="EmbeddingWriteBudgetMs" value="8000" />
</appSettings>

<system.webServer>


+ 286
- 0
scripts/backup.asp View File

@@ -0,0 +1,286 @@
<%
' Backup, verification and restore of the SQLite database (spec NFR-005, AC-17).
' Run through scripts\backup.cmd, which sets BACKUP_ACTION and BACKUP_FILE:
'
' backup [file] consistent online copy with VACUUM INTO (default db/backups/app-YYYYMMDD-HHMMSS.sqlite),
' then verifies the copy and compares its row counts with the live database
' verify <file> PRAGMA integrity_check, foreign_key_check, latest migration and row counts per table
' restore <file> verifies <file>, keeps the current database as db/backups/pre-restore-<ts>.sqlite, then copies
' <file> over the live database. Only with the HTTP server and embed worker STOPPED
' (scripts\restore.cmd does that); afterwards run scripts\embed.cmd reindex.
'
' File names are relative to the framework folder (for example db/backups/app-20261205-120000.sqlite) or absolute
' under /opt/axonasp/site. The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site
' Prints "RESULT: ok" or "RESULT: failed" as the last line (the CLI exit code is not reliable, see AGENTS.md).
%>
<!--#include file="../core/autoload_core.asp" -->
<%
Const BK_DIR = "/db/backups"
Const BK_LIVE = "/db/app.sqlite"
Const BK_SITE = "/opt/axonasp/site"

Dim sh : Set sh = CreateObject("WScript.Shell")
Dim fso : Set fso = Server.CreateObject("Scripting.FileSystemObject")

Function Arg(name)
Dim v
v = sh.ExpandEnvironmentStrings("%" & name & "%")
If v = "%" & name & "%" Then v = ""
Arg = Trim(v)
End Function

Sub Say(msg)
Response.Write msg & vbCrLf
End Sub

Function Stamp()
Dim n
n = Now()
Stamp = Year(n) & Right("0" & Month(n), 2) & Right("0" & Day(n), 2) & "-" & _
Right("0" & Hour(n), 2) & Right("0" & Minute(n), 2) & Right("0" & Second(n), 2)
End Function

' Physical path for a file name given relative to the framework folder (or absolute under it). "" if invalid.
Function PhysPath(name)
Dim p
PhysPath = ""
p = Replace(name, "\", "/")
If InStr(p, "..") > 0 Then Exit Function
If Left(p, Len(BK_SITE) + 1) = BK_SITE & "/" Then
p = Mid(p, Len(BK_SITE) + 1)
End If
If Left(p, 1) <> "/" Then
p = "/" & p
End If
PhysPath = Server.MapPath(p)
End Function

Function SqlText(s)
SqlText = "'" & Replace(s, "'", "''") & "'"
End Function

' Opens a SQLite file with G3DB; Nothing if it cannot be opened.
Function OpenDb(path)
Dim db
Set OpenDb = Nothing
Set db = Server.CreateObject("G3DB")
If Not db.Open("sqlite", path) Then
Say "ERROR: cannot open " & path & ": " & db.LastError
Exit Function
End If
Set OpenDb = db
End Function

' Checks a database file and prints its report; returns True when it is sound. counts receives "table=n;..." text.
Function CheckDb(path, ByRef counts)
Dim db, rs, names, i, n, v, ok, fk, latest
CheckDb = False
counts = ""
If Not fso.FileExists(path) Then
Say "ERROR: no such file: " & path
Exit Function
End If
Set db = OpenDb(path)
If db Is Nothing Then
Exit Function
End If
ok = True

Set rs = db.Query("PRAGMA integrity_check")
If IsEmpty(rs) Then
Say "ERROR: integrity_check failed: " & db.LastError
db.Close
Exit Function
End If
v = ""
Do While Not rs.EOF
v = v & rs(0) & " "
rs.MoveNext
Loop
rs.Close
v = Trim(v)
Say "integrity_check: " & v
If v <> "ok" Then
ok = False
End If

Set rs = db.Query("PRAGMA foreign_key_check")
fk = 0
If Not IsEmpty(rs) Then
Do While Not rs.EOF
fk = fk + 1
rs.MoveNext
Loop
rs.Close
End If
Say "foreign_key_violations: " & fk
If fk > 0 Then
ok = False
End If

Set rs = db.Query("SELECT MAX(version) FROM schema_migrations")
latest = ""
If Not IsEmpty(rs) Then
If Not rs.EOF Then
latest = "" & rs(0)
End If
rs.Close
End If
Say "latest_migration: " & latest
If latest = "" Then
ok = False
End If

' Table names first (close the result set before counting).
names = ""
Set rs = db.Query("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
If Not IsEmpty(rs) Then
Do While Not rs.EOF
names = names & rs(0) & vbLf
rs.MoveNext
Loop
rs.Close
End If
names = Split(names, vbLf)
For i = 0 To UBound(names) - 1
Set rs = db.Query("SELECT COUNT(*) FROM """ & Replace(names(i), """", """""") & """")
n = "?"
If Not IsEmpty(rs) Then
If Not rs.EOF Then
n = "" & rs(0)
End If
rs.Close
End If
counts = counts & names(i) & "=" & n & ";"
Next
db.Close
Say "tables: " & (UBound(names))
CheckDb = ok
End Function

Function DoBackup()
Dim target, db, res, counts, liveCounts, sz, t0
DoBackup = False
If Arg("BACKUP_FILE") = "" Then
If Not fso.FolderExists(Server.MapPath(BK_DIR)) Then
fso.CreateFolder Server.MapPath(BK_DIR)
End If
target = Server.MapPath(BK_DIR & "/app-" & Stamp() & ".sqlite")
Else
target = PhysPath(Arg("BACKUP_FILE"))
End If
If target = "" Then
Say "ERROR: invalid file name"
Exit Function
End If
If fso.FileExists(target) Then
Say "ERROR: file exists: " & target
Exit Function
End If
Set db = OpenDb(Server.MapPath(BK_LIVE))
If db Is Nothing Then
Exit Function
End If
t0 = Timer
' VACUUM INTO writes a consistent, compacted copy while the server keeps running (readers and writers wait).
Set res = db.Exec("VACUUM INTO " & SqlText(target))
If IsEmpty(res) Then
Say "ERROR: VACUUM INTO failed: " & db.LastError
db.Close
Exit Function
End If
db.Close
sz = fso.GetFile(target).Size
Say "backup: " & target
Say "bytes: " & sz
Say "seconds: " & FormatNumber(Timer - t0, 2, -1, 0, 0)
If Not CheckDb(target, counts) Then
Exit Function
End If
Say "-- live database"
If Not CheckDb(Server.MapPath(BK_LIVE), liveCounts) Then
Exit Function
End If
If counts = liveCounts Then
Say "row_counts: match"
Else
' A write between the copy and the comparison also gives a difference; rerun verify if the server is busy.
Say "row_counts: differ (backup " & counts & " live " & liveCounts & ")"
End If
DoBackup = True
End Function

Function DoVerify()
Dim path, counts
DoVerify = False
path = PhysPath(Arg("BACKUP_FILE"))
If path = "" Then
Say "ERROR: give the backup file (BACKUP_FILE)"
Exit Function
End If
If Not CheckDb(path, counts) Then
Exit Function
End If
Say "row_counts: " & counts
DoVerify = True
End Function

Function DoRestore()
Dim src, live, safety, counts, f
DoRestore = False
src = PhysPath(Arg("BACKUP_FILE"))
live = Server.MapPath(BK_LIVE)
If src = "" Then
Say "ERROR: give the backup file (BACKUP_FILE)"
Exit Function
End If
If LCase(src) = LCase(live) Then
Say "ERROR: the backup is the live database"
Exit Function
End If
If Not CheckDb(src, counts) Then
Say "ERROR: the backup did not verify; nothing was changed"
Exit Function
End If
If fso.FileExists(live) Then
If Not fso.FolderExists(Server.MapPath(BK_DIR)) Then
fso.CreateFolder Server.MapPath(BK_DIR)
End If
safety = Server.MapPath(BK_DIR & "/pre-restore-" & Stamp() & ".sqlite")
fso.CopyFile live, safety, False
Say "previous database kept as: " & safety
End If
For Each f In Array(live & "-wal", live & "-shm", live & "-journal")
If fso.FileExists(f) Then
fso.DeleteFile f, True
End If
Next
fso.CopyFile src, live, True
Say "restored: " & src & " -> " & live
Say "-- restored database"
If Not CheckDb(live, counts) Then
Exit Function
End If
Say "row_counts: " & counts
DoRestore = True
End Function

Dim action, ok
action = LCase(Arg("BACKUP_ACTION"))
ok = False
Select Case action
Case "backup"
ok = DoBackup()
Case "verify"
ok = DoVerify()
Case "restore"
ok = DoRestore()
Case Else
Say "Usage: BACKUP_ACTION=backup|verify|restore [BACKUP_FILE=db/backups/<file>.sqlite]"
End Select
If ok Then
Say "RESULT: ok"
Else
Say "RESULT: failed"
End If
%>

+ 18
- 0
scripts/backup.cmd View File

@@ -0,0 +1,18 @@
@echo off
rem SQLite backup and verification, run inside the "axonasp" container (the server keeps running).
rem
rem scripts\backup.cmd backup [file] consistent copy (VACUUM INTO) to db\backups\app-YYYYMMDD-HHMMSS.sqlite
rem or [file], then integrity check and row-count comparison with the live db
rem scripts\backup.cmd verify <file> integrity check, foreign keys, latest migration, row counts per table
rem
rem File names are relative to the repo root, for example db/backups/app-20261205-120000.sqlite.
rem To restore, use scripts\restore.cmd <file>. The last line printed is "RESULT: ok" or "RESULT: failed".
setlocal
set CMD=%~1
if "%CMD%"=="" set CMD=backup
if /i "%CMD%"=="restore" (
echo Use scripts\restore.cmd ^<file^>: it stops the server first.
exit /b 1
)
docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "BACKUP_ACTION=%CMD%" -e "BACKUP_FILE=%~2" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp
exit /b %errorlevel%

+ 107
- 0
scripts/embed.asp View File

@@ -0,0 +1,107 @@
<%
' Semantic index maintenance (see core/lib.Embeddings.asp). Run through scripts\embed.cmd, which sets EMBED_ACTION:
' 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" -->
<%
Dim sh : Set sh = CreateObject("WScript.Shell")
Emb_TimeoutMs = 60000 ' the worker may wait for a slow provider (web requests use EmbeddingTimeoutMs)
Dim action : action = LCase(Trim(sh.ExpandEnvironmentStrings("%EMBED_ACTION%")))
Dim rs, total, n, rounds, ts

Sub ShowStatus()
Dim r
Response.Write "provider: " & Emb_Setting("EmbeddingProvider", "none") & vbCrLf
Response.Write "model: " & Emb_Model() & " (" & Emb_Dims() & " dimensions)" & vbCrLf
Response.Write "collection: " & Emb_Collection() & vbCrLf
Set r = DAL().Query("SELECT status, COUNT(*) FROM embedding_index GROUP BY status ORDER BY status", Empty)
Do While Not r.EOF
Response.Write " " & r(0) & ": " & r(1) & vbCrLf
r.MoveNext
Loop
r.Close
Set r = DAL().Query("SELECT COUNT(*) FROM embedding_index WHERE status = 'indexed' AND (model <> ? OR dimensions <> ?)", Array(Emb_Model(), Emb_Dims()))
If Not r.EOF Then
If CLng(r(0)) > 0 Then
Response.Write " stale (other model): " & r(0) & " -> run: scripts\embed.cmd reindex" & vbCrLf
End If
End If
r.Close
Set r = DAL().Query("SELECT error FROM embedding_index WHERE status = 'failed' ORDER BY updated_at DESC LIMIT 1", Empty)
If Not r.EOF Then
Response.Write " last error: " & r(0) & vbCrLf
End If
r.Close
End Sub

Sub RunAll()
total = 0
rounds = 0
Do
Emb_LastError = ""
n = Emb_ProcessPending("", 64)
total = total + n
rounds = rounds + 1
If n = 0 Or rounds > 10000 Then
Exit Do
End If
Loop
Response.Write "indexed: " & total & vbCrLf
If Len(Emb_LastError) > 0 Then
Response.Write "ERROR: " & Emb_LastError & vbCrLf
End If
End Sub

Select Case action
Case "status"
ShowStatus
Case "run"
If Not Emb_Enabled() Then
Response.Write "EmbeddingProvider is not ollama in public/web.config; nothing to do." & vbCrLf
Else
DAL().Execute "UPDATE embedding_index SET status = 'pending', attempts = 0 WHERE status = 'failed'", Empty
RunAll
ShowStatus
End If
Case "reindex"
If Not Emb_Enabled() Then
Response.Write "EmbeddingProvider is not ollama in public/web.config; nothing to do." & vbCrLf
Else
ts = Api_Now()
' rows for everything that should be indexed (missing ones are added), all set to pending
DAL().Execute "INSERT OR IGNORE INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _
"SELECT 'memory', m.id, m.tenant_id, m.namespace_id, m.current_revision, 'pending', 0, ? FROM memories m WHERE m.lifecycle_status = 'active'", ts
DAL().Execute "INSERT OR IGNORE INTO embedding_index (target_kind, target_id, tenant_id, namespace_id, revision, status, attempts, updated_at) " & _
"SELECT 'chunk', c.id, d.tenant_id, d.namespace_id, c.document_revision, 'pending', 0, ? FROM chunks c JOIN documents d ON d.id = c.document_id " & _
"WHERE c.document_revision = d.current_revision", ts
DAL().Execute "UPDATE embedding_index SET status = 'pending', attempts = 0, error = NULL, updated_at = ? WHERE status <> 'delete'", ts
RunAll
ShowStatus
End If
Case "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
%>

+ 12
- 0
scripts/embed.cmd View File

@@ -0,0 +1,12 @@
@echo off
rem Semantic index maintenance, run inside the "axonasp" container.
rem
rem scripts\embed.cmd status counts per status, model and collection
rem scripts\embed.cmd run embed every pending/failed memory and chunk (resets failed attempts first)
rem scripts\embed.cmd reindex mark every active memory and current chunk pending, then run
rem (after changing EmbeddingModel/EmbeddingDimensions, or to rebuild the vector store)
setlocal
set CMD=%1
if "%CMD%"=="" set CMD=status
docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "EMBED_ACTION=%CMD%" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp
exit /b %errorlevel%

+ 43
- 0
scripts/kb.sh View File

@@ -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

+ 40
- 0
scripts/ops.sh View File

@@ -0,0 +1,40 @@
#!/usr/bin/env bash
# Linux/macOS equivalents of the scripts\*.cmd tools, for a server deployment (run from the repo root on the host
# that runs the "axonasp" container).
#
# bash scripts/ops.sh migrate [up|down|status] schema migrations (run "up" once per pending migration)
# bash scripts/ops.sh provision <action> [args...] same actions as scripts\provision.cmd
# bash scripts/ops.sh embed [status|run|reindex] semantic index maintenance
# bash scripts/ops.sh backup [file] online backup to db/backups/ and verification
# bash scripts/ops.sh verify <file> verify a backup file
# bash scripts/ops.sh restore <file> stop, verify, restore, start, reindex (see README)
set -eu
cd "$(dirname "$0")/.."
cli() { docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site "$@"; }
cmd=${1:-}; [ $# -gt 0 ] && shift
case "$cmd" in
migrate)
cli -e "MIGRATE=${1:-up}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/migrate.asp ;;
provision)
[ $# -ge 1 ] || { echo "usage: ops.sh provision <action> [args...]" >&2; exit 1; }
cli -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 ;;
embed)
cli -e "EMBED_ACTION=${1:-status}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp ;;
backup|verify)
cli -e "BACKUP_ACTION=$cmd" -e "BACKUP_FILE=${1:-}" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp ;;
restore)
[ $# -ge 1 ] || { echo "usage: ops.sh restore db/backups/<file>.sqlite" >&2; exit 1; }
docker compose stop axonasp embed-worker
log=$(docker compose run --rm --no-deps -T -e SERVER_WEB_ROOT=/opt/axonasp/site -e BACKUP_ACTION=restore \
-e "BACKUP_FILE=$1" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 || true)
echo "$log"
docker compose start axonasp embed-worker
if ! grep -q '^RESULT: ok' <<<"$log"; then
echo "Restore FAILED, see above. If the copy had started, the previous database is in db/backups/pre-restore-*.sqlite." >&2
exit 1
fi
"$0" embed reindex ;;
*)
sed -n '2,11p' "$0"; exit 1 ;;
esac

+ 8
- 0
scripts/provision.asp View File

@@ -181,7 +181,15 @@ Select Case action
If Not TenantExists(a1) Then
Fail "usage: purge <tenant_id> (tenant must exist)"
Else
' 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


+ 29
- 0
scripts/restore.cmd View File

@@ -0,0 +1,29 @@
@echo off
rem Restores the SQLite database from a backup made by scripts\backup.cmd. Run from the repo root.
rem
rem scripts\restore.cmd db/backups/app-YYYYMMDD-HHMMSS.sqlite
rem
rem 1. stops the HTTP server and the embed worker (nothing may write during the copy)
rem 2. verifies the backup (integrity_check, foreign keys, migrations); if it fails nothing is changed
rem 3. keeps the current database as db\backups\pre-restore-<timestamp>.sqlite and copies the backup over it
rem 4. starts the server and the worker again, then rebuilds the vector index from the restored data
rem (Qdrant is derived data and may hold vectors for rows the backup does not have)
rem If the restored schema is older than the code, run scripts\migrate.cmd up afterwards.
setlocal
if "%~1"=="" (
echo Usage: scripts\restore.cmd db/backups/^<file^>.sqlite
exit /b 1
)
docker compose stop axonasp embed-worker || exit /b 1
docker compose run --rm --no-deps -T -e SERVER_WEB_ROOT=/opt/axonasp/site -e BACKUP_ACTION=restore -e "BACKUP_FILE=%~1" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp > "%TEMP%\amk-restore.log"
set RC=%errorlevel%
type "%TEMP%\amk-restore.log"
docker compose start axonasp embed-worker
findstr /b /c:"RESULT: ok" "%TEMP%\amk-restore.log" >nul
if errorlevel 1 (
echo Restore FAILED, see the messages above. If the backup did not verify, nothing was changed; if the copy
echo had started, the previous database is in db\backups\pre-restore-^<timestamp^>.sqlite.
exit /b 1
)
call "%~dp0embed.cmd" reindex
exit /b 0

+ 12
- 3
scripts/templates/Api.tpl.asp View File

@@ -18,6 +18,7 @@ Const {{CONST}}_MAX_PER_PAGE = 100

Class Api{{TABLE}}Controller_Class
{{MEMBERS}}
Private m_unsupportedChar ' set by Utf8Decode for code points above U+FFFF

' Dispatcher reads this to decide whether to wrap the output in the HTML layout
Public Property Get useLayout()
@@ -239,12 +240,18 @@ Class Api{{TABLE}}Controller_Class
Exit Function
End If
' AxonASP: BinaryRead returns one character per byte, so decode the UTF-8 by hand.
m_unsupportedChar = False
text = Utf8Decode(CStr(Request.BinaryRead(n)))

If JsonLite_Parse(text) Is Nothing Then
SendError 400, "Body must be a valid JSON object."
Exit Function
End If
' Reject rather than store damaged text (see Utf8Decode)
If m_unsupportedChar Or JsonLite_SurrogateSeen Then
SendError 422, "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them."
Exit Function
End If
ReadBodyText = text
End Function

@@ -284,9 +291,11 @@ Class Api{{TABLE}}Controller_Class
Next
End If
If ok And cp <= 1114111 Then
If cp >= 65536 Then
cp = cp - 65536
out = out & ChrW(55296 + Int(cp / 1024)) & ChrW(56320 + (cp Mod 1024))
' AxonASP (pinned build): ChrW above U+FFFF fails and surrogate pairs come out as CESU-8, so these
' code points are flagged and ReadBodyText answers 422.
If cp > 65535 Or (cp >= 55296 And cp <= 57343) Then
m_unsupportedChar = True
out = out & ChrW(65533)
Else
out = out & ChrW(cp)
End If


+ 106
- 0
tests/backup-restore.sh View File

@@ -0,0 +1,106 @@
#!/usr/bin/env bash
# Backup and restore drill (spec NFR-005, AC-17): an online backup of the live database verifies (integrity_check,
# foreign keys, migrations, row counts), a damaged or missing file is refused, and the backup restored into an isolated
# environment (a separate container on port 8802 with its own db folder; the live database is never touched) serves
# the same data: the export of a test tenant from the restored copy equals the export from the live server.
# The restore time is measured against RTO_SECONDS (default 120); RPO is the backup interval (see README).
#
# Needs the compose stack running (container "axonasp", http://localhost:8801). Creates a throw-away tenant, one
# backup file under db/backups and a scratch folder db/backups/drill-*, and removes all of them at the end.
# bash tests/backup-restore.sh
set -u
BASE=${BASE:-http://localhost:8801/api/v1}
ISO_PORT=${ISO_PORT:-8802}
ISO_BASE=http://localhost:$ISO_PORT/api/v1
RTO_SECONDS=${RTO_SECONDS:-120}
IMAGE=$(docker inspect axonasp --format '{{.Config.Image}}')
REPO=$(cd "$(dirname "$0")/.." && pwd -W)
TAG=drill-$$-$RANDOM
BK=db/backups/$TAG.sqlite
ISO=db/backups/$TAG
ISO_NAME=amk-restore-$TAG
PASS=0; FAIL=0; FAILED=(); TENANT=""
export MSYS_NO_PATHCONV=1
prov() {
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 '\015'
}
bak() { # bak <action> [file] (in the live container)
docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "BACKUP_ACTION=$1" -e "BACKUP_FILE=${2:-}" \
axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 | tr -d '\015'
}
iso_run() { # one-off container with the isolated db folder (what scripts/restore.cmd does, minus the live db)
docker run --rm -v "$REPO:/opt/axonasp/site" -v "$REPO/$ISO:/opt/axonasp/site/db" \
-e SERVER_WEB_ROOT=/opt/axonasp/site -e "BACKUP_ACTION=$1" -e "BACKUP_FILE=${2:-}" \
"$IMAGE" ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 | tr -d '\015'
}
field() { sed -n "s/.*$1: *\([^ ]*\).*/\1/p" | head -1; }
jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
last() { grep '^RESULT:' | tail -1; }
check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
data_of() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');print(json.dumps(json.load(sys.stdin)['data'],sort_keys=True))"; }
sha() { sha256sum "$1" | cut -c1-64; }
cleanup() {
docker rm -f "$ISO_NAME" >/dev/null 2>&1
[ -n "$TENANT" ] && prov purge "$TENANT" >/dev/null
rm -rf "$REPO/$ISO" "$REPO/$BK" "$REPO/$BK-damaged"
}
trap cleanup EXIT
cd "$REPO" || exit 2

# ---- test data in the live database ----------------------------------------------------------------------------
TENANT=$(prov tenant "drill" | field tenant_id)
OUT=$(prov principal "$TENANT" drill-owner human); PID=$(echo "$OUT" | field principal_id); KEY=$(echo "$OUT" | field api_key)
prov grant "$PID" /drill "read,write,admin" 1 >/dev/null
NS=$(prov namespace "$TENANT" /drill | field namespace_id)
[ -n "$NS" ] && [ -n "$KEY" ] || { echo "setup failed"; exit 2; }
auth=(-H "Authorization: Bearer $KEY")
MID=$(curl -s "${auth[@]}" -X POST "$BASE/remember" -d "{\"namespace_id\":\"$NS\",\"type\":\"decision\",\"title\":\"Drill fact\",\"content\":\"Backups are taken with VACUUM INTO.\"}" | jget id)
curl -s -o /dev/null "${auth[@]}" -X POST "$BASE/memories/$MID/verifications" -d '{"result":"verified","method":"manual","revision":1}'
curl -s -o /dev/null "${auth[@]}" -X POST "$BASE/ingestion/jobs" -d "{\"namespace_id\":\"$NS\",\"title\":\"Drill runbook\",\"format\":\"markdown\",\"content\":\"# Restore\n\nStop the server, copy, start, reindex.\"}"
[ -n "$MID" ] || { echo "data setup failed"; exit 2; }

# ---- backup and verify (live container, server running) --------------------------------------------------------
OUT=$(bak backup "$BK")
check "backup -> ok" "RESULT: ok" "$(echo "$OUT" | last)"
check "backup integrity_check ok" "ok" "$(echo "$OUT" | field integrity_check)"
check "backup row counts match live" "match" "$(echo "$OUT" | field row_counts)"
check "backup file exists" "yes" "$([ -s "$BK" ] && echo yes || echo no)"
check "backup to an existing file -> failed" "RESULT: failed" "$(bak backup "$BK" | last)"
check "backup path with .. -> failed" "RESULT: failed" "$(bak backup "db/../x.sqlite" | last)"
check "verify backup -> ok" "RESULT: ok" "$(bak verify "$BK" | last)"
check "verify missing file -> failed" "RESULT: failed" "$(bak verify "db/backups/none-$TAG.sqlite" | last)"
python -I -c "import sys;b=bytearray(open(sys.argv[1],'rb').read());n=len(b)//2;b[n:n+20000]=b'\xa5'*20000;open(sys.argv[2],'wb').write(b)" "$BK" "$BK-damaged"
check "verify damaged file -> failed" "RESULT: failed" "$(bak verify "$BK-damaged" | last)"
LIVE_EXPORT=$(curl -s "${auth[@]}" -X POST "$BASE/exports" -d '{}' | data_of)

# ---- restore into an isolated environment ----------------------------------------------------------------------
mkdir -p "$ISO"
cp "$BK" "$ISO/backup.sqlite"; cp "$BK-damaged" "$ISO/damaged.sqlite"
OUT=$(iso_run restore db/damaged.sqlite)
check "restore of a damaged backup -> failed" "RESULT: failed" "$(echo "$OUT" | last)"
check "failed restore created no database" "no" "$([ -e "$ISO/app.sqlite" ] && echo yes || echo no)"
T0=$(date +%s)
OUT=$(iso_run restore db/backup.sqlite)
check "isolated restore -> ok" "RESULT: ok" "$(echo "$OUT" | last)"
check "restored file equals the backup" "$(sha "$BK")" "$(sha "$ISO/app.sqlite")"
docker run -d --name "$ISO_NAME" -p "$ISO_PORT:8801" -v "$REPO:/opt/axonasp/site" -v "$REPO/$ISO:/opt/axonasp/site/db" \
-e SERVER_WEB_ROOT=/opt/axonasp/site/public "$IMAGE" >/dev/null
for i in $(seq 1 60); do curl -s -o /dev/null "$ISO_BASE/health/live" && break; sleep 1; done
RTO=$(( $(date +%s) - T0 ))
check "restored server healthy within RTO (${RTO}s <= ${RTO_SECONDS}s)" "yes" "$([ "$(curl -s -o /dev/null -w '%{http_code}' "$ISO_BASE/health/live")" = 200 ] && [ "$RTO" -le "$RTO_SECONDS" ] && echo yes || echo no)"
R=$(curl -s "${auth[@]}" "$ISO_BASE/memories/$MID")
check "restored: API key works, memory present" "Backups are taken with VACUUM INTO." "$(echo "$R" | python -I -c "import sys,json;print(json.load(sys.stdin)['data']['content'])")"
check "restored: verification kept" "verified" "$(echo "$R" | python -I -c "import sys,json;print(json.load(sys.stdin)['data']['verification_status'])")"
check "restored: lexical search works" "yes" "$(curl -s "${auth[@]}" -X POST "$ISO_BASE/search" -d '{"query":"reindex"}' | grep -q '"chunk_id"' && echo yes || echo no)"
check "restored export equals live export" "yes" "$([ "$(curl -s "${auth[@]}" -X POST "$ISO_BASE/exports" -d '{}' | data_of)" = "$LIVE_EXPORT" ] && echo yes || echo no)"
check "restore kept no pre-restore copy (no previous db)" "0" "$(ls "$ISO"/backups 2>/dev/null | grep -c pre-restore)"
OUT=$(docker exec "$ISO_NAME" sh -c 'BACKUP_ACTION=restore BACKUP_FILE=db/backup.sqlite SERVER_WEB_ROOT=/opt/axonasp/site ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp' 2>&1 | tr -d '\015')
check "second restore keeps the previous db" "1" "$(ls "$ISO"/backups 2>/dev/null | grep -c pre-restore)"
check "live server unaffected" "200" "$(curl -s -o /dev/null -w '%{http_code}' "${auth[@]}" "$BASE/memories/$MID")"

echo "restore time: ${RTO}s (RTO target ${RTO_SECONDS}s)"
echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

+ 99
- 0
tests/observability.sh View File

@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# Observability checks (spec NFR-004, FR-019): correlation ids (a caller's X-Request-Id is echoed and logged, an
# unsafe one is replaced), one structured access-log line per API response without secrets, request counters and a
# latency histogram, installation-wide gauges, and the metrics endpoint's protection (token, method, disabled state).
#
# Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). The metrics checks
# need AMK_METRICS_TOKEN set for the container (git-ignored .env, then docker compose up -d); without it only the
# "disabled -> 404" check runs. Restarts the container once; creates and purges a throw-away tenant.
# bash tests/observability.sh
set -u
BASE=${BASE:-http://localhost:8801/api/v1}
PASS=0; FAIL=0; FAILED=(); TENANT=""
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 '\015'
}
field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
cleanup() { [ -n "$TENANT" ] && prov purge "$TENANT" >/dev/null; }
trap cleanup EXIT
restart() { docker restart axonasp >/dev/null; for i in $(seq 1 30); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done; }
# access-log JSON lines written since the container started
logs() { docker logs axonasp 2>&1 | grep -o '{"log":"access".*'; }
TOKEN=$(MSYS_NO_PATHCONV=1 docker exec axonasp printenv AMK_METRICS_TOKEN 2>/dev/null | tr -d '\015')
metrics() { curl -s -H "Authorization: Bearer $TOKEN" "$BASE/metrics"; }
# value of one sample line, e.g. metric 'amk_http_requests_total{action="ApiHealthController.Live",method="GET",status="200"}'
sample() { grep -F "$1 " | grep -v "^#" | head -1 | awk '{print $NF}'; }

TENANT=$(prov tenant "obs" | field tenant_id)
OUT=$(prov principal "$TENANT" obs-agent agent); PID=$(echo "$OUT" | field principal_id); KEY=$(echo "$OUT" | field api_key)
prov grant "$PID" /obs "read,write" 1 >/dev/null
NS=$(prov namespace "$TENANT" /obs | field namespace_id)
[ -n "$NS" ] && [ -n "$KEY" ] || { echo "setup failed"; exit 2; }

restart
# ---- correlation ids and access log ------------------------------------------------------------------------------
RID="obs-test-$RANDOM-$RANDOM"
H=$(curl -s -D - -o /dev/null -H "X-Request-Id: $RID" -H "Authorization: Bearer $KEY" -X POST "$BASE/remember" \
-d "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"Obs\",\"content\":\"secret-ish body text 4711\"}" | tr -d '\015')
check "cold: write with caller request id -> 201" "201" "$(echo "$H" | sed -n 's/^HTTP\/[0-9.]* \([0-9]*\).*/\1/p' | head -1)"
check "caller X-Request-Id echoed" "$RID" "$(echo "$H" | sed -n 's/^[Xx]-[Rr]equest-[Ii]d: *//p')"
BADH=$(curl -s -D - -o /dev/null -H 'X-Request-Id: bad id with spaces' "$BASE/health/live" | tr -d '\015' | sed -n 's/^[Xx]-[Rr]equest-[Ii]d: *//p')
check "unsafe X-Request-Id replaced" "yes" "$([[ "$BADH" == req-* ]] && echo yes || echo no)"
LONGH=$(curl -s -D - -o /dev/null -H "X-Request-Id: $(printf 'a%.0s' $(seq 1 80))" "$BASE/health/live" | tr -d '\015' | sed -n 's/^[Xx]-[Rr]equest-[Ii]d: *//p')
check "over-long X-Request-Id replaced" "yes" "$([[ "$LONGH" == req-* ]] && echo yes || echo no)"
ERR=$(curl -s -H "X-Request-Id: $RID-404" -H "Authorization: Bearer $KEY" "$BASE/memories/00000000-0000-0000-0000-000000000000")
check "error body carries the request id" "yes" "$(grep -q "\"request_id\":\"$RID-404\"" <<<"$ERR" && echo yes || echo no)"
LINE=$(logs | grep -F "\"request_id\":\"$RID\"" | head -1)
check "access log line for the write" "201 ApiMemoriesController.Remember POST $TENANT $PID" \
"$(python -I -c "import sys,json;d=json.loads(sys.argv[1]);print(d['status'],d['action'],d['method'],d['tenant_id'],d['principal_id'])" "$LINE" 2>&1)"
check "access log has a duration" "yes" "$(python -I -c "import sys,json;d=json.loads(sys.argv[1]);print('yes' if d['duration_ms']>=0 else 'no')" "$LINE" 2>&1)"
check "404 logged with its request id" "404" "$(logs | grep -F "\"request_id\":\"$RID-404\"" | python -I -c "import sys,json;print(json.loads(sys.stdin.readline())['status'])" 2>&1)"
ALL=$(docker logs axonasp 2>&1)
check "no API key in the logs" "no" "$(grep -qF "$KEY" <<<"$ALL" && echo yes || echo no)"
check "no request body in the logs" "no" "$(grep -qF "secret-ish body text 4711" <<<"$ALL" && echo yes || echo no)"
check "unauthenticated request logged without identity" "null" "$(logs | grep -F '"action":"ApiHealthController.Live"' | tail -1 | python -I -c "import sys,json;print(json.dumps(json.loads(sys.stdin.readline())['tenant_id']))" 2>&1)"

# ---- metrics -----------------------------------------------------------------------------------------------------
if [ ${#TOKEN} -lt 16 ]; then
check "metrics disabled without a token -> 404" "404" "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/metrics")"
echo "AMK_METRICS_TOKEN is not set for the container: metrics checks skipped"
else
check "metrics without token -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' "$BASE/metrics")"
check "metrics with an API key -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $KEY" "$BASE/metrics")"
check "metrics wrong method -> 405" "405" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $TOKEN" "$BASE/metrics")"
check "metrics content type" "text/plain; version=0.0.4; charset=utf-8" \
"$(curl -s -D - -o /dev/null -H "Authorization: Bearer $TOKEN" "$BASE/metrics" | tr -d '\015' | sed -n 's/^[Cc]ontent-[Tt]ype: *//p')"
LIVE='amk_http_requests_total{action="ApiHealthController.Live",method="GET",status="200"}'
B1=$(metrics | sample "$LIVE"); B1=${B1:-0}
for i in 1 2 3 4 5; do curl -s -o /dev/null "$BASE/health/live"; done
M=$(metrics)
check "request counter counts exactly" "$((B1 + 5))" "$(echo "$M" | sample "$LIVE")"
check "401s are counted" "yes" "$(echo "$M" | grep -q 'action="ApiHealthController.Metrics",method="GET",status="401"' && echo yes || echo no)"
check "write is counted" "1" "$(echo "$M" | sample 'amk_http_requests_total{action="ApiMemoriesController.Remember",method="POST",status="201"}')"
check "histogram +Inf bucket equals count" "yes" "$(echo "$M" | python -I -c "
import sys,re
t=sys.stdin.read()
inf=re.search(r'amk_http_request_duration_ms_bucket\{action=\"ApiHealthController.Live\",le=\"\+Inf\"\} (\d+)',t).group(1)
cnt=re.search(r'amk_http_request_duration_ms_count\{action=\"ApiHealthController.Live\"\} (\d+)',t).group(1)
b=[int(x) for x in re.findall(r'amk_http_request_duration_ms_bucket\{action=\"ApiHealthController.Live\",le=\"[0-9]+\"\} (\d+)',t)]
print('yes' if inf==cnt and b==sorted(b) and b[-1]<=int(inf) else 'no')")"
check "gauges: memories" "yes" "$(echo "$M" | grep -q '^amk_memories{status="active"} [0-9]' && echo yes || echo no)"
curl -s -o /dev/null -H "Authorization: Bearer $KEY" -X POST "$BASE/recall" -d '{"query":"zzqx unmatched term"}'
M2=$(metrics)
R1=$(echo "$M" | sample 'amk_retrieval_empty_total{operation="recall"}'); R2=$(echo "$M2" | sample 'amk_retrieval_empty_total{operation="recall"}')
check "retrieval metrics: empty recall counted" "$(( ${R1:-0} + 1 ))" "${R2:-0}"
check "metrics carry no tenant ids" "no" "$(grep -qF "$TENANT" <<<"$M2" && echo yes || echo no)"
check "metrics every line well-formed" "0" "$(echo "$M2" | grep -v '^# \(HELP\|TYPE\) ' | grep -cvE '^[a-z_]+(\{[a-z_]+="[^"]*"(,[a-z_]+="[^"]*")*\})? -?[0-9.e+]+$')"
S1=$(echo "$M2" | sample amk_process_start_time_seconds)
sleep 1; restart
M3=$(metrics)
check "restart resets counters" "1" "$(echo "$M3" | grep -c '^amk_http_requests_total')"
check "restart moves the start time" "yes" "$([ "$(echo "$M3" | sample amk_process_start_time_seconds)" -gt "${S1:-0}" ] && echo yes || echo no)"
fi

echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

+ 17
- 2
tests/phase1-api.sh View File

@@ -16,6 +16,7 @@ prov() { # prov <action> [arg1 arg2 arg3 arg4]
axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r'
}
field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } # field <name> from provision output
has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; }
jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; } # first "name":"value" in a JSON text

cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; }
@@ -145,11 +146,17 @@ check "state must be object -> 422" "422" "$(code "$WK" PUT /sessions/$SID/state
check "complete -> 200" "200" "$(code "$WK" POST /sessions/$SID/complete -d '{"outcome":"ok"}')"
check "save after complete -> 409" "409" "$(code "$WK" PUT /sessions/$SID/state -H 'If-Match: 2' -d '{"state":{"s":3}}')"

# ---- UTF-8 round trip (BMP and beyond) -------------------------------------------------------------------
U=$'caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac \xf0\x9f\x98\x80'
# ---- UTF-8 round trip (BMP); characters above U+FFFF are rejected (pinned runtime cannot hold them) -------
U=$'caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac'
UJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"utf8","content":"%s"}' "$NSA" "$U")
UID_=$(printf '%s' "$UJ" | curl -s -X POST -H "Authorization: Bearer $WK" --data-binary @- "$BASE/remember" | jget id)
check "utf-8 content round trip" "yes" "$(body "$WK" GET /memories/$UID_ | grep -qF "$U" && echo yes || echo no)"
EJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"emoji","content":"x %s"}' "$NSA" $'\xf0\x9f\x98\x80')
check "raw emoji -> 422" "422" "$(printf '%s' "$EJ" | curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $WK" --data-binary @- "$BASE/remember")"
# escaped surrogate pair; the backslashes are produced at run time so no tool or shell can pre-decode them
SJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"emoji","content":"x %sud83d%sude00"}' "$NSA" '\' '\')
check "escaped surrogate pair -> 422" "422" "$(code "$WK" POST /remember --data-binary "$SJ")"
check "unsupported_character code" "yes" "$(has unsupported_character "$(body "$WK" POST /remember --data-binary "$SJ")")"

# ---- revoked key, restart persistence (AC-01), cold first request ----------------------------------------
KID=$(prov key "$WID" | field api_key_id); KK=$(prov key "$WID" | field api_key)
@@ -163,6 +170,14 @@ check "after restart: write works first (cold)" "201" "$(code "$WK" POST /rememb
check "after restart: memory persisted" "200" "$(code "$WK" GET /memories/$M1)"
check "after restart: checkpoint persisted" "yes" "$(body "$WK" GET /sessions/$SID/state | grep -q '"step":2' && echo yes || echo no)"

# ---- routing: wrong method and unknown API path ------------------------------------------------------------
R=$(curl -s -i -X DELETE "$BASE/recall")
check "wrong method -> 405" "yes" "$(grep -q '^HTTP/1.1 405' <<<"$R" && echo yes || echo no)"
check "405 carries Allow" "yes" "$(grep -qi '^Allow: POST' <<<"$R" && echo yes || echo no)"
check "405 body is JSON error" "yes" "$(has '"code":"method_not_allowed"' "$R")"
check "unknown API path -> JSON 404" "yes" "$(curl -s "$BASE/no-such-endpoint" | grep -q '"code":"not_found"' && echo yes || echo no)"
check "unknown page stays 404" "404" "$(curl -s -o /dev/null -w '%{http_code}' "${BASE%/api/v1}/no-such-page")"

echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

+ 168
- 0
tests/phase3-context.sh View File

@@ -0,0 +1,168 @@
#!/usr/bin/env bash
# Phase 3 checks for POST /context (spec FR-010, section 9.3, AC-05): sections, constraints loaded by scope,
# verification and lifecycle filtering, conflicts, deduplication, token budget (incl. the 422 budget error),
# working state, isolation (AC-06), 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-context.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;d=json.load(sys.stdin);print($1)"; } # jq_ '<python expr on d>'
js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; } # JSON string literal

# remember <key> <ns> <type> <title> <content> [importance] -> memory id
remember() {
local imp=${6:-0.5}
body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5"),\"importance\":$imp}" | jget id
}
verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"$3\",\"method\":\"manual\",\"revision\":1}" >/dev/null; }
ctx() { local key=$1; shift; body "$key" POST /context -d "$1"; }

# ---- setup ------------------------------------------------------------------------------------------------
TA=$(prov tenant "p3-A" | field tenant_id); TB=$(prov tenant "p3-B" | field tenant_id); TENANTS=("$TA" "$TB")
mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
mk "$TA" 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,delete,verify" 1 >/dev/null
prov grant "$WID" /big "read,write,delete,verify" 1 >/dev/null
prov grant "$RID" /kb "read" 1 >/dev/null
prov grant "$BID" /kb "read,write,delete,verify" 1 >/dev/null
prov grant "$BLID" /elsewhere "read" 1 >/dev/null
NS=$(prov namespace "$TA" /kb | field namespace_id); NSSUB=$(prov namespace "$TA" /kb/sub | field namespace_id)
NSBIG=$(prov namespace "$TA" /big | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
[ -n "$NS" ] && [ -n "$NSSUB" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; }

# ---- cold start: first request after a restart is a context 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
check "cold: context on empty tenant -> 200" "200" "$(code "$WK" POST /context -d '{"task":"zebracorn"}')"

C1=$(remember "$WK" "$NS" constraint "No Friday deploys" "Never deploy zebracorn on Fridays." 0.9); verify "$WK" "$C1" verified
C2=$(remember "$WK" "$NS" constraint "Draft xylophone rule" "Draft constraint about the xylophone." 0.8) # unverified
P1=$(remember "$WK" "$NS" preference "Tabs" "Prefer tabs in zebracorn source files." 0.4); verify "$WK" "$P1" verified
D1=$(remember "$WK" "$NS" decision "Storage" "We chose SQLite for zebracorn storage." 0.5); verify "$WK" "$D1" verified
L1=$(remember "$WK" "$NS" lesson "Migrations" "Zebracorn migrations must run one at a time." 0.5); verify "$WK" "$L1" verified
K1=$(remember "$WK" "$NS" semantic "Port" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$K1" verified
K2=$(remember "$WK" "$NS" semantic "Platform" "Zebracorn runs on Windows only." 0.5); verify "$WK" "$K2" disputed
K3=$(remember "$WK" "$NS" semantic "Old host" "Zebracorn used to run on host alpha." 0.5); verify "$WK" "$K3" verified
code "$WK" POST /memories/$K3/retire >/dev/null
KD=$(remember "$WK" "$NSSUB" semantic "Port copy" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$KD" verified # same content
X1=$(remember "$WK" "$NS" semantic "Fruit" "Bananas are yellow." 0.5); verify "$WK" "$X1" verified # unrelated
E1=$(remember "$WK" "$NS" semantic "Escaping" "Zebracorn quote \"q\" and <script>alert(1)</script> tag." 0.5); verify "$WK" "$E1" verified
# Non-ASCII goes in as JSON \u escapes (Git Bash curl mangles raw UTF-8 literals), BMP only: characters above U+FFFF are a known runtime issue, see phase1
UJ='{"namespace_id":"'$NS'","type":"semantic","title":"utf8","content":"Gr\u00fc\u00dfe zebracorn \u65e5\u672c"}'
UM=$(curl -s -X POST -H "Authorization: Bearer $WK" --data-binary "$UJ" "$BASE/remember" | jget id); verify "$WK" "$UM" verified
LONGC=$(python -I -c "print(' '.join(['Rule %d: every zebracorn release needs a signed checklist entry.' % i for i in range(20)]))")
CB=$(remember "$WK" "$NSBIG" constraint "Big rule" "$LONGC" 0.9); verify "$WK" "$CB" verified
BM=$(remember "$BK" "$NSB" constraint "B secret" "Tenant B secret zebracorn rule." 0.9); verify "$BK" "$BM" verified
FILL=$(python -I -c "print(' '.join(['zebracorn operations note %d explains the routine.' % i for i in range(40)]))")
curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \
-d "{\"namespace_id\":\"$NS\",\"title\":\"Ops\",\"source_uri\":\"kb://ops\",\"format\":\"markdown\",\"content\":$(js "# Ops

Zebracorn runbook: restart the zebracorn service with care.

$FILL")}"
SID=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"Ship zebracorn\"}" | jget id)
code "$WK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"step":3,"next":"tests"}}' >/dev/null
[ -n "$C1" ] && [ -n "$K2" ] && [ -n "$SID" ] && [ -n "$CB" ] || { echo "data setup failed"; exit 2; }

# ---- full briefing ------------------------------------------------------------------------------------------
R=$(ctx "$WK" "{\"task\":\"zebracorn deploy\",\"namespace_ids\":[\"$NS\",\"$NSSUB\"],\"session_id\":\"$SID\"}")
check "context -> valid JSON" "yes" "$(echo "$R" | jq_ "'yes'" 2>/dev/null || echo no)"
check "constraint loaded by scope" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
check "constraint has policy authority" "policy" "$(echo "$R" | jq_ "[x for x in d['constraints'] if x['id']=='$C1'][0].get('authority')")"
check "unverified constraint excluded by default" "no" "$(has "$C2" "$R")"
check "preference included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$P1' for x in d['preferences']) else 'no'")"
check "decision section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$D1' for x in d['decisions']) else 'no'")"
check "lesson section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$L1' for x in d['lessons']) else 'no'")"
check "knowledge section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K1' for x in d['knowledge']) else 'no'")"
check "disputed memory under conflicts" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K2' and x['content_trust']=='disputed_memory' for x in d['conflicts']) else 'no'")"
check "retired memory excluded" "no" "$(has "$K3" "$R")"
check "unrelated memory not matched" "no" "$(has "$X1" "$R")"
check "duplicate content appears once" "no" "$(has "$KD" "$R")"
check "duplicates counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['duplicates']>=1 else 'no'")"
check "unverified excluded counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['unverified_excluded']>=1 else 'no'")"
check "references are untrusted" "yes" "$(echo "$R" | jq_ "'yes' if d['references'] and all(x['content_trust']=='untrusted_reference' for x in d['references']) else 'no'")"
check "working state included" "tests" "$(echo "$R" | jq_ "d['working_state']['state']['next']")"
check "items carry revision and provenance" "yes" "$(echo "$R" | jq_ "'yes' if all('revision' in x and 'created_by' in x['provenance'] for x in d['knowledge']) else 'no'")"
check "used tokens within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=d['budget']['max_context_tokens'] else 'no'")"
check "complete and not truncated" "True False" "$(echo "$R" | jq_ "d['budget']['complete'], d['budget']['truncated']" | tr -d '(),')"
check "counting method declared" "estimate_chars_div_4" "$(echo "$R" | jq_ "d['budget']['counting_method']")"
check "strategy reported" "yes" "$(echo "$R" | jq_ "'yes' if d['strategy'] in ('hybrid','lexical') else 'no'")"
check "tenant B content never included" "no" "$(has 'Tenant B secret' "$R")"
check "escaped content round-trips" "yes" "$(echo "$R" | jq_ "'yes' if any(x['content']=='Zebracorn quote \"q\" and <script>alert(1)</script> tag.' for x in d['knowledge']) else 'no'")"
check "UTF-8 round trip" "yes" "$(echo "$R" | python -I -c "
import sys,json
d=json.loads(sys.stdin.buffer.read()); u='Gr\u00fc\u00dfe zebracorn \u65e5\u672c'
print('yes' if any(x['content']==u for x in d['knowledge']) else 'no')")"

# ---- verification filter ------------------------------------------------------------------------------------
R=$(ctx "$WK" "{\"task\":\"zebracorn xylophone\",\"namespace_ids\":[\"$NS\"],\"verification_filter\":\"include_unverified\"}")
check "include_unverified -> unverified section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' and x['content_trust']=='unverified_memory' for x in d['unverified']) else 'no'")"
check "unverified constraint is not policy" "no" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' for x in d['constraints']) else 'no'")"

# ---- budget -------------------------------------------------------------------------------------------------
R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_context_tokens\":100}")
check "small budget -> truncated" "True" "$(echo "$R" | jq_ "d['budget']['truncated']")"
check "small budget -> within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=100 else 'no'")"
check "small budget keeps constraints" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
check "small budget -> over_budget counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['over_budget']>0 else 'no'")"
check "constraints over budget -> 422" "422" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}")"
check "budget error code" "context_budget_exceeded" "$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}" | jq_ "d['error']['code']")"
check "bigger budget fits big constraint" "200" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":2000}")"
R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_items\":1,\"max_references\":0}")
check "max_items caps a section" "1" "$(echo "$R" | jq_ "len(d['knowledge'])")"
check "max_references 0 -> none" "0" "$(echo "$R" | jq_ "len(d['references'])")"

# ---- include and detail -------------------------------------------------------------------------------------
R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"include\":[\"lessons\"]}")
check "include limits sections" "False False True" "$(echo "$R" | jq_ "'decisions' in d, 'references' in d, 'lessons' in d" | tr -d '(),')"
check "constraints always included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"detail_level\":\"summary\"}")
check "summary detail on knowledge" "True False" "$(echo "$R" | jq_ "'summary' in d['knowledge'][0], 'content' in d['knowledge'][0]" | tr -d '(),')"
check "constraints stay full in summary" "yes" "$(echo "$R" | jq_ "'yes' if 'content' in d['constraints'][0] else 'no'")"

# ---- access -------------------------------------------------------------------------------------------------
check "reader gets briefing" "yes" "$(ctx "$RK" '{"task":"zebracorn"}' | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
check "reader can use session read" "200" "$(code "$RK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
R=$(ctx "$BLK" '{"task":"zebracorn"}')
check "no-access principal gets empty briefing" "0 0" "$(echo "$R" | jq_ "len(d['constraints']), len(d['knowledge'])" | tr -d '(),')"
check "no-access session -> 404" "404" "$(code "$BLK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
check "other tenant session -> 404" "404" "$(code "$BK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
check "unknown session -> 404" "404" "$(code "$WK" POST /context -d '{"task":"zebracorn","session_id":"00000000-0000-4000-8000-000000000000"}')"
check "tenant B sees only its constraint" "yes" "$(ctx "$BK" '{"task":"zebracorn"}' | jq_ "'yes' if [x['id'] for x in d['constraints']]==['$BM'] else 'no'")"
check "namespace outside grants yields nothing" "0" "$(ctx "$RK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"]}" | jq_ "len(d['constraints'])")"

# ---- validation ---------------------------------------------------------------------------------------------
check "no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{"task":"x"}' "$BASE/context")"
check "missing task -> 422" "422" "$(code "$WK" POST /context -d '{}')"
check "task without words -> 422" "422" "$(code "$WK" POST /context -d '{"task":"!!!"}')"
check "budget too small -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":50}')"
check "budget not whole -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":500.5}')"
check "unknown include -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","include":["bogus"]}')"
check "unsupported format -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","format":"markdown"}')"
check "bad verification_filter -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","verification_filter":"all"}')"
check "bad session id -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","session_id":"nope"}')"
check "bad namespace ids -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","namespace_ids":["nope"]}')"
check "invalid JSON -> 400" "400" "$(code "$WK" POST /context -d '{"task":')"
check "empty body -> 400" "400" "$(code "$WK" POST /context)"

echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

+ 222
- 0
tests/phase3-learning.sh View File

@@ -0,0 +1,222 @@
#!/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 -> 405" "405" "$(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 -> 405" "405" "$(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\"}")"

# ---- feedback adjusts ranking (current revision only) -------------------------------------------------------
check "search shows chunk feedback" "1" "$(body "$RK" POST /search -d '{"query":"quillfeather daemon gentle"}' | jq_ "[r for r in d['results'] if r['chunk_id']=='$CH'][0]['feedback']['incorrect_or_harmful']")"
KA=$(remember "$WK" "$NS" semantic "Kestrel cache" "Kestrel cache holds 64 MB."); verify "$VK" "$KA"
KB=$(remember "$WK" "$NS" semantic "Kestrel cache" "Kestrel cache holds 128 MB."); verify "$VK" "$KB"
R=$(body "$RK" POST /recall -d "{\"query\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}")
QK=$(echo "$R" | jget query_id); TOP=$(echo "$R" | jq_ "d['results'][0]['id']"); OTHER=$(echo "$R" | jq_ "d['results'][1]['id']")
check "two kestrel results before feedback" "yes" "$([ -n "$TOP" ] && [ -n "$OTHER" ] && [ "$TOP" != "$OTHER" ] && echo yes || echo no)"
for k in "$RK" "$VK"; do code "$k" POST /feedback -d "{\"query_id\":\"$QK\",\"result_id\":\"$TOP\",\"usefulness\":\"incorrect\"}" >/dev/null; done
R=$(body "$RK" POST /recall -d "{\"query\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}")
check "negative feedback demotes the result" "$OTHER" "$(echo "$R" | jq_ "d['results'][0]['id']")"
check "demoted result carries feedback counts" "2" "$(echo "$R" | jq_ "[r for r in d['results'] if r['id']=='$TOP'][0]['feedback']['incorrect_or_harmful']")"
check "recall warns about demotion" "yes" "$(has 'negative feedback' "$R")"
check "context warns about demotion" "yes" "$(has 'negative feedback' "$(body "$RK" POST /context -d "{\"task\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}")")"
code "$WK" PATCH /memories/$TOP -H 'If-Match: 1' -d '{"content":"Kestrel cache holds 256 MB."}' >/dev/null; verify "$VK" "$TOP" 2
R=$(body "$RK" POST /recall -d "{\"query\":\"kestrel cache holds\",\"namespace_ids\":[\"$NS\"]}")
check "new revision starts without feedback" "None" "$(echo "$R" | jq_ "[r for r in d['results'] if r['id']=='$TOP'][0].get('feedback')")"
check "no demotion warning after correction" "no" "$(has 'negative feedback' "$R")"

# ---- forgetting removes linked data --------------------------------------------------------------------------
C8=$(learn "$WK" "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Port clash v2\",\"content\":\"Prefer 7102.\",\"target_memory_id\":\"$MEM1\",\"base_revision\":1}" | jget id)
check "forget accepted memory -> 200" "200" "$(code "$AK" DELETE /memories/$MEM1)"
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 ]

+ 145
- 0
tests/phase3-portability.sh View File

@@ -0,0 +1,145 @@
#!/usr/bin/env bash
# Export/import checks (spec FR-018, NFR-007, NFR-009, AC-06, AC-14): canonical export with schema version and
# integrity digest, filtering by read permission (no disclosure of unreadable namespaces or evidence targets), import
# into a clean tenant with ids, revisions, verifications, provenance, documents, chunks and evidence intact (a second
# export of the imported data equals the first), integrity and validation errors, all-or-nothing conflicts, size limit.
#
# Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions throw-away
# tenants and purges them at the end (even on failure).
# bash tests/phase3-portability.sh
set -u
BASE=${BASE:-http://localhost:8801/api/v1}
PASS=0; FAIL=0; FAILED=(); TENANTS=()
TMP=$(mktemp -d)
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; if [ -n "${KEEP:-}" ]; then echo "kept $TMP"; else rm -rf "$TMP"; fi; }
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; }
pyf() { python -I -c "import sys,json,hashlib;a=sys.argv[2:];$1" "$@"; } # pyf '<python using a[]>' args...
jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)"; }
js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; }
remember() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5")${6:-}}" | jget id; }
# rememberj: like remember, but $5 is already a JSON string literal
rememberj() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$5}" | jget id; }
verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"verified\",\"method\":\"manual\",\"revision\":${3:-1}}" >/dev/null; }
# export <key> <file> [body]
export_() { curl -s -X POST -H "Authorization: Bearer $1" -d "${3:-{\}}" -o "$2" -w '%{http_code}' "$BASE/exports"; }
import_() { curl -s -X POST -H "Authorization: Bearer $1" --data-binary @"$2" -w '\n%{http_code}' "$BASE/imports"; }
digest_ok() { pyf "raw=open(a[0],'rb').read().decode('utf-8');d=json.loads(raw);i=raw.index('\"data\":')+7;j=raw.rindex(',\"counts\":');print(hashlib.sha256(raw[i:j].encode('utf-8')).hexdigest()==d['integrity']['digest'])" "$1"; }
mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }

# ---- setup: tenant A with two namespaces and a secret one ------------------------------------------------------
TA=$(prov tenant "port-A" | field tenant_id); TB=$(prov tenant "port-B" | field tenant_id); TENANTS=("$TA" "$TB")
mk "$TA" owner human; OID=$P_ID; OK=$P_KEY
mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY
mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY
mk "$TB" ownerB human; BID=$P_ID; BK=$P_KEY
prov grant "$OID" /kb admin 1 >/dev/null; prov grant "$OID" /secret admin 1 >/dev/null
prov grant "$WID" /kb "read,write" 1 >/dev/null
prov grant "$RID" /kb read 1 >/dev/null
prov grant "$BLID" /elsewhere read 1 >/dev/null
prov grant "$BID" /kb admin 1 >/dev/null
NS=$(prov namespace "$TA" /kb | field namespace_id); NSUB=$(prov namespace "$TA" /kb/sub | field namespace_id)
NSS=$(prov namespace "$TA" /secret | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
[ -n "$NS" ] && [ -n "$NSUB" ] && [ -n "$NSS" ] && [ -n "$NSB" ] && [ -n "$OK" ] || { echo "setup failed"; exit 2; }

M1=$(remember "$WK" "$NS" semantic "Pelican port" "The pelican service listens on port 9100." ',"tags":["ports","pelican"],"confidence":0.75')
code "$WK" PATCH /memories/$M1 -H 'If-Match: 1' -d '{"content":"The pelican service listens on port 9200.","change_reason":"moved"}' >/dev/null
verify "$OK" "$M1" 2
M2C=$(python -I -c "import json;print(json.dumps('Quote \"q\", backslash '+chr(92)+', tab'+chr(9)+' and Gr'+chr(252)+chr(223)+'e '+chr(0x65e5)+'.'))" | tr -d '[:cntrl:]')
M2=$(rememberj "$WK" "$NSUB" lesson "Escapes <b>" "$M2C")
M3=$(remember "$WK" "$NS" semantic "Old pelican host" "Pelican ran on host alpha.")
code "$OK" POST /memories/$M3/retire >/dev/null
MS=$(remember "$OK" "$NSS" semantic "Pelican secret" "The pelican vault key is in safe nine.")
curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" -d "{\"namespace_id\":\"$NS\",\"title\":\"Pelican runbook\",\"source_uri\":\"kb://pelican\",\"format\":\"markdown\",\"content\":\"# Pelican\n\nRestart pelican gently.\n\n## Ports\n\nPelican uses 9100.\"}"
DOC=$(curl -s -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" -d "{\"namespace_id\":\"$NS\",\"title\":\"Pelican runbook\",\"source_uri\":\"kb://pelican\",\"format\":\"markdown\",\"content\":\"# Pelican\n\nRestart pelican gently.\n\n## Ports\n\nPelican uses 9200 now.\"}" | jget document_id)
CH=$(body "$RK" POST /search -d '{"query":"pelican 9200"}' | jq_ "d['results'][0]['chunk_id']" 2>/dev/null)
# evidence: a candidate citing M1 and the chunk (readable) and the secret memory (owner only), accepted by the owner
C1=$(body "$OK" POST /learn -d "{\"namespace_id\":\"$NS\",\"type\":\"lesson\",\"title\":\"Pelican moved\",\"content\":\"Pelican moved from 9100 to 9200.\",\"evidence\":[{\"kind\":\"memory\",\"id\":\"$M1\"},{\"kind\":\"chunk\",\"id\":\"$CH\",\"excerpt\":\"9200\"},{\"kind\":\"memory\",\"id\":\"$MS\",\"role\":\"context\"}]}" | jget id)
M4=$(body "$OK" POST /candidates/$C1/review -d '{"decision":"accept","verify":true}' | jget resulting_memory_id)
MB=$(remember "$BK" "$NSB" semantic "B pelican" "Tenant B pelican fact.")
[ -n "$M1" ] && [ -n "$M2" ] && [ -n "$DOC" ] && [ -n "$CH" ] && [ -n "$M4" ] && [ -n "$MB" ] || { echo "data setup failed"; exit 2; }

# ---- export ----------------------------------------------------------------------------------------------------
docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
check "cold: owner export -> 200" "200" "$(export_ "$OK" "$TMP/owner.json")"
E="$TMP/owner.json"
check "format and schema version" "agent-memory-export 1" "$(pyf "d=json.load(open(a[0],encoding='utf-8'));print(d['format'],d['schema_version'])" "$E")"
check "integrity digest valid" "True" "$(digest_ok "$E")"
check "counts" "3 5 6 1 2 3" "$(pyf "c=json.load(open(a[0],encoding='utf-8'))['counts'];print(c['namespaces'],c['memories'],c['memory_revisions'],c['documents'],c['document_revisions'],c['evidence_links'])" "$E")"
check "memory keeps both revisions" "2" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print(len([m for m in d['memories'] if m['id']==a[1]][0]['revisions']))" "$E" "$M1")"
check "provenance kept (created_by)" "$WID" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print([m for m in d['memories'] if m['id']==a[1]][0]['created_by'])" "$E" "$M1")"
check "retired status kept" "retired" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];print([m for m in d['memories'] if m['id']==a[1]][0]['lifecycle_status'])" "$E" "$M3")"
check "UTF-8 and escapes exported" "yes" "$(pyf "d=json.load(open(a[0],encoding='utf-8'))['data'];c=[m for m in d['memories'] if m['id']==a[1]][0]['revisions'][0]['content'];print('yes' if chr(92) in c and chr(252) in c and chr(0x65e5) in c and chr(9) in c else 'no')" "$E" "$M2")"
check "export content-disposition" "yes" "$(curl -s -i -X POST -H "Authorization: Bearer $OK" -d '{}' "$BASE/exports" | grep -qi '^content-disposition: attachment' && echo yes || echo no)"
export_ "$RK" "$TMP/reader.json" >/dev/null
check "reader export: no secret namespace" "no" "$(has '/secret' "$(cat "$TMP/reader.json")")"
check "reader export: secret memory id absent" "no" "$(has "$MS" "$(cat "$TMP/reader.json")")"
check "reader export: unreadable evidence omitted" "1" "$(pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['evidence_links_omitted'])" "$TMP/reader.json")"
export_ "$BLK" "$TMP/blind.json" >/dev/null
check "blind export is empty" "0 0" "$(pyf "c=json.load(open(a[0],encoding='utf-8'))['counts'];print(c['memories'],c['documents'])" "$TMP/blind.json")"
export_ "$BK" "$TMP/b.json" >/dev/null
check "tenant B export has only B" "yes no" "$(has "$MB" "$(cat "$TMP/b.json")") $(has "$M1" "$(cat "$TMP/b.json")")"
export_ "$OK" "$TMP/sub.json" "{\"namespace_ids\":[\"$NSUB\"]}" >/dev/null
check "namespace filter" "1 /kb/sub" "$(pyf "d=json.load(open(a[0],encoding='utf-8'));print(d['counts']['memories'],d['data']['namespaces'][0]['path'])" "$TMP/sub.json")"
check "filter with unreadable id gives nothing" "0" "$(export_ "$RK" "$TMP/x.json" "{\"namespace_ids\":[\"$NSS\"]}" >/dev/null; pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['memories'])" "$TMP/x.json")"
check "export bad namespace_ids -> 422" "422" "$(code "$OK" POST /exports -d '{"namespace_ids":"x"}')"
check "export no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{}' "$BASE/exports")"
check "export wrong method -> 405" "405" "$(code "$OK" GET /exports)"

# ---- import validation (nothing written) ------------------------------------------------------------------------
pyf "d=json.load(open(a[0],encoding='utf-8'));d['format']='other';open(a[1],'w',encoding='utf-8').write(json.dumps(d))" "$E" "$TMP/badfmt.json"
check "import wrong format -> 422" "422" "$(import_ "$BK" "$TMP/badfmt.json" | tail -1)"
pyf "raw=open(a[0],encoding='utf-8').read();open(a[1],'w',encoding='utf-8').write(raw.replace('\"schema_version\":1','\"schema_version\":2',1))" "$E" "$TMP/v2.json"
check "import schema_version 2 -> 422" "unsupported_schema_version" "$(import_ "$BK" "$TMP/v2.json" | head -1 | jget code)"
pyf "raw=open(a[0],encoding='utf-8').read();open(a[1],'w',encoding='utf-8').write(raw.replace('port 9200','port 6666',1))" "$E" "$TMP/tampered.json"
check "tampered data -> integrity_mismatch" "integrity_mismatch" "$(import_ "$BK" "$TMP/tampered.json" | head -1 | jget code)"
check "import into tenant without /secret -> 422" "422" "$(import_ "$BK" "$E" | tail -1)"
export_ "$OK" "$TMP/kb.json" "{\"namespace_ids\":[\"$NS\"]}" >/dev/null
check "import into existing ids -> 409" "409" "$(import_ "$BK" "$TMP/kb.json" | tail -1)"
check "failed imports wrote nothing in B" "1" "$(export_ "$BK" "$TMP/b2.json" >/dev/null; pyf "print(json.load(open(a[0],encoding='utf-8'))['counts']['memories'])" "$TMP/b2.json")"
check "import by non-admin -> 422" "422" "$(import_ "$RK" "$TMP/sub.json" | tail -1)"
check "import empty body -> 400" "400" "$(code "$OK" POST /imports)"
check "import invalid JSON -> 400" "400" "$(code "$OK" POST /imports -d '{"format":')"
python -I -c "import sys;open(sys.argv[1],'w').write('{\"pad\":\"'+'x'*(9*1024*1024)+'\"}')" "$TMP/big.json"
check "import over 8 MiB -> 413" "413" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $OK" --data-binary @"$TMP/big.json" "$BASE/imports")"

# ---- round trip: purge tenant A, recreate its namespaces, import, export again ----------------------------------
prov purge "$TA" >/dev/null
TA2=$(prov tenant "port-A2" | field tenant_id); TENANTS+=("$TA2")
mk "$TA2" restorer human; RSID=$P_ID; RSK=$P_KEY
prov grant "$RSID" /kb admin 1 >/dev/null; prov grant "$RSID" /secret admin 1 >/dev/null
prov namespace "$TA2" /kb >/dev/null; prov namespace "$TA2" /kb/sub >/dev/null; prov namespace "$TA2" /secret >/dev/null
docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
R=$(import_ "$RSK" "$E")
check "cold: import into clean tenant -> 201" "201" "$(tail -1 <<<"$R")"
check "import counts" "5 6 3 1 2" "$(head -1 <<<"$R" | jq_ "' '.join(str(d['imported'][k]) for k in ['memories','memory_revisions','evidence_links','documents','document_revisions'])")"
R=$(body "$RSK" GET /memories/$M1)
check "imported memory: same id, revision 2" "2" "$(echo "$R" | jq_ "d['data']['current_revision']")"
check "imported memory: verified" "verified" "$(echo "$R" | jq_ "d['data']['verification_status']")"
check "imported memory: provenance" "$WID" "$(echo "$R" | jq_ "d['data']['created_by']")"
check "imported memory: tags" "['ports', 'pelican']" "$(echo "$R" | jq_ "d['data']['tags']")"
check "imported history: 2 versions" "2" "$(body "$RSK" GET /memories/$M1/versions | jq_ "len(d['data'])")"
check "imported UTF-8 and escapes intact" "yes" "$(body "$RSK" GET /memories/$M2 | jq_ "'yes' if chr(92) in d['data']['content'] and chr(252) in d['data']['content'] and chr(0x65e5) in d['data']['content'] and chr(9) in d['data']['content'] else 'no'")"
check "imported retired memory stays retired" "retired" "$(body "$RSK" GET /memories/$M3 | jq_ "d['data']['status']")"
check "recall finds imported memory" "yes" "$(body "$RSK" POST /recall -d '{"query":"pelican service port"}' | jq_ "'yes' if any(x['id']=='$M1' for x in d['results']) else 'no'")"
check "search finds imported chunk (same id)" "yes" "$(body "$RSK" POST /search -d '{"query":"pelican 9200"}' | jq_ "'yes' if any(x['chunk_id']=='$CH' for x in d['results']) else 'no'")"
check "document keeps revision 2" "2" "$(body "$RSK" GET /documents/$DOC | jq_ "d['data']['current_revision']")"
check "imported evidence available" "3" "$(body "$RSK" GET /memories/$M4/sources | jq_ "len([e for e in d['evidence'] if e['available']])")"
export_ "$RSK" "$TMP/again.json" >/dev/null
check "re-export equals the original (AC-14)" "True" "$(pyf "x=json.load(open(a[0],encoding='utf-8'))['data'];y=json.load(open(a[1],encoding='utf-8'))['data'];print(x==y)" "$E" "$TMP/again.json")"
check "importing twice -> 409" "409" "$(import_ "$RSK" "$E" | tail -1)"

echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

+ 127
- 0
tests/phase3-semantic.sh View File

@@ -0,0 +1,127 @@
#!/usr/bin/env bash
# Phase 3 checks for semantic retrieval (spec FR-008, FR-009, section 10): embeddings via Ollama, vectors in Qdrant,
# hybrid ranking in /recall, /search and /context, isolation (AC-06), re-indexing on correction, removal on forget,
# purge and new document revisions (AC-13), degradation to lexical when the provider is down (AC-16), recovery with
# scripts/embed.asp, and a cold start.
#
# Needs the containers from docker-compose.yml running (axonasp, ollama with nomic-embed-text pulled, qdrant) and
# EmbeddingProvider=ollama in public/web.config. Provisions throw-away tenants and purges them at the end. Stops and
# restarts the ollama container once.
# bash tests/phase3-semantic.sh
set -u
BASE=${BASE:-http://localhost:8801/api/v1}
COLL=${COLL:-amk_nomic_embed_text_768}
PASS=0; FAIL=0; FAILED=(); TENANTS=()
prov() {
MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
-e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r'
}
embed() { MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "EMBED_ACTION=$1" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/embed.asp 2>&1 | tr -d '\r'; }
field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
cleanup() { docker start ollama >/dev/null 2>&1; for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; }
trap cleanup EXIT
check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
jq_() { python -I -c "import sys,json;d=json.load(sys.stdin);print($1)"; }
js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; }
remember() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5")}" | jget id; }
verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"verified\",\"method\":\"manual\",\"revision\":${3:-1}}" >/dev/null; }
recall() { body "$1" POST /recall -d "{\"query\":$(js "$2")}"; }
ids() { jq_ "' '.join(r.get('id', r.get('chunk_id','')) for r in d['results'])"; }
# number of vector points of a tenant, optionally of one kind (asked from inside the axonasp container, which can
# reach qdrant): points <tenant_id> [memory|chunk]
points() {
local q
q=$(python -I -c "
import json,sys
must=[{'key':'tenant_id','match':{'value':sys.argv[1]}}]
if len(sys.argv)>2 and sys.argv[2]: must.append({'key':'kind','match':{'value':sys.argv[2]}})
print(json.dumps({'exact':True,'filter':{'must':must}}))" "$1" "${2:-}")
docker exec axonasp wget -qO- --header='Content-Type: application/json' --post-data="$q" \
"http://qdrant:6333/collections/$COLL/points/count" | python -I -c "import sys,json;print(json.load(sys.stdin)['result']['count'])"
}

# ---- setup ------------------------------------------------------------------------------------------------
TA=$(prov tenant "p3s-A" | field tenant_id); TB=$(prov tenant "p3s-B" | field tenant_id); TENANTS=("$TA" "$TB")
mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY
mk "$TB" writerB agent; BID=$P_ID; BK=$P_KEY
prov grant "$WID" /kb "read,write,delete,verify" 1 >/dev/null
prov grant "$BID" /kb "read,write,delete,verify" 1 >/dev/null
prov grant "$BLID" /elsewhere "read" 1 >/dev/null
NS=$(prov namespace "$TA" /kb | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
[ -n "$NS" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; }

# ---- cold start: first request after a restart is a write that must also be embedded --------------------------
docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
M1=$(remember "$WK" "$NS" semantic "Release rule" "Never deploy to production on Fridays."); verify "$WK" "$M1"
check "cold: write embedded immediately" "1" "$(points "$TA" memory)"
M2=$(remember "$WK" "$NS" semantic "Fruit" "Bananas are a good source of potassium."); verify "$WK" "$M2"
M3=$(remember "$WK" "$NS" semantic "Staging" "The staging database is reset every night at 2am."); verify "$WK" "$M3"
MB=$(remember "$BK" "$NSB" semantic "B release rule" "Tenant B never deploys to production on Fridays either."); verify "$BK" "$MB"
check "all memories embedded" "3" "$(points "$TA" memory)"

# ---- semantic recall without word overlap ---------------------------------------------------------------------
R=$(recall "$WK" "fruit nutrition")
check "paraphrase finds memory" "$M2" "$(echo "$R" | ids)"
check "strategy hybrid" "hybrid" "$(echo "$R" | jq_ "d['strategy']")"
check "no degradation warning" "0" "$(echo "$R" | jq_ "len(d['warnings'])")"
check "second paraphrase" "$M3" "$(recall "$WK" "test environment data wipe schedule" | ids)"
check "release question ranks the rule first" "$M1" "$(recall "$WK" "When are we allowed to ship a release?" | jq_ "d['results'][0]['id']")"
check "unrelated query below threshold" "" "$(recall "$WK" "quantum chromodynamics lecture" | ids)"
check "other tenant never sees A by meaning" "$MB" "$(recall "$BK" "When are we allowed to ship a release?" | ids)"
check "principal without namespace sees nothing" "" "$(recall "$BLK" "fruit nutrition" | ids)"

# ---- correction re-embeds, forget removes the point -----------------------------------------------------------
check "correct -> 200" "200" "$(code "$WK" PATCH /memories/$M2 -H 'If-Match: 1' -d '{"title":"Coffee machine","content":"The office coffee machine is descaled every Monday."}')"
verify "$WK" "$M2" 2
check "old meaning no longer matches" "" "$(recall "$WK" "fruit nutrition" | ids)"
check "new meaning matches" "$M2" "$(recall "$WK" "when is the espresso maker cleaned" | ids)"
check "forget -> 200" "200" "$(code "$WK" DELETE /memories/$M3)"
check "forgotten memory point removed" "2" "$(points "$TA" memory)"

# ---- documents ---------------------------------------------------------------------------------------------------
DOC1=$(printf '# Runbook\n\nIf the payment gateway times out, restart the checkout worker and page the on-call engineer.\n')
D=$(body "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"Runbook\",\"source_uri\":\"kb://runbook\",\"format\":\"markdown\",\"content\":$(js "$DOC1")}" | jget document_id)
S=$(body "$WK" POST /search -d '{"query":"what to do when card processing hangs"}')
check "semantic chunk search" "yes" "$(echo "$S" | jq_ "'yes' if d['results'] and 'payment gateway' in d['results'][0]['content'] else 'no'")"
check "search strategy hybrid" "hybrid" "$(echo "$S" | jq_ "d['strategy']")"
P_BEFORE=$(points "$TA" chunk)
DOC2=$(printf '# Runbook\n\nFor holiday rotas ask the team lead.\n')
body "$WK" POST /ingestion/jobs -d "{\"namespace_id\":\"$NS\",\"title\":\"Runbook\",\"source_uri\":\"kb://runbook\",\"format\":\"markdown\",\"content\":$(js "$DOC2")}" >/dev/null
check "new revision replaces old chunk points" "$P_BEFORE" "$(points "$TA" chunk)"
check "old revision text not found by meaning" "0" "$(body "$WK" POST /search -d '{"query":"what to do when card processing hangs"}' | jq_ "len(d['results'])")"

# ---- context uses the same ranking -------------------------------------------------------------------------------
C=$(body "$WK" POST /context -d "{\"task\":\"Plan the timing of the next production release\",\"namespace_ids\":[\"$NS\"]}")
check "context finds rule by meaning" "yes" "$(echo "$C" | jq_ "'yes' if any(x['id']=='$M1' for x in d['knowledge']) else 'no'")"
check "context strategy hybrid" "hybrid" "$(echo "$C" | jq_ "d['strategy']")"

# ---- degradation: provider down ----------------------------------------------------------------------------------
docker stop ollama >/dev/null
R=$(recall "$WK" "Fridays production")
check "provider down: recall still 200" "$M1" "$(echo "$R" | ids)"
check "provider down: lexical strategy" "lexical" "$(echo "$R" | jq_ "d['strategy']")"
check "provider down: warning" "yes" "$(echo "$R" | jq_ "'yes' if any('unavailable' in w for w in d['warnings']) else 'no'")"
check "provider down: remember still 201" "201" "$(code "$WK" POST /remember -d "{\"namespace_id\":\"$NS\",\"type\":\"semantic\",\"title\":\"Pets\",\"content\":\"Dogs are allowed in the office on Thursdays.\"}")"
M4=$(body "$WK" GET "/memories?namespace_id=$NS&limit=50" | python -I -c "import sys,json;print([m['id'] for m in json.load(sys.stdin)['data'] if m['title']=='Pets'][0])")
verify "$WK" "$M4"
check "provider down: new memory not yet embedded" "2" "$(points "$TA" memory)"
# a web request leaves the row pending (no attempt used); the embed-worker may already have tried it and marked it failed
check "provider down: status shows pending or failed" "yes" "$(embed status | grep -qE '(pending|failed): ' && echo yes || echo no)"
docker start ollama >/dev/null; for i in $(seq 1 30); do docker exec axonasp wget -qO- http://ollama:11434/api/version >/dev/null 2>&1 && break; sleep 1; done
embed run >/dev/null
check "embed run catches up" "3" "$(points "$TA" memory)"
check "caught-up memory found by meaning" "$M4" "$(recall "$WK" "can I bring my puppy to work" | ids)"

# ---- purge removes every point of the tenant ---------------------------------------------------------------------
prov purge "$TB" >/dev/null; TENANTS=("$TA")
check "purge removes tenant points" "0" "$(points "$TB")"

echo "passed: $PASS failed: $FAIL"
for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
[ "$FAIL" -eq 0 ]

Loading…
Cancel
Save

Powered by TurnKey Linux.