소스 검색

Export/import API and backup/restore procedure

- POST /exports: canonical agent-memory-export document (schema_version 1,
  sha256 digest over data), filtered by read permission; POST /imports keeps
  ids, revisions, timestamps and provenance, rebuilds derived data, and is
  all-or-nothing (409 conflict, 422 format/schema/integrity, 413 over 8 MiB)
- JsonLite: RegExp tokenizer; Api_Utf8Decode works on byte runs (builtins cost
  time proportional to string length, per-character loops timed out)
- scripts/backup.cmd (VACUUM INTO + integrity/foreign key/row-count checks),
  scripts/restore.cmd; restore drill into an isolated container
- Tests: phase3-portability.sh (44), backup-restore.sh (21); docs and OpenAPI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pull/1/head
부모
커밋
92d8f4a7a4
15개의 변경된 파일과 2260개의 추가작업 그리고 276개의 파일을 삭제
  1. +3
    -0
      .gitignore
  2. +10
    -2
      AGENTS.md
  3. +14
    -2
      README.md
  4. +1042
    -0
      app/controllers/ApiPortabilityController.asp
  5. +1
    -0
      app/controllers/autoload_controllers.asp
  6. +97
    -48
      core/lib.Api.asp
  7. +1
    -0
      core/lib.ControllerRegistry.asp
  8. +220
    -224
      core/lib.JsonLite.asp
  9. +4
    -0
      public/Default.asp
  10. +284
    -0
      public/api/memory-v1.openapi.json
  11. +286
    -0
      scripts/backup.asp
  12. +18
    -0
      scripts/backup.cmd
  13. +29
    -0
      scripts/restore.cmd
  14. +106
    -0
      tests/backup-restore.sh
  15. +145
    -0
      tests/phase3-portability.sh

+ 3
- 0
.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/

+ 10
- 2
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 <file>` (`scripts/backup.asp`; see README "Operations"). Backups go to `db/backups/` (git-ignored). `bash tests/backup-restore.sh` restores into an isolated container on port 8802 and never touches the live database. Never run `restore.cmd` against the live database without the user's go-ahead.
- 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]' <file>`, and in shell code prefer `tr -d '[:cntrl:]'`-style classes or octal escapes.
- **Builtins cost time proportional to the string length.** On this build `Len`, `Mid`, `InStr` and friends take time that grows with the length of the string they get (`Len` of 200 KB about 0.4 ms, `InStr` about 5 ms), so a per-character loop over a large string is quadratic and hit the 60 s script timeout (JSON parsing of an import). Process large text in bulk: `VBScript.RegExp` (`Execute` over 450 KB took 30 ms), `Replace`, `Split`, and `G3STRINGBUILDER` (`Append`/`ToString`) instead of `s = s & x` in loops. `core/lib.JsonLite.asp` tokenizes with one RegExp and `Api_Utf8Decode` works on byte runs for this reason.
- **A request that times out keeps running.** After the script timeout the client gets its error, but the script goroutine is detached and carries on, possibly holding an open G3DB transaction; later requests then fail or wait. Restart the container after a timeout during development, and keep long work (imports, rebuilds) well under the limit.
- **RegExp quirks.** `Match.FirstIndex`/`Length` are byte offsets into the UTF-8 text, not character positions (contrary to the manual), so do not `Mid` with them on non-ASCII strings; use `Execute` results' `Value` or `Replace`/`Split` instead. A literal backslash or bracket inside a character class (`[^"\\]`) fails in AxonASP's pattern translation: write `\x5C`, `\x5B`, `\x5D`.
- **`G3AXON.FUNCTIONS` `AxUrlDecode` also turns `+` into a space.** It is used to decode percent-encoded UTF-8 byte runs that cannot contain `+`; do not feed it raw text.
- **Fixed-size array members fail.** `Private m_cnt(7)` in a Class gave "Subscript out of range" when used; declare `Private m_cnt()` and `ReDim m_cnt(7)` in a method.
- **`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.


+ 14
- 2
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/<file>.sqlite`.
- **Restore**: `scripts\restore.cmd db/backups/<file>.sqlite`. It stops `axonasp` and `embed-worker`, verifies the backup (nothing changes if that fails), keeps the current database as `db\backups\pre-restore-<timestamp>.sqlite`, copies the backup into place, starts both containers and runs `scripts\embed.cmd reindex`. If the backup is older than the code's schema, run `scripts\migrate.cmd up` afterwards (once per pending migration).
- **Recovery objectives**: the recovery point (RPO) is the backup interval; schedule `scripts\backup.cmd backup` (for example hourly with Task Scheduler or cron) to match the loss you can accept. The recovery time (RTO) is the restore plus the reindex. The drill `bash tests/backup-restore.sh` restores a fresh backup into an isolated container (own db folder, port 8802; the live database is not touched), checks that the restored server returns the same export as the live one, and fails if it takes longer than `RTO_SECONDS` (default 120). Measured here: about 70 to 100 seconds, almost all of it the first start of a new container; `restore.cmd` restarts the existing containers instead. The reindex time grows with the data and does not block reads: lexical retrieval works at once, semantic ranking catches up.
- An export (`POST /exports`) is a portable copy per caller and namespace, not a full backup: it leaves out tenants, principals, keys, grants, sessions, feedback and audit events.

## Configuration



+ 1042
- 0
app/controllers/ApiPortabilityController.asp
파일 크기가 너무 크기때문에 변경 상태를 표시하지 않습니다.
파일 보기


