diff --git a/.gitignore b/.gitignore index d864bfa..c9b203d 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,6 @@ # Local knowledge base keys (scripts/kb.sh) /.amk.env + +# Database backups (scripts/backup.cmd); keep copies somewhere else too +/db/backups/ diff --git a/AGENTS.md b/AGENTS.md index 876cdfc..40d422f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,9 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w - 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`. -- The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all five suites (`tests/phase*.sh`). +- 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 ` (`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. +- The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all seven suites (`tests/*.sh`). ### This repo's own knowledge base (dogfooding) @@ -185,7 +187,13 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o - **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. +- **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]' `, 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. +- **`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. diff --git a/README.md b/README.md index e7344c4..d39db22 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,8 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec - 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). **Known limitation** - Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8). @@ -67,11 +69,21 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). - `scripts\embed.cmd status|run|reindex`: semantic index status, catch up on pending/failed items, or rebuild (after changing the model). -- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93). Each creates and purges its own tenants. +- Tests (containers must be running): `bash tests/phase1-api.sh` (79 checks), `bash tests/phase2-api.sh` (45), `bash tests/phase3-context.sh` (60), `bash tests/phase3-semantic.sh` (30; stops and restarts the ollama container once), `bash tests/phase3-learning.sh` (93), `bash tests/phase3-portability.sh` (44), `bash tests/backup-restore.sh` (21; starts a throw-away container on port 8802). Each creates and purges its own tenants. **Next (not started)** 1. Consolidation of related experiences into candidates (today agents propose them by hand with `POST /learn`). -2. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). +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/.sqlite`. +- **Restore**: `scripts\restore.cmd db/backups/.sqlite`. It stops `axonasp` and `embed-worker`, verifies the backup (nothing changes if that fails), keeps the current database as `db\backups\pre-restore-.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 diff --git a/app/controllers/ApiPortabilityController.asp b/app/controllers/ApiPortabilityController.asp new file mode 100644 index 0000000..a12bda1 --- /dev/null +++ b/app/controllers/ApiPortabilityController.asp @@ -0,0 +1,1042 @@ +<% +' ApiPortabilityController: canonical export and import (spec FR-018, NFR-007, NFR-009, AC-06, AC-14). +' +' POST /api/v1/exports Export {"namespace_ids":[...]} (optional; default: every namespace the caller can read) +' POST /api/v1/imports Import the document returned by /exports, unchanged (max 8 MiB) +' +' Export document (schema_version 1): +' {"format":"agent-memory-export","schema_version":1,"exported_at":"...","data":{...},"counts":{...}, +' "integrity":{"algorithm":"sha256","digest":""}} +' data.namespaces [{path}], data.memories [{id, namespace, type, lifecycle_status, valid_from, valid_until, created_by, +' created_at, updated_at, current_revision, revisions[...], verifications[...]}], data.documents [{id, namespace, +' source_uri, format, title, current_revision, created_by, created_at, updated_at, revisions[{..., chunks[...]}]}], +' data.evidence_links [{id, owner_kind:"memory", owner_id, owner_revision, target_kind, target_id, target_revision, +' role, excerpt, created_by, created_at}]. +' Canonical records keep their ids, revision numbers, timestamps and principal ids (provenance). Derived data +' (lexical and semantic indexes, content hashes) is rebuilt on import. Not exported in version 1: sessions, +' experiences, learning candidates, feedback, retrieval telemetry, audit events. Evidence whose target the caller +' cannot read is left out (counted in counts.evidence_links_omitted). +' +' Import needs admin on every target namespace (matched by path in the caller's tenant; they must exist). Any id that +' already exists makes the whole import fail (409); any invalid item fails it with 422; nothing is written then. +Const PORT_FORMAT = "agent-memory-export" +Const PORT_SCHEMA = 1 +Const PORT_MAX_IMPORT = 8388608 + +' List of strings joined with a separator, on the native G3STRINGBUILDER (string concatenation in a loop is +' quadratic). The export runs all its queries before building, so no builder is held across G3DB calls. +Class Port_Buf + Private m_sb, m_n, m_sep + + Private Sub Class_Initialize() + Set m_sb = Server.CreateObject("G3STRINGBUILDER") + m_n = 0 + m_sep = "," + End Sub + + Private Sub Class_Terminate() + Set m_sb = Nothing + End Sub + + ' Separator put between items (default ",") + Public Property Let Sep(v) + m_sep = v + End Property + + Public Sub Add(s) + If m_n > 0 Then + If Len(m_sep) > 0 Then + m_sb.Append m_sep + End If + End If + m_sb.Append s + m_n = m_n + 1 + End Sub + + Public Property Get Count() + Count = m_n + End Property + + Public Function Text() + Text = m_sb.ToString() + End Function +End Class + +Class ApiPortabilityController_Class + ' import state + Private m_err, m_nsPaths(), m_nsIds(), m_nsN, m_types, m_memIds, m_cnt() + + Public Property Get useLayout() + useLayout = False + End Property + + Public Property Let useLayout(v) + End Property + + Public Property Get Title() + Title = "Portability API" + End Property + + '--------------------------------------------------------------- + ' POST /api/v1/exports + '--------------------------------------------------------------- + Public Sub Export() + Dim body, input, allowed, requested, arr, i, ok, rs, nsRows, memRows, revRows, verRows, docRows, drRows, chRows, evRows + Dim data, tq, nsList, m, p, v, d, dr, ch, item, sub1, sub2, nMem, nRev, nVer, nDoc, nDr, nCh, nEv, nEvAll, digest, out, ts + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + allowed = Api_AllowedNamespaceIds("read") + If input.HasRaw("namespace_ids") Then + arr = JsonLite_ParseStringArray(input.Raw("namespace_ids")) + If IsNull(arr) Then + Api_Invalid Array("namespace_ids must be an array of namespace ids.") + Exit Sub + End If + requested = "" + For i = 0 To UBound(arr) + If Not Api_IsId(arr(i)) Then + Api_Invalid Array("namespace_ids must be an array of namespace ids.") + Exit Sub + End If + ' only ids the caller can read; others are silently left out (no existence disclosure) + If InStr("," & allowed & ",", ",'" & LCase(arr(i)) & "',") > 0 Then + If Len(requested) > 0 Then + requested = requested & "," + End If + requested = requested & "'" & LCase(arr(i)) & "'" + End If + Next + allowed = requested + ElseIf input.Exists("namespace_ids") Then + If Not IsNull(input.Item("namespace_ids")) Then + Api_Invalid Array("namespace_ids must be an array of namespace ids.") + Exit Sub + End If + End If + + ts = Api_Now() + Set data = New Port_Buf + data.Sep = "" ' items below carry their own commas + nMem = 0 : nRev = 0 : nVer = 0 : nDoc = 0 : nDr = 0 : nCh = 0 : nEv = 0 : nEvAll = 0 + nsRows = Empty : memRows = Empty : revRows = Empty : verRows = Empty : docRows = Empty : drRows = Empty : chRows = Empty : evRows = Empty + If Len(allowed) > 0 Then + tq = "'" & Api_TenantId & "'" ' authenticated tenant id (a UUID), safe to inline + nsRows = Rows("SELECT id, path FROM namespaces WHERE tenant_id = " & tq & " AND id IN (" & allowed & ") ORDER BY path") + memRows = Rows("SELECT id, namespace_id, type, lifecycle_status, valid_from, valid_until, creator_principal_id, created_at, updated_at, current_revision " & _ + "FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ") ORDER BY id") + revRows = Rows("SELECT r.memory_id, r.id, r.revision, r.title, r.summary, r.content, r.attributes, r.tags, r.confidence, r.importance, r.change_reason, " & _ + "r.verification_status, r.created_by, r.created_at FROM memory_revisions r JOIN memories m ON m.id = r.memory_id " & _ + "WHERE m.tenant_id = " & tq & " AND m.namespace_id IN (" & allowed & ") ORDER BY r.memory_id, r.revision") + verRows = Rows("SELECT v.memory_id, v.id, v.revision, v.method, v.result, v.notes, v.reviewer_principal_id, v.created_at FROM verifications v " & _ + "JOIN memories m ON m.id = v.memory_id WHERE m.tenant_id = " & tq & " AND m.namespace_id IN (" & allowed & ") ORDER BY v.memory_id, v.created_at, v.id") + docRows = Rows("SELECT id, namespace_id, source_uri, format, title, current_revision, created_by, created_at, updated_at FROM documents " & _ + "WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ") ORDER BY id") + drRows = Rows("SELECT r.document_id, r.id, r.revision, r.content, r.char_count, r.chunk_count, r.created_by, r.created_at FROM document_revisions r " & _ + "JOIN documents d ON d.id = r.document_id WHERE d.tenant_id = " & tq & " AND d.namespace_id IN (" & allowed & ") ORDER BY r.document_id, r.revision") + chRows = Rows("SELECT c.document_id, c.document_revision, c.id, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, c.token_estimate, c.created_at " & _ + "FROM chunks c JOIN documents d ON d.id = c.document_id WHERE d.tenant_id = " & tq & " AND d.namespace_id IN (" & allowed & ") " & _ + "ORDER BY c.document_id, c.document_revision, c.ordinal") + ' evidence of exported memories whose target the caller can read + evRows = Rows("SELECT id, owner_id, owner_revision, target_kind, target_id, target_revision, role, excerpt, created_by, created_at FROM evidence_links e " & _ + "WHERE e.tenant_id = " & tq & " AND e.owner_kind = 'memory' AND e.owner_id IN (SELECT id FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ")) AND (" & _ + "(e.target_kind = 'memory' AND e.target_id IN (SELECT id FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & "))) OR " & _ + "(e.target_kind = 'document' AND e.target_id IN (SELECT id FROM documents WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & "))) OR " & _ + "(e.target_kind = 'chunk' AND e.target_id IN (SELECT c.id FROM chunks c JOIN documents d ON d.id = c.document_id WHERE d.tenant_id = " & tq & " AND d.namespace_id IN (" & allowed & "))) OR " & _ + "(e.target_kind = 'experience' AND e.target_id IN (SELECT id FROM experiences WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & ")))) ORDER BY e.created_at, e.id") + Set rs = DAL().Query("SELECT COUNT(*) FROM evidence_links WHERE tenant_id = " & tq & " AND owner_kind = 'memory' AND owner_id IN (SELECT id FROM memories WHERE tenant_id = " & tq & " AND namespace_id IN (" & allowed & "))", Empty) + nEvAll = CLng(rs(0)) + rs.Close + End If + + ' namespaces + Set nsList = New Port_Buf + If Not IsEmpty(nsRows) Then + For i = 0 To UBound(nsRows, 2) + nsList.Add "{""path"":" & JsonLite_Quote("" & nsRows(1, i)) & "}" + Next + End If + data.Add "{""namespaces"":[" & nsList.Text() & "],""memories"":[" + + ' memories with revisions and verifications (all three ordered by memory id: merge in one pass) + p = 0 + v = 0 + If Not IsEmpty(memRows) Then + For m = 0 To UBound(memRows, 2) + Set sub1 = New Port_Buf + Do While p <= RowsMax(revRows) + If "" & revRows(0, p) <> "" & memRows(0, m) Then + Exit Do + End If + sub1.Add "{""id"":" & JsonLite_Quote("" & revRows(1, p)) & ",""revision"":" & CLng(revRows(2, p)) & ",""title"":" & JsonLite_Quote("" & revRows(3, p)) & _ + ",""summary"":" & JStr(revRows(4, p)) & ",""content"":" & JsonLite_Quote("" & revRows(5, p)) & ",""attributes"":" & JRaw(revRows(6, p)) & _ + ",""tags"":" & JRaw(revRows(7, p)) & ",""confidence"":" & JNum(revRows(8, p)) & ",""importance"":" & JNum(revRows(9, p)) & _ + ",""change_reason"":" & JStr(revRows(10, p)) & ",""verification_status"":" & JsonLite_Quote("" & revRows(11, p)) & _ + ",""created_by"":" & JsonLite_Quote("" & revRows(12, p)) & ",""created_at"":" & JsonLite_Quote("" & revRows(13, p)) & "}" + nRev = nRev + 1 + p = p + 1 + Loop + Set sub2 = New Port_Buf + Do While v <= RowsMax(verRows) + If "" & verRows(0, v) <> "" & memRows(0, m) Then + Exit Do + End If + sub2.Add "{""id"":" & JsonLite_Quote("" & verRows(1, v)) & ",""revision"":" & CLng(verRows(2, v)) & ",""method"":" & JsonLite_Quote("" & verRows(3, v)) & _ + ",""result"":" & JsonLite_Quote("" & verRows(4, v)) & ",""notes"":" & JStr(verRows(5, v)) & ",""reviewer"":" & JsonLite_Quote("" & verRows(6, v)) & _ + ",""created_at"":" & JsonLite_Quote("" & verRows(7, v)) & "}" + nVer = nVer + 1 + v = v + 1 + Loop + item = "{""id"":" & JsonLite_Quote("" & memRows(0, m)) & ",""namespace"":" & JsonLite_Quote(NsPath(nsRows, "" & memRows(1, m))) & _ + ",""type"":" & JsonLite_Quote("" & memRows(2, m)) & ",""lifecycle_status"":" & JsonLite_Quote("" & memRows(3, m)) & _ + ",""valid_from"":" & JStr(memRows(4, m)) & ",""valid_until"":" & JStr(memRows(5, m)) & ",""created_by"":" & JsonLite_Quote("" & memRows(6, m)) & _ + ",""created_at"":" & JsonLite_Quote("" & memRows(7, m)) & ",""updated_at"":" & JsonLite_Quote("" & memRows(8, m)) & _ + ",""current_revision"":" & CLng(memRows(9, m)) & ",""revisions"":[" & sub1.Text() & "],""verifications"":[" & sub2.Text() & "]}" + If m > 0 Then + item = "," & item + End If + data.Add item + nMem = nMem + 1 + Next + End If + data.Add "],""documents"":[" + + ' documents with revisions and their chunks + dr = 0 + ch = 0 + If Not IsEmpty(docRows) Then + For d = 0 To UBound(docRows, 2) + Set sub1 = New Port_Buf + Do While dr <= RowsMax(drRows) + If "" & drRows(0, dr) <> "" & docRows(0, d) Then + Exit Do + End If + Set sub2 = New Port_Buf + Do While ch <= RowsMax(chRows) + If "" & chRows(0, ch) <> "" & docRows(0, d) Then + Exit Do + End If + If CLng(chRows(1, ch)) <> CLng(drRows(2, dr)) Then + Exit Do + End If + sub2.Add "{""id"":" & JsonLite_Quote("" & chRows(2, ch)) & ",""ordinal"":" & CLng(chRows(3, ch)) & ",""content"":" & JsonLite_Quote("" & chRows(4, ch)) & _ + ",""heading_path"":" & JStr(chRows(5, ch)) & ",""start_offset"":" & CLng(chRows(6, ch)) & ",""end_offset"":" & CLng(chRows(7, ch)) & _ + ",""token_estimate"":" & CLng(chRows(8, ch)) & ",""created_at"":" & JsonLite_Quote("" & chRows(9, ch)) & "}" + nCh = nCh + 1 + ch = ch + 1 + Loop + sub1.Add "{""id"":" & JsonLite_Quote("" & drRows(1, dr)) & ",""revision"":" & CLng(drRows(2, dr)) & ",""content"":" & JsonLite_Quote("" & drRows(3, dr)) & _ + ",""created_by"":" & JsonLite_Quote("" & drRows(6, dr)) & ",""created_at"":" & JsonLite_Quote("" & drRows(7, dr)) & ",""chunks"":[" & sub2.Text() & "]}" + nDr = nDr + 1 + dr = dr + 1 + Loop + item = "{""id"":" & JsonLite_Quote("" & docRows(0, d)) & ",""namespace"":" & JsonLite_Quote(NsPath(nsRows, "" & docRows(1, d))) & _ + ",""source_uri"":" & JStr(docRows(2, d)) & ",""format"":" & JsonLite_Quote("" & docRows(3, d)) & ",""title"":" & JsonLite_Quote("" & docRows(4, d)) & _ + ",""current_revision"":" & CLng(docRows(5, d)) & ",""created_by"":" & JsonLite_Quote("" & docRows(6, d)) & ",""created_at"":" & JsonLite_Quote("" & docRows(7, d)) & _ + ",""updated_at"":" & JsonLite_Quote("" & docRows(8, d)) & ",""revisions"":[" & sub1.Text() & "]}" + If d > 0 Then + item = "," & item + End If + data.Add item + nDoc = nDoc + 1 + Next + End If + data.Add "],""evidence_links"":[" + If Not IsEmpty(evRows) Then + For i = 0 To UBound(evRows, 2) + item = "{""id"":" & JsonLite_Quote("" & evRows(0, i)) & ",""owner_kind"":""memory"",""owner_id"":" & JsonLite_Quote("" & evRows(1, i)) & _ + ",""owner_revision"":" & JNum(evRows(2, i)) & ",""target_kind"":" & JsonLite_Quote("" & evRows(3, i)) & ",""target_id"":" & JsonLite_Quote("" & evRows(4, i)) & _ + ",""target_revision"":" & JNum(evRows(5, i)) & ",""role"":" & JsonLite_Quote("" & evRows(6, i)) & ",""excerpt"":" & JStr(evRows(7, i)) & _ + ",""created_by"":" & JsonLite_Quote("" & evRows(8, i)) & ",""created_at"":" & JsonLite_Quote("" & evRows(9, i)) & "}" + If i > 0 Then + item = "," & item + End If + data.Add item + nEv = nEv + 1 + Next + End If + data.Add "]}" + + out = data.Text() + digest = Api_Sha256(out) + Api_Audit "export.create", "export", "", "ok" + Response.AddHeader "Content-Disposition", "attachment; filename=""agent-memory-export.json""" + Api_Send 200, "{""format"":""" & PORT_FORMAT & """,""schema_version"":" & PORT_SCHEMA & ",""exported_at"":" & JsonLite_Quote(ts) & _ + ",""data"":" & out & ",""counts"":{""namespaces"":" & (RowsMax(nsRows) + 1) & ",""memories"":" & nMem & ",""memory_revisions"":" & nRev & _ + ",""verifications"":" & nVer & ",""documents"":" & nDoc & ",""document_revisions"":" & nDr & ",""chunks"":" & nCh & ",""evidence_links"":" & nEv & _ + ",""evidence_links_omitted"":" & (nEvAll - nEv) & "},""integrity"":{""algorithm"":""sha256"",""digest"":""" & digest & """}}" + End Sub + + '--------------------------------------------------------------- + ' POST /api/v1/imports + '--------------------------------------------------------------- + Public Sub Import() + Dim body, input, dataRaw, integ, data, items, i, k, rs + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBodyMax(PORT_MAX_IMPORT) + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + ' envelope and integrity + If "" & input.Item("format") <> PORT_FORMAT Then + Api_Invalid Array("format must be """ & PORT_FORMAT & """ (a document produced by POST /exports).") + Exit Sub + End If + If VarType(input.Item("schema_version")) <> vbDouble Then + Api_Invalid Array("schema_version is required.") + Exit Sub + End If + If input.Item("schema_version") <> PORT_SCHEMA Then + Api_Error 422, "unsupported_schema_version", "schema_version " & input.Item("schema_version") & " is not supported; this server reads version " & PORT_SCHEMA & "." + Exit Sub + End If + If Not input.HasRaw("data") Then + Api_Invalid Array("data is required.") + Exit Sub + End If + dataRaw = input.Raw("data") + If Not input.HasRaw("integrity") Then + Api_Invalid Array("integrity is required.") + Exit Sub + End If + Set integ = JsonLite_Parse(input.Raw("integrity")) + If integ Is Nothing Then + Api_Invalid Array("integrity must be an object.") + Exit Sub + End If + If LCase("" & integ.Item("algorithm")) <> "sha256" Then + Api_Invalid Array("integrity.algorithm must be sha256.") + Exit Sub + End If + If LCase("" & integ.Item("digest")) <> Api_Sha256(dataRaw) Then + Api_Error 422, "integrity_mismatch", "The sha256 digest of data does not match integrity.digest. The export was changed or reformatted after it was produced." + Exit Sub + End If + Set data = JsonLite_Parse(dataRaw) + If data Is Nothing Then + Api_Invalid Array("data must be an object.") + Exit Sub + End If + + ReDim m_cnt(7) + For i = 0 To 7 + m_cnt(i) = 0 + Next + m_err = "" + m_memIds = "," + m_nsN = 0 + ReDim m_nsPaths(15) + ReDim m_nsIds(15) + m_types = "," + Set rs = DAL().Query("SELECT code FROM memory_types", Empty) + Do While Not rs.EOF + m_types = m_types & LCase("" & rs(0)) & "," + rs.MoveNext + Loop + rs.Close + + ' namespaces: every path must exist in the caller's tenant with admin permission + items = ArrayOf(data, "namespaces") + If Len(m_err) = 0 Then + For i = 0 To UBound(items) + ResolveNamespace items(i) + If Len(m_err) > 0 Then + Exit For + End If + Next + End If + If Len(m_err) > 0 Then + Api_Invalid Array(m_err) + Exit Sub + End If + + On Error Resume Next + DAL().BeginTransaction + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + items = ArrayOf(data, "memories") + If Len(m_err) = 0 Then + For i = 0 To UBound(items) + ImportMemory items(i), i + If Len(m_err) > 0 Then + Exit For + End If + Next + End If + If Len(m_err) = 0 Then + items = ArrayOf(data, "documents") + End If + If Len(m_err) = 0 Then + For i = 0 To UBound(items) + ImportDocument items(i), i + If Len(m_err) > 0 Then + Exit For + End If + Next + End If + If Len(m_err) = 0 Then + items = ArrayOf(data, "evidence_links") + End If + If Len(m_err) = 0 Then + For i = 0 To UBound(items) + ImportEvidence items(i), i + If Len(m_err) > 0 Then + Exit For + End If + Next + End If + + If Len(m_err) > 0 Then + On Error Resume Next + DAL().RollbackTransaction + On Error GoTo 0 + If Left(m_err, 9) = "conflict:" Then + Api_Error 409, "import_conflict", Mid(m_err, 11) & " Nothing was imported." + ElseIf Left(m_err, 3) = "db:" Then + Api_Error 500, "internal_error", "Import failed while writing (" & Mid(m_err, 4) & "). Nothing was imported." + Else + Api_Invalid Array(m_err & " Nothing was imported.") + End If + Api_Audit "import.apply", "import", "", "failed" + Exit Sub + End If + + On Error Resume Next + DAL().CommitTransaction + If Err.Number <> 0 Then + k = Err.Number : Api_NoteDbError + Api_DbFailed k, "" + Exit Sub + End If + On Error GoTo 0 + + Emb_AfterWrite Api_TenantId, 8 + Api_Audit "import.apply", "import", "", "ok" + Api_Send 201, "{""imported"":{""namespaces"":" & m_nsN & ",""memories"":" & m_cnt(0) & ",""memory_revisions"":" & m_cnt(1) & ",""verifications"":" & m_cnt(2) & _ + ",""documents"":" & m_cnt(3) & ",""document_revisions"":" & m_cnt(4) & ",""chunks"":" & m_cnt(5) & ",""evidence_links"":" & m_cnt(6) & "}" & _ + ",""indexing"":{""lexical"":""indexed"",""semantic"":""pending""}}" + End Sub + + '=============================================================== + ' Import helpers. Each sets m_err ("" = fine; "conflict: ..." = 409; "db: ..." = 500; else 422) and returns. + '=============================================================== + Private Sub ResolveNamespace(objText) + Dim o, path, rs, id + Set o = JsonLite_Parse(objText) + path = "" + If Not o Is Nothing Then + path = Trim("" & o.Item("path")) + End If + If Len(path) = 0 Or Left(path, 1) <> "/" Then + m_err = "data.namespaces: each entry needs a path starting with /." + Exit Sub + End If + Set rs = DAL().Query("SELECT id FROM namespaces WHERE tenant_id = ? AND path = ?", Array(Api_TenantId, path)) + id = "" + If Not rs.EOF Then + id = "" & rs(0) + End If + rs.Close + If Len(id) = 0 Then + m_err = "namespace " & path & " does not exist or you lack admin permission on it (create it and grant admin first)." + Exit Sub + End If + If Not Api_CanAccessNamespace(id, "admin") Then + m_err = "namespace " & path & " does not exist or you lack admin permission on it (create it and grant admin first)." + Exit Sub + End If + If m_nsN > UBound(m_nsPaths) Then + ReDim Preserve m_nsPaths(m_nsN * 2) + ReDim Preserve m_nsIds(m_nsN * 2) + End If + m_nsPaths(m_nsN) = path + m_nsIds(m_nsN) = id + m_nsN = m_nsN + 1 + End Sub + + Private Function NsIdOf(path) + Dim i + NsIdOf = "" + For i = 0 To m_nsN - 1 + If m_nsPaths(i) = path Then + NsIdOf = m_nsIds(i) + Exit Function + End If + Next + End Function + + Private Sub ImportMemory(objText, idx) + Dim o, at, id, nsId, memType, life, curRev, revs, vers, i, r, rv, rid, title, content, tagsRaw, attrRaw, vs, curTitle, curContent, curTags, revSeen, ver + + at = "data.memories[" & idx & "]" + Set o = JsonLite_Parse(objText) + If o Is Nothing Then + m_err = at & " must be an object." + Exit Sub + End If + id = NeedId(o, "id", at) + nsId = NeedNs(o, at) + memType = LCase(NeedStr(o, "type", at, 40)) + life = NeedEnum(o, "lifecycle_status", at, ",active,retired,superseded,") + curRev = NeedInt(o, "current_revision", at, 1, 100000) + If Len(m_err) > 0 Then + Exit Sub + End If + If InStr(m_types, "," & memType & ",") = 0 Then + m_err = at & ".type '" & memType & "' is not a known memory type." + Exit Sub + End If + If IdTaken("SELECT 1 FROM memories WHERE id = ?", id) Then + m_err = "conflict: memory " & id & " already exists." + Exit Sub + End If + + revs = ArrayOf(o, "revisions") + If Len(m_err) > 0 Then + m_err = at & ": " & m_err + Exit Sub + End If + If UBound(revs) + 1 <> curRev Then + m_err = at & ".revisions must hold revisions 1.." & curRev & " (current_revision)." + Exit Sub + End If + On Error Resume Next + DAL().Execute "INSERT INTO memories (id, tenant_id, namespace_id, type, current_revision, lifecycle_status, creator_principal_id, created_at, updated_at) VALUES (?, ?, ?, ?, " & curRev & ", ?, ?, ?, ?)", _ + Array(id, Api_TenantId, nsId, memType, life, NeedId(o, "created_by", at), NeedTs(o, "created_at", at), NeedTs(o, "updated_at", at)) + DAL().Execute "UPDATE memories SET valid_from = ?, valid_until = ? WHERE id = ?", Array(OptStr(o, "valid_from", at, 40), OptStr(o, "valid_until", at, 40), id) + If Err.Number <> 0 Then + m_err = "db: memory " & id & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) > 0 Then + Exit Sub + End If + m_cnt(0) = m_cnt(0) + 1 + m_memIds = m_memIds & id & "," + + revSeen = "," + For i = 0 To UBound(revs) + Set r = JsonLite_Parse(revs(i)) + rv = at & ".revisions[" & i & "]" + If r Is Nothing Then + m_err = rv & " must be an object." + Exit Sub + End If + rid = NeedId(r, "id", rv) + ver = NeedInt(r, "revision", rv, 1, curRev) + title = NeedStr(r, "title", rv, 200) + content = NeedStr(r, "content", rv, 100000) + vs = NeedEnum(r, "verification_status", rv, ",unverified,verified,disputed,rejected,") + tagsRaw = OptRaw(r, "tags", rv, "[") + attrRaw = OptRaw(r, "attributes", rv, "{") + If Len(m_err) > 0 Then + Exit Sub + End If + If InStr(revSeen, "," & ver & ",") > 0 Then + m_err = rv & ".revision " & ver & " appears twice." + Exit Sub + End If + revSeen = revSeen & ver & "," + If IdTaken("SELECT 1 FROM memory_revisions WHERE id = ?", rid) Then + m_err = "conflict: memory revision " & rid & " already exists." + Exit Sub + End If + On Error Resume Next + DAL().Execute "INSERT INTO memory_revisions (id, memory_id, revision, title, content, content_hash, created_by, created_at) VALUES (?, ?, " & ver & ", ?, ?, ?, ?, ?)", _ + Array(rid, id, title, content, Mem_Hash(nsId, memType, title, content), NeedId(r, "created_by", rv), NeedTs(r, "created_at", rv)) + DAL().Execute "UPDATE memory_revisions SET summary = ?, attributes = ?, tags = ?, confidence = ?, importance = ?, change_reason = ?, verification_status = ? WHERE id = ?", _ + Array(OptStr(r, "summary", rv, 2000), attrRaw, tagsRaw, OptUnit(r, "confidence", rv), OptUnit(r, "importance", rv), OptStr(r, "change_reason", rv, 2000), vs, rid) + If Err.Number <> 0 Then + m_err = "db: memory revision " & rid & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) > 0 Then + Exit Sub + End If + m_cnt(1) = m_cnt(1) + 1 + If ver = curRev Then + curTitle = title + curContent = content + curTags = tagsRaw + End If + Next + + vers = ArrayOf(o, "verifications") + If Len(m_err) > 0 Then + m_err = at & ": " & m_err + Exit Sub + End If + For i = 0 To UBound(vers) + Set r = JsonLite_Parse(vers(i)) + rv = at & ".verifications[" & i & "]" + If r Is Nothing Then + m_err = rv & " must be an object." + Exit Sub + End If + rid = NeedId(r, "id", rv) + ver = NeedInt(r, "revision", rv, 1, curRev) + vs = NeedEnum(r, "result", rv, ",verified,disputed,rejected,") + If Len(m_err) > 0 Then + Exit Sub + End If + If IdTaken("SELECT 1 FROM verifications WHERE id = ?", rid) Then + m_err = "conflict: verification " & rid & " already exists." + Exit Sub + End If + On Error Resume Next + DAL().Execute "INSERT INTO verifications (id, memory_id, revision, method, result, notes, reviewer_principal_id, created_at) VALUES (?, ?, " & ver & ", ?, ?, ?, ?, ?)", _ + Array(rid, id, NeedStr(r, "method", rv, 100), vs, OptStr(r, "notes", rv, 2000), NeedId(r, "reviewer", rv), NeedTs(r, "created_at", rv)) + If Err.Number <> 0 Then + m_err = "db: verification " & rid & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) > 0 Then + Exit Sub + End If + m_cnt(2) = m_cnt(2) + 1 + Next + + ' derived data: lexical index now, semantic index after commit + On Error Resume Next + Search_IndexMemory id, curRev, Api_TenantId, nsId, curTitle, curContent, curTags + Emb_MarkPending "memory", id, Api_TenantId, nsId, curRev + If Err.Number <> 0 Then + m_err = "db: indexing memory " & id & ": " & Err.Description + Err.Clear + End If + On Error GoTo 0 + End Sub + + Private Sub ImportDocument(objText, idx) + Dim o, at, id, nsId, fmt, curRev, revs, i, j, r, rv, rid, ver, content, chunks, c, cv, cid, revSeen, nCh + + at = "data.documents[" & idx & "]" + Set o = JsonLite_Parse(objText) + If o Is Nothing Then + m_err = at & " must be an object." + Exit Sub + End If + id = NeedId(o, "id", at) + nsId = NeedNs(o, at) + fmt = NeedEnum(o, "format", at, ",text,markdown,") + curRev = NeedInt(o, "current_revision", at, 1, 100000) + If Len(m_err) > 0 Then + Exit Sub + End If + If IdTaken("SELECT 1 FROM documents WHERE id = ?", id) Then + m_err = "conflict: document " & id & " already exists." + Exit Sub + End If + revs = ArrayOf(o, "revisions") + If Len(m_err) > 0 Then + m_err = at & ": " & m_err + Exit Sub + End If + If UBound(revs) + 1 <> curRev Then + m_err = at & ".revisions must hold revisions 1.." & curRev & " (current_revision)." + Exit Sub + End If + On Error Resume Next + DAL().Execute "INSERT INTO documents (id, tenant_id, namespace_id, format, title, current_revision, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, " & curRev & ", ?, ?, ?)", _ + Array(id, Api_TenantId, nsId, fmt, NeedStr(o, "title", at, 500), NeedId(o, "created_by", at), NeedTs(o, "created_at", at), NeedTs(o, "updated_at", at)) + DAL().Execute "UPDATE documents SET source_uri = ? WHERE id = ?", Array(OptStr(o, "source_uri", at, 2000), id) + If Err.Number <> 0 Then + m_err = "db: document " & id & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) > 0 Then + Exit Sub + End If + m_cnt(3) = m_cnt(3) + 1 + + revSeen = "," + For i = 0 To UBound(revs) + Set r = JsonLite_Parse(revs(i)) + rv = at & ".revisions[" & i & "]" + If r Is Nothing Then + m_err = rv & " must be an object." + Exit Sub + End If + rid = NeedId(r, "id", rv) + ver = NeedInt(r, "revision", rv, 1, curRev) + content = NeedStr(r, "content", rv, 1048576) + chunks = ArrayOf(r, "chunks") + If Len(m_err) > 0 Then + Exit Sub + End If + If InStr(revSeen, "," & ver & ",") > 0 Then + m_err = rv & ".revision " & ver & " appears twice." + Exit Sub + End If + revSeen = revSeen & ver & "," + If IdTaken("SELECT 1 FROM document_revisions WHERE id = ?", rid) Then + m_err = "conflict: document revision " & rid & " already exists." + Exit Sub + End If + nCh = UBound(chunks) + 1 + On Error Resume Next + DAL().Execute "INSERT INTO document_revisions (id, document_id, revision, content_hash, content, char_count, chunk_count, created_by, created_at) VALUES (?, ?, " & ver & ", ?, ?, " & Len(content) & ", " & nCh & ", ?, ?)", _ + Array(rid, id, Api_Sha256(content), content, NeedId(r, "created_by", rv), NeedTs(r, "created_at", rv)) + If Err.Number <> 0 Then + m_err = "db: document revision " & rid & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) > 0 Then + Exit Sub + End If + m_cnt(4) = m_cnt(4) + 1 + + For j = 0 To UBound(chunks) + Set c = JsonLite_Parse(chunks(j)) + cv = rv & ".chunks[" & j & "]" + If c Is Nothing Then + m_err = cv & " must be an object." + Exit Sub + End If + cid = NeedId(c, "id", cv) + If Len(m_err) > 0 Then + Exit Sub + End If + If IdTaken("SELECT 1 FROM chunks WHERE id = ?", cid) Then + m_err = "conflict: chunk " & cid & " already exists." + Exit Sub + End If + On Error Resume Next + DAL().Execute "INSERT INTO chunks (id, document_id, document_revision, ordinal, content, heading_path, start_offset, end_offset, token_estimate, created_at) VALUES (?, ?, " & ver & ", " & _ + NeedInt(c, "ordinal", cv, 0, 1000000) & ", ?, ?, " & NeedInt(c, "start_offset", cv, 0, 100000000) & ", " & NeedInt(c, "end_offset", cv, 0, 100000000) & ", " & _ + NeedInt(c, "token_estimate", cv, 0, 100000000) & ", ?)", Array(cid, id, NeedStr(c, "content", cv, 1048576), OptStr(c, "heading_path", cv, 2000), NeedTs(c, "created_at", cv)) + If Err.Number <> 0 Then + m_err = "db: chunk " & cid & ": " & Err.Description + Err.Clear + Exit Sub + End If + ' the current revision is searchable: lexical index now, semantic index after commit + If ver = curRev Then + DAL().Execute "INSERT INTO chunks_fts (content, chunk_id, tenant_id, namespace_id) VALUES (?, ?, ?, ?)", Array("" & c.Item("content"), cid, Api_TenantId, nsId) + Emb_MarkPending "chunk", cid, Api_TenantId, nsId, ver + End If + If Err.Number <> 0 Then + m_err = "db: indexing chunk " & cid & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) > 0 Then + Exit Sub + End If + m_cnt(5) = m_cnt(5) + 1 + Next + Next + End Sub + + Private Sub ImportEvidence(objText, idx) + Dim o, at, id, ownerId, kind + at = "data.evidence_links[" & idx & "]" + Set o = JsonLite_Parse(objText) + If o Is Nothing Then + m_err = at & " must be an object." + Exit Sub + End If + id = NeedId(o, "id", at) + ownerId = NeedId(o, "owner_id", at) + kind = NeedEnum(o, "target_kind", at, ",experience,chunk,memory,document,") + NeedEnum o, "owner_kind", at, ",memory," + If Len(m_err) > 0 Then + Exit Sub + End If + If InStr(m_memIds, "," & ownerId & ",") = 0 Then + m_err = at & ".owner_id must be a memory of this export." + Exit Sub + End If + If IdTaken("SELECT 1 FROM evidence_links WHERE id = ?", id) Then + m_err = "conflict: evidence link " & id & " already exists." + Exit Sub + End If + On Error Resume Next + DAL().Execute "INSERT INTO evidence_links (id, tenant_id, owner_kind, owner_id, target_kind, target_id, created_by, created_at) VALUES (?, ?, 'memory', ?, ?, ?, ?, ?)", _ + Array(id, Api_TenantId, ownerId, kind, NeedId(o, "target_id", at), NeedId(o, "created_by", at), NeedTs(o, "created_at", at)) + DAL().Execute "UPDATE evidence_links SET owner_revision = ?, target_revision = ?, role = ?, excerpt = ? WHERE id = ?", _ + Array(OptInt(o, "owner_revision", at), OptInt(o, "target_revision", at), NeedEnum(o, "role", at, ",supports,contradicts,context,"), OptStr(o, "excerpt", at, 2000), id) + If Err.Number <> 0 Then + m_err = "db: evidence link " & id & ": " & Err.Description + Err.Clear + Exit Sub + End If + On Error GoTo 0 + If Len(m_err) = 0 Then + m_cnt(6) = m_cnt(6) + 1 + End If + End Sub + + ' ---- field readers (first error wins; they return a harmless value after an error) ---- + Private Sub Fail(msg) + If Len(m_err) = 0 Then + m_err = msg + End If + End Sub + + Private Function ArrayOf(o, k) + Dim a + ArrayOf = Array() + If Not o.HasRaw(k) Then + If o.Exists(k) Then + If Not IsNull(o.Item(k)) Then + Fail k & " must be an array of objects." + End If + End If + Exit Function + End If + a = JsonLite_SplitObjectArray(o.Raw(k)) + If IsNull(a) Then + Fail k & " must be an array of objects." + Exit Function + End If + ArrayOf = a + End Function + + Private Function NeedStr(o, k, at, maxLen) + Dim v + NeedStr = "" + v = o.Item(k) + If VarType(v) <> vbString Then + Fail at & "." & k & " is required (string)." + Exit Function + End If + If Len(v) = 0 Or Len(v) > maxLen Then + Fail at & "." & k & " must be 1 to " & maxLen & " characters." + Exit Function + End If + NeedStr = v + End Function + + Private Function OptStr(o, k, at, maxLen) + Dim v + OptStr = Null + v = o.Item(k) + If IsNull(v) Then + Exit Function + End If + If VarType(v) <> vbString Then + Fail at & "." & k & " must be a string or null." + Exit Function + End If + If Len(v) > maxLen Then + Fail at & "." & k & " must be at most " & maxLen & " characters." + Exit Function + End If + OptStr = v + End Function + + Private Function NeedId(o, k, at) + Dim v + v = NeedStr(o, k, at, 64) + If Len(v) > 0 Then + If Not Api_IsId(v) Then + Fail at & "." & k & " must be a UUID." + End If + End If + NeedId = LCase(v) + End Function + + Private Function NeedTs(o, k, at) + NeedTs = NeedStr(o, k, at, 40) + End Function + + Private Function NeedEnum(o, k, at, allowedList) + Dim v + v = LCase(NeedStr(o, k, at, 40)) + If Len(v) > 0 Then + If InStr(allowedList, "," & v & ",") = 0 Then + Fail at & "." & k & " must be one of " & Mid(allowedList, 2, Len(allowedList) - 2) & "." + End If + End If + NeedEnum = v + End Function + + Private Function NeedInt(o, k, at, lo, hi) + Dim v + NeedInt = lo + v = o.Item(k) + If VarType(v) <> vbDouble Then + Fail at & "." & k & " is required (integer)." + Exit Function + End If + If v <> Int(v) Or v < lo Or v > hi Then + Fail at & "." & k & " must be an integer between " & lo & " and " & hi & "." + Exit Function + End If + NeedInt = CLng(v) + End Function + + Private Function OptInt(o, k, at) + Dim v + OptInt = Null + v = o.Item(k) + If IsNull(v) Then + Exit Function + End If + OptInt = NeedInt(o, k, at, 0, 100000000) + End Function + + Private Function OptUnit(o, k, at) + Dim v + OptUnit = Null + v = o.Item(k) + If IsNull(v) Then + Exit Function + End If + If VarType(v) <> vbDouble Then + Fail at & "." & k & " must be a number between 0 and 1." + Exit Function + End If + If v < 0 Or v > 1 Then + Fail at & "." & k & " must be a number between 0 and 1." + Exit Function + End If + OptUnit = v + End Function + + ' Raw JSON array/object text (first character `first`), or Null + Private Function OptRaw(o, k, at, first) + Dim raw + OptRaw = Null + If Not o.HasRaw(k) Then + If o.Exists(k) Then + If Not IsNull(o.Item(k)) Then + Fail at & "." & k & " has the wrong type." + End If + End If + Exit Function + End If + raw = o.Raw(k) + If Left(raw, 1) <> first Then + Fail at & "." & k & " has the wrong type." + Exit Function + End If + OptRaw = raw + End Function + + Private Function NeedNs(o, at) + Dim path, id + path = NeedStr(o, "namespace", at, 500) + NeedNs = "" + If Len(path) = 0 Then + Exit Function + End If + id = NsIdOf(path) + If Len(id) = 0 Then + Fail at & ".namespace " & path & " is not listed in data.namespaces." + Exit Function + End If + NeedNs = id + End Function + + Private Function IdTaken(sql, id) + Dim rs + Set rs = DAL().Query(sql, id) + IdTaken = Not rs.EOF + rs.Close + End Function + + ' ---- export helpers ---- + Private Function Rows(sql) + Dim rs + Rows = Empty + Set rs = DAL().Query(sql, Empty) + If Not rs.EOF Then + Rows = rs.GetRows() + End If + rs.Close + End Function + + Private Function RowsMax(r) + If IsEmpty(r) Then + RowsMax = -1 + Else + RowsMax = UBound(r, 2) + End If + End Function + + Private Function NsPath(nsRows, nsId) + Dim i + NsPath = "" + For i = 0 To RowsMax(nsRows) + If "" & nsRows(0, i) = nsId Then + NsPath = "" & nsRows(1, i) + Exit Function + End If + Next + 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) + If IsNull(v) Then + JRaw = "null" + ElseIf Len("" & v) = 0 Then + JRaw = "null" + Else + JRaw = "" & v + End If + 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 "export" : Export + Case "import" : Import + Case Else + Err.Raise 438, "ApiPortabilityController_Class", "Action '" & actionName & "' not found" + End Select + End Sub + +End Class + +Dim ApiPortabilityController_Class__Singleton +Function ApiPortabilityController() + If IsEmpty(ApiPortabilityController_Class__Singleton) Then + Set ApiPortabilityController_Class__Singleton = New ApiPortabilityController_Class + End If + Set ApiPortabilityController = ApiPortabilityController_Class__Singleton +End Function + +' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) +Sub ApiPortabilityController_Invoke(actionName, args) + ApiPortabilityController().Invoke actionName, args +End Sub +%> diff --git a/app/controllers/autoload_controllers.asp b/app/controllers/autoload_controllers.asp index ccd3076..34832b5 100644 --- a/app/controllers/autoload_controllers.asp +++ b/app/controllers/autoload_controllers.asp @@ -7,3 +7,4 @@ + diff --git a/core/lib.Api.asp b/core/lib.Api.asp index 4f1dc09..961d531 100644 --- a/core/lib.Api.asp +++ b/core/lib.Api.asp @@ -77,6 +77,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" @@ -133,15 +134,20 @@ 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 @@ -155,66 +161,109 @@ Function Api_ReadBody() 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_ReadBody = text + 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 - ' 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 - out = out & ChrW(65533) + 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 - out = out & ChrW(cp) + cp = cp * 64 + (b And 63) End If - i = i + extra + 1 + 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 diff --git a/core/lib.ControllerRegistry.asp b/core/lib.ControllerRegistry.asp index dcaef1c..aee2d2a 100644 --- a/core/lib.ControllerRegistry.asp +++ b/core/lib.ControllerRegistry.asp @@ -17,6 +17,7 @@ Class ControllerRegistry_Class RegisterController "errorcontroller" RegisterController "apicontextcontroller" RegisterController "apilearningcontroller" + RegisterController "apiportabilitycontroller" RegisterController "apidocumentscontroller" RegisterController "apihealthcontroller" RegisterController "apisessionscontroller" diff --git a/core/lib.JsonLite.asp b/core/lib.JsonLite.asp index 661dd7b..b94307f 100644 --- a/core/lib.JsonLite.asp +++ b/core/lib.JsonLite.asp @@ -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 @@ -12,12 +12,18 @@ ' 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 @@ -105,140 +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, m_sur + Private m_t, m_n, m_i, m_ok, m_sur Public Property Get SurrogateSeen() SurrogateSeen = (m_sur = True) End Property - Public Function Run(text) - Dim obj + Private Function Load(text) m_sur = False - m_s = "" & text - m_len = Len(m_s) - m_pos = 1 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 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) - End If - SkipWs - If m_pos > m_len Then - m_ok = False - Exit Function + obj.AddRaw k, JsonLite_JoinTokens(m_t, rawStart, m_i - 1) 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 @@ -247,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 @@ -281,75 +296,73 @@ 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 @@ -359,18 +372,20 @@ Class JsonLite_Parser If cu < 0 Then cu = cu + 65536 End If - m_pos = m_pos + 4 ' 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 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 < 0 Then - lo = lo + 65536 - End If - If lo >= 56320 And lo <= 57343 Then - m_pos = m_pos + 6 + 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 @@ -378,16 +393,15 @@ Class JsonLite_Parser m_sur = True cu = 65533 End If - out = out & ChrW(cu) + 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) @@ -412,59 +426,47 @@ End Function ' Raw texts of the objects in a JSON array of objects ("[{...},{...}]"), each parseable with JsonLite_Parse. ' Returns an empty array for "[]", Null when the text is not an array whose elements are all objects. -' The text has already been validated as JSON by the body parse, so only depth and strings are tracked. +' 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, i, n, c, depth, inStr_, esc, start, items(), cnt + Dim t, n, i, tok, depth, start, items(), cnt JsonLite_SplitObjectArray = Null - t = Trim("" & text) - n = Len(t) + 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 Left(t, 1) <> "[" Or Right(t, 1) <> "]" Then + If t(0) <> "[" Or t(n - 1) <> "]" Then Exit Function End If cnt = 0 ReDim items(7) depth = 0 - inStr_ = False - esc = False start = 0 - For i = 2 To n - 1 - c = Mid(t, i, 1) - If inStr_ Then - If esc Then - esc = False - ElseIf c = "\" Then - esc = True - ElseIf c = """" Then - inStr_ = False - End If - ElseIf c = """" Then - If depth = 0 Then - Exit Function ' a string element - End If - inStr_ = True - ElseIf c = "{" Or c = "[" Then + For i = 1 To n - 2 + tok = t(i) + If tok = "{" Or tok = "[" Then If depth = 0 Then - If c = "[" Then + If tok = "[" Then Exit Function ' a nested array element End If start = i End If depth = depth + 1 - ElseIf c = "}" Or c = "]" Then + 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) = Mid(t, start, i - start + 1) + items(cnt) = JsonLite_JoinTokens(t, start, i) cnt = cnt + 1 End If ElseIf depth = 0 Then - If c <> "," And c <> " " And c <> vbTab And c <> vbCr And c <> vbLf Then - Exit Function ' a number/true/false/null element + If tok <> "," Then + Exit Function ' a string/number/true/false/null element End If End If Next @@ -487,30 +489,24 @@ Function JsonLite_Parse(text) 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) diff --git a/public/Default.asp b/public/Default.asp index 8aa9cc7..ffbe72d 100644 --- a/public/Default.asp +++ b/public/Default.asp @@ -51,6 +51,10 @@ 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() diff --git a/public/api/memory-v1.openapi.json b/public/api/memory-v1.openapi.json index aa3f449..6494c5f 100644 --- a/public/api/memory-v1.openapi.json +++ b/public/api/memory-v1.openapi.json @@ -1046,6 +1046,120 @@ "type": "string" } } + }, + "ExportRequest": { + "type": "object", + "properties": { + "namespace_ids": { + "type": "array", + "items": { + "type": "string", + "format": "uuid" + }, + "description": "Limit the export to these namespaces (unreadable ones are skipped silently). Default: all readable namespaces." + } + } + }, + "Export": { + "type": "object", + "required": [ + "format", + "schema_version", + "data", + "integrity" + ], + "properties": { + "format": { + "type": "string", + "enum": [ + "agent-memory-export" + ] + }, + "schema_version": { + "type": "integer", + "enum": [ + 1 + ] + }, + "exported_at": { + "type": "string" + }, + "data": { + "type": "object", + "description": "namespaces [{path}], memories [{id, namespace, type, lifecycle_status, valid_from, valid_until, created_by, created_at, updated_at, current_revision, revisions[], verifications[]}], documents [{id, namespace, source_uri, format, title, current_revision, created_by, created_at, updated_at, revisions[{..., chunks[]}]}], evidence_links [{id, owner_kind, owner_id, owner_revision, target_kind, target_id, target_revision, role, excerpt, created_by, created_at}]. Not in version 1: sessions, experiences, candidates, feedback, retrieval telemetry, audit events.", + "properties": { + "namespaces": { + "type": "array", + "items": { + "type": "object" + } + }, + "memories": { + "type": "array", + "items": { + "type": "object" + } + }, + "documents": { + "type": "array", + "items": { + "type": "object" + } + }, + "evidence_links": { + "type": "array", + "items": { + "type": "object" + } + } + } + }, + "counts": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + "description": "namespaces, memories, memory_revisions, verifications, documents, document_revisions, chunks, evidence_links, evidence_links_omitted" + }, + "integrity": { + "type": "object", + "properties": { + "algorithm": { + "type": "string", + "enum": [ + "sha256" + ] + }, + "digest": { + "type": "string", + "description": "Hex SHA-256 of the exact UTF-8 text of the data value as it appears in the document; any reformatting breaks it." + } + } + } + } + }, + "ImportResult": { + "type": "object", + "properties": { + "imported": { + "type": "object", + "additionalProperties": { + "type": "integer" + }, + "description": "namespaces, memories, memory_revisions, verifications, documents, document_revisions, chunks, evidence_links" + }, + "indexing": { + "type": "object", + "properties": { + "lexical": { + "type": "string" + }, + "semantic": { + "type": "string" + } + } + } + } } } }, @@ -3494,6 +3608,176 @@ } } } + }, + "/exports": { + "post": { + "summary": "Export every namespace the caller can read (or the namespace_ids given) as one canonical, integrity-protected JSON document. Evidence whose target the caller cannot read is left out and counted in counts.evidence_links_omitted. Sent as an attachment.", + "tags": [ + "portability" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": false, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ExportRequest" + } + } + } + }, + "responses": { + "200": { + "description": "The export document", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Export" + } + } + } + }, + "400": { + "description": "Invalid JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed (namespace_ids is not an array of ids)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/imports": { + "post": { + "summary": "Import a document produced by POST /exports, unchanged (max 8 MiB). Needs admin on every target namespace, matched by path in the caller's tenant (they must exist). Ids, revisions, timestamps and principal ids are kept; content hashes and the lexical index are rebuilt and embeddings are queued. All or nothing.", + "tags": [ + "portability" + ], + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Export" + } + } + } + }, + "responses": { + "201": { + "description": "Imported", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ImportResult" + } + } + } + }, + "400": { + "description": "Empty body or invalid JSON", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "401": { + "description": "Missing, invalid, revoked or expired API key", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "409": { + "description": "import_conflict: an id in the document already exists; nothing was imported", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "body_too_large: more than 8 MiB", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed: wrong format, unsupported_schema_version, integrity_mismatch, a missing target namespace, no admin permission on it, or an invalid item; nothing was imported", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error; nothing was imported", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } } } } diff --git a/scripts/backup.asp b/scripts/backup.asp new file mode 100644 index 0000000..3e97372 --- /dev/null +++ b/scripts/backup.asp @@ -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 PRAGMA integrity_check, foreign_key_check, latest migration and row counts per table +' restore verifies , keeps the current database as db/backups/pre-restore-.sqlite, then copies +' 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). +%> + +<% +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/.sqlite]" +End Select +If ok Then + Say "RESULT: ok" +Else + Say "RESULT: failed" +End If +%> diff --git a/scripts/backup.cmd b/scripts/backup.cmd new file mode 100644 index 0000000..05c5d0e --- /dev/null +++ b/scripts/backup.cmd @@ -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 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 . 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 ^: 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% diff --git a/scripts/restore.cmd b/scripts/restore.cmd new file mode 100644 index 0000000..71ce4a3 --- /dev/null +++ b/scripts/restore.cmd @@ -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-.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/^.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-^.sqlite. + exit /b 1 +) +call "%~dp0embed.cmd" reindex +exit /b 0 diff --git a/tests/backup-restore.sh b/tests/backup-restore.sh new file mode 100644 index 0000000..f1297b3 --- /dev/null +++ b/tests/backup-restore.sh @@ -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 [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 ] diff --git a/tests/phase3-portability.sh b/tests/phase3-portability.sh new file mode 100644 index 0000000..0bc0192 --- /dev/null +++ b/tests/phase3-portability.sh @@ -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 '' 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 [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 " "$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 ]