+ 1
- 0
app/controllers/autoload_controllers.asp 파일 보기

@@ -7,3 +7,4 @@
<!--#include file="ApiDocumentsController.asp" -->
<!--#include file="ApiContextController.asp" -->
<!--#include file="ApiLearningController.asp" -->
<!--#include file="ApiPortabilityController.asp" -->

+ 97
- 48
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


+ 1
- 0
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"


+ 220
- 224
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)


+ 4
- 0
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()


+ 284
- 0
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"
}
}
}
}
}
}
}
}
}

+ 286
- 0
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 <file> PRAGMA integrity_check, foreign_key_check, latest migration and row counts per table
' restore <file> verifies <file>, keeps the current database as db/backups/pre-restore-<ts>.sqlite, then copies
' <file> over the live database. Only with the HTTP server and embed worker STOPPED
' (scripts\restore.cmd does that); afterwards run scripts\embed.cmd reindex.
'
' File names are relative to the framework folder (for example db/backups/app-20261205-120000.sqlite) or absolute
' under /opt/axonasp/site. The framework folder must be the web root: -e SERVER_WEB_ROOT=/opt/axonasp/site
' Prints "RESULT: ok" or "RESULT: failed" as the last line (the CLI exit code is not reliable, see AGENTS.md).
%>
<!--#include file="../core/autoload_core.asp" -->
<%
Const BK_DIR = "/db/backups"
Const BK_LIVE = "/db/app.sqlite"
Const BK_SITE = "/opt/axonasp/site"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

+ 18
- 0
scripts/backup.cmd 파일 보기

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

+ 29
- 0
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-<timestamp>.sqlite and copies the backup over it
rem 4. starts the server and the worker again, then rebuilds the vector index from the restored data
rem (Qdrant is derived data and may hold vectors for rows the backup does not have)
rem If the restored schema is older than the code, run scripts\migrate.cmd up afterwards.
setlocal
if "%~1"=="" (
echo Usage: scripts\restore.cmd db/backups/^<file^>.sqlite
exit /b 1
)
docker compose stop axonasp embed-worker || exit /b 1
docker compose run --rm --no-deps -T -e SERVER_WEB_ROOT=/opt/axonasp/site -e BACKUP_ACTION=restore -e "BACKUP_FILE=%~1" axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp > "%TEMP%\amk-restore.log"
set RC=%errorlevel%
type "%TEMP%\amk-restore.log"
docker compose start axonasp embed-worker
findstr /b /c:"RESULT: ok" "%TEMP%\amk-restore.log" >nul
if errorlevel 1 (
echo Restore FAILED, see the messages above. If the backup did not verify, nothing was changed; if the copy
echo had started, the previous database is in db\backups\pre-restore-^<timestamp^>.sqlite.
exit /b 1
)
call "%~dp0embed.cmd" reindex
exit /b 0

+ 106
- 0
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 <action> [file] (in the live container)
docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site -e "BACKUP_ACTION=$1" -e "BACKUP_FILE=${2:-}" \
axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 | tr -d '\015'
}
iso_run() { # one-off container with the isolated db folder (what scripts/restore.cmd does, minus the live db)
docker run --rm -v "$REPO:/opt/axonasp/site" -v "$REPO/$ISO:/opt/axonasp/site/db" \
-e SERVER_WEB_ROOT=/opt/axonasp/site -e "BACKUP_ACTION=$1" -e "BACKUP_FILE=${2:-}" \
"$IMAGE" ./axonasp-cli -r /opt/axonasp/site/scripts/backup.asp 2>&1 | tr -d '\015'
}
field() { sed -n "s/.*$1: *\([^ ]*\).*/\1/p" | head -1; }
jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
last() { grep '^RESULT:' | tail -1; }
check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
data_of() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');print(json.dumps(json.load(sys.stdin)['data'],sort_keys=True))"; }
sha() { sha256sum "$1" | cut -c1-64; }
cleanup() {
docker rm -f "$ISO_NAME" >/dev/null 2>&1
[ -n "$TENANT" ] && prov purge "$TENANT" >/dev/null
rm -rf "$REPO/$ISO" "$REPO/$BK" "$REPO/$BK-damaged"
}
trap cleanup EXIT
cd "$REPO" || exit 2

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

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

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

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

+ 145
- 0
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 '<python using a[]>' args...
jq_() { python -I -c "import sys,json;sys.stdin.reconfigure(encoding='utf-8');d=json.load(sys.stdin);print($1)"; }
js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; }
remember() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5")${6:-}}" | jget id; }
# rememberj: like remember, but $5 is already a JSON string literal
rememberj() { body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$5}" | jget id; }
verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"verified\",\"method\":\"manual\",\"revision\":${3:-1}}" >/dev/null; }
# export <key> <file> [body]
export_() { curl -s -X POST -H "Authorization: Bearer $1" -d "${3:-{\}}" -o "$2" -w '%{http_code}' "$BASE/exports"; }
import_() { curl -s -X POST -H "Authorization: Bearer $1" --data-binary @"$2" -w '\n%{http_code}' "$BASE/imports"; }
digest_ok() { pyf "raw=open(a[0],'rb').read().decode('utf-8');d=json.loads(raw);i=raw.index('\"data\":')+7;j=raw.rindex(',\"counts\":');print(hashlib.sha256(raw[i:j].encode('utf-8')).hexdigest()==d['integrity']['digest'])" "$1"; }
mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }

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

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

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

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

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

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

불러오는 중...
취소
저장

Powered by TurnKey Linux.