diff --git a/AGENTS.md b/AGENTS.md index f28fb8e..811d65a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,6 +35,8 @@ When unsure about an object, ProgID, method or config key, check `/opt/axonasp/w - Controllers `ApiMemoriesController`, `ApiSessionsController`, `ApiHealthController` are hand-written (the generators cover one-table CRUD only); routes under `/api/v1/...` are in `public/Default.asp`. - Regression suite: `bash tests/phase1-api.sh` (needs the container running; creates and purges its own tenants; ends with a container restart). - Phase 2 (documents): `ApiDocumentsController` (ingestion/jobs, jobs, documents, chunks, search) plus `POST /recall` and `POST /memories/:id/verifications` in `ApiMemoriesController`; chunker and FTS5 indexing live in `core/lib.Search.asp`. Regression suite: `bash tests/phase2-api.sh`. OpenAPI: `public/api/memory-v1.openapi.json`. A caller without the needed namespace permission gets 404, never 403. +- Phase 3 (context): `ApiContextController` (`POST /context`) assembles a budgeted briefing. Constraints are loaded by scope (not similarity) and are required: if they do not fit `max_context_tokens` the answer is 422 `context_budget_exceeded`. Regression suite: `bash tests/phase3-context.sh`. +- The AxonASP image is pinned by digest in `docker-compose.yml`. To upgrade, change the digest deliberately, `docker compose up -d`, and rerun all three suites. ### Adding a table end to end (the workflow that was verified) @@ -164,7 +166,9 @@ Create objects with `Server.CreateObject("ProgID")` using exact ProgIDs from `/o - **Migrator: one migration per process.** `migrate.cmd up` with two or more pending migrations failed on the second one (`Runtime error: Migrator '800A0002'`; an AxonASP VM panic "assignment to entry in nil map" when reproduced in a plain script). Run `migrate.cmd up` once per pending migration. Even a successful apply/rollback currently ends with `Object required` from `core/helpers.asp` and exit code 1 (reproduced on the original unmodified framework, so not caused by local changes); check `migrate.cmd status` rather than the exit code. - **Close a result set before running another statement.** Running a query inside a loop over an open G3DB result set hung the request (script timeout), and a write executed while a result set was still open was silently lost (the `provision key` action created no key). Copy the values you need, `rs.Close`, then query/write. - **G3DB takes at most 8 parameters per statement** ("Too many parameters (12); the maximum is 8"). Split wide INSERTs into an INSERT plus an UPDATE inside one transaction (see `InsertRevision` in `ApiMemoriesController.asp`). -- **Non-BMP characters:** AxonASP strings hold whole code points. `ChrW(128512)` is one character; building it from a UTF-16 surrogate pair stores two U+FFFD. `Api_Utf8Decode` and `JsonLite` (for surrogate-pair `\u` escapes) combine accordingly. +- **Characters above U+FFFF (emoji) cannot be held** on the pinned build (CLI v2.3.42): `ChrW(128512)` raises "Invalid procedure call" (older builds returned one character), and `ChrW(55357) & ChrW(56832)` is written out as CESU-8 (`ED A0 BD ...`), which is invalid UTF-8. `Api_Utf8Decode` and JsonLite therefore flag such code points (raw 4-byte UTF-8 or escaped surrogate pairs) and `Api_ReadBody` answers 422 `unsupported_character`; the generator template does the same. Do not store them as U+FFFD silently. +- **`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. - **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 4217442..af8e5b8 100644 --- a/README.md +++ b/README.md @@ -56,17 +56,20 @@ Implements [Universal-Agent-Memory-Specification.md](Universal-Agent-Memory-Spec **Done** - Phase 1: tenants, principals, hashed API keys, namespaces, grants (read/write/delete/verify/admin); memories with revisions, correction (If-Match), retire/forget, idempotency keys, duplicate detection, audit events; sessions with checkpoints; health. - Phase 2: Markdown/text ingestion with chunking and source locators (`core/lib.Search.asp`), documents/chunks/jobs, lexical search over chunks (FTS5), `POST /recall` over memories, verification (`POST /memories/:id/verifications`), `content_trust` labelling. +- Phase 3 (part): `POST /context` assembles a task briefing under a token budget: constraints loaded by scope (required; 422 `context_budget_exceeded` when they do not fit), working state from a session checkpoint, preferences, disputed items as conflicts, decisions/lessons/knowledge and reference passages by lexical match, optional unverified items; deduplicated and trust-labelled. + +**Known limitation** +- Characters above U+FFFF (emoji) are rejected with 422 `unsupported_character`: the pinned AxonASP build cannot hold them (see AGENTS.md section 8). **Tooling** - `scripts\provision.cmd` (tenant, principal, key, namespace, grant, revoke, list, purge); see AGENTS.md section 1. Quote permission lists in PowerShell: `'"read,write"'`. - `scripts\export-memories.ps1` / `scripts/export-memories.sh`: dump every readable memory (set `AMK_KEY`). -- Tests (container must be running): `bash tests/phase1-api.sh` (71 checks), `bash tests/phase2-api.sh` (45 checks). Both create and purge their own tenants. +- Tests (container must be running): `bash tests/phase1-api.sh` (74 checks), `bash tests/phase2-api.sh` (45 checks), `bash tests/phase3-context.sh` (60 checks). Each creates and purges its own tenants. **Next (not started)** -1. Context assembly (`/context`): budgeted, deduplicated, trust-labelled bundle for an agent. -2. Embeddings and hybrid retrieval (needs a decision on the embedding provider). -3. Experiences, candidates and review; feedback (AC-18). -4. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). +1. Embeddings and hybrid retrieval. Decided: local Ollama container for embeddings and a vector store container (Qdrant) next to SQLite, behind a replaceable provider interface; lexical retrieval stays the fallback with a degradation warning. +2. Experiences, candidates and review; feedback (AC-18). +3. Import/export API, and management endpoints for namespaces, principals and grants (today only via `provision.cmd`). ## Configuration diff --git a/app/controllers/ApiContextController.asp b/app/controllers/ApiContextController.asp new file mode 100644 index 0000000..ad7933f --- /dev/null +++ b/app/controllers/ApiContextController.asp @@ -0,0 +1,807 @@ +<% +' ApiContextController: task briefing assembly (spec FR-010, section 9.3, section 10, AC-05, AC-16). +' Stateless JSON API, no layout. Helpers: core/lib.Api.asp (auth, errors), core/lib.Search.asp (FTS query). +' +' POST /api/v1/context +' {"task", "namespace_ids":[], "session_id", "include":["constraints","preferences","decisions","lessons","knowledge", +' "references","working_state"], "verification_filter":"verified_only|include_unverified", +' "detail_level":"full|summary", "max_context_tokens":100..32000, "max_items":1..50, "max_references":0..20, +' "format":"structured"} +' +' Assembly (all filtered to active, currently valid memories in namespaces the caller can read): +' constraints every constraint memory in scope, by importance: loaded by scope, not by similarity, and required. +' If they do not fit the budget the request fails with 422 context_budget_exceeded. +' working_state latest checkpoint of session_id (404 when the session is not visible) +' preferences every preference memory in scope, by importance +' conflicts disputed memories among the above and the task matches (always reported, labelled) +' decisions / lessons / knowledge lexical (FTS5/bm25) matches of the task, by type +' references lexical matches over current document chunks (untrusted reference content) +' unverified unverified matches, only with verification_filter include_unverified +' The budget is filled in that order; an item that does not fit is skipped and counted. Memories with identical +' content (same text, ignoring case and outer whitespace) appear once. Token counts are estimates (characters / 4) of the included text, not of +' the JSON envelope. Constraints are always returned in full, also with detail_level summary. +Const CTX_CONSTRAINTS = 0 +Const CTX_PREFERENCES = 1 +Const CTX_CONFLICTS = 2 +Const CTX_DECISIONS = 3 +Const CTX_LESSONS = 4 +Const CTX_KNOWLEDGE = 5 +Const CTX_REFERENCES = 6 +Const CTX_UNVERIFIED = 7 +Const CTX_SECTION_COUNT = 8 +Const CTX_MAX_POLICIES = 200 + +Class ApiContextController_Class + Private m_errs + ' candidates, in rank order within each section + Private m_cSec(), m_cJson(), m_cTok(), m_cN + Private m_seen, m_dupes, m_unverifiedExcluded, m_lastTok + + Public Property Get useLayout() + useLayout = False + End Property + + Public Property Let useLayout(v) + End Property + + Public Property Get Title() + Title = "Context API" + End Property + + '--------------------------------------------------------------- + ' POST /api/v1/context + '--------------------------------------------------------------- + Public Sub Assemble() + Dim body, input, task, fts, budget, maxItems, maxRefs, detail, vf, fmt, requested, allowed, sessionId + Dim incPrefs, incDecisions, incLessons, incKnowledge, incRefs, incState + Dim rs, sql, now_, i, j, n, ids(), scores(), idList, sec, json, warnings, complete + Dim stateJson, stateTok, sessNs, sessStatus, sessObjective, curRev, savedAt + Dim used, requiredTok, policyCount, truncated, omittedBudget, omittedLimit, cap + Dim outSec(), cnt(), out, refSeen, txt, policiesCapped + + If Not Api_Authenticate() Then Exit Sub + body = Api_ReadBody() + If IsEmpty(body) Then Exit Sub + Set input = JsonLite_Parse(body) + + '--- validation ----------------------------------------------- + m_errs = "" + task = ReqString(input, "task", 2000) + budget = OptInt(input, "max_context_tokens", 4000, 100, 32000) + maxItems = OptInt(input, "max_items", 10, 1, 50) + maxRefs = OptInt(input, "max_references", 5, 0, 20) + detail = LCase("" & OptStringDefault(input, "detail_level", 20, "full")) + If detail <> "full" And detail <> "summary" Then + AddErr "detail_level must be full or summary." + End If + vf = LCase("" & OptStringDefault(input, "verification_filter", 30, "verified_only")) + If vf <> "verified_only" And vf <> "include_unverified" Then + AddErr "verification_filter must be verified_only or include_unverified." + End If + fmt = LCase("" & OptStringDefault(input, "format", 20, "structured")) + If fmt <> "structured" Then + AddErr "format must be structured." + End If + sessionId = OptStringDefault(input, "session_id", 64, "") + If Len(sessionId) > 0 Then + If Not Api_IsId(sessionId) Then + AddErr "session_id must be a valid id." + End If + End If + requested = IdListSql(input, "namespace_ids") + + incPrefs = True + incDecisions = True + incLessons = True + incKnowledge = True + incRefs = True + incState = True + If input.HasRaw("include") Then + Dim incArr, inc + incArr = JsonLite_ParseStringArray(input.Raw("include")) + If IsNull(incArr) Then + AddErr "include must be an array of section names." + Else + incPrefs = False + incDecisions = False + incLessons = False + incKnowledge = False + incRefs = False + incState = False + For i = 0 To UBound(incArr) + inc = LCase(Trim(incArr(i))) + Select Case inc + Case "constraints" + ' always included + Case "preferences" + incPrefs = True + Case "decisions" + incDecisions = True + Case "lessons" + incLessons = True + Case "knowledge" + incKnowledge = True + Case "references" + incRefs = True + Case "working_state" + incState = True + Case Else + AddErr "include contains an unknown section: " & Left(inc, 40) & "." + End Select + Next + End If + ElseIf input.Exists("include") Then + If Not IsNull(input.Item("include")) Then + AddErr "include must be an array of section names." + End If + End If + If Len(m_errs) > 0 Then + Api_Invalid Split(m_errs, Chr(30)) + Exit Sub + End If + + fts = Search_FtsQuery(task) + If Len(fts) = 0 Then + Api_Invalid Array("task must contain at least one word.") + Exit Sub + End If + + '--- session (checked before any retrieval: an invisible session is a 404) --- + stateJson = "null" + stateTok = 0 + If Len(sessionId) > 0 Then + Set rs = DAL().Query("SELECT namespace_id, status, objective FROM sessions WHERE id = ? AND tenant_id = ?", Array(sessionId, Api_TenantId)) + If rs.EOF Then + rs.Close + Api_Error 404, "session_not_found", "Session not found." + Exit Sub + End If + sessNs = "" & rs(0) + sessStatus = "" & rs(1) + sessObjective = "" & rs(2) + rs.Close + If Not Api_CanAccessNamespace(sessNs, "read") Then + Api_Error 404, "session_not_found", "Session not found." + Exit Sub + End If + If incState Then + curRev = 0 + Set rs = DAL().Query("SELECT MAX(revision) FROM checkpoints WHERE session_id = ?", sessionId) + If Not rs.EOF Then + If Not IsNull(rs(0)) Then + curRev = CLng(rs(0)) + End If + End If + rs.Close + txt = "null" + savedAt = "null" + If curRev > 0 Then + Set rs = DAL().Query("SELECT state, created_at FROM checkpoints WHERE session_id = ? AND revision = ?", Array(sessionId, curRev)) + If Not rs.EOF Then + txt = "" & rs(0) + savedAt = JsonLite_Quote("" & rs(1)) + End If + rs.Close + End If + stateTok = Tokens(sessObjective & vbLf & txt) + stateJson = "{""session_id"":" & JsonLite_Quote(sessionId) & ",""status"":" & JsonLite_Quote(sessStatus) & _ + ",""objective"":" & JsonLite_Quote(sessObjective) & ",""revision"":" & curRev & ",""state"":" & txt & _ + ",""saved_at"":" & savedAt & ",""token_estimate"":" & stateTok & "}" + End If + End If + + allowed = Api_AllowedNamespaceIds("read") + If Len(allowed) > 0 And Len(requested) > 0 Then + allowed = IntersectIds(allowed, requested) + End If + + m_cN = 0 + ReDim m_cSec(31) + ReDim m_cJson(31) + ReDim m_cTok(31) + m_seen = Chr(31) + m_dupes = 0 + m_unverifiedExcluded = 0 + policiesCapped = False + now_ = Api_Now() + + If Len(allowed) > 0 Then + '--- 1. policies: constraints and preferences, by scope ------------------ + sql = CtxMemorySelect() & " WHERE m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ + "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _ + "AND r.verification_status <> 'rejected' AND m.type IN ('constraint','preference') " & _ + "ORDER BY CASE m.type WHEN 'constraint' THEN 0 ELSE 1 END, COALESCE(r.importance, 0) DESC, m.updated_at DESC LIMIT " & (CTX_MAX_POLICIES + 1) + Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_)) + policyCount = 0 + Do While Not rs.EOF + policyCount = policyCount + 1 + If policyCount > CTX_MAX_POLICIES Then + policiesCapped = True + Exit Do + End If + If "" & rs(2) = "constraint" Then + AddMemory rs, CTX_CONSTRAINTS, vf, "full", 0 + ElseIf incPrefs Then + AddMemory rs, CTX_PREFERENCES, vf, detail, 0 + End If + rs.MoveNext + Loop + rs.Close + + '--- 2. lexical memory matches --------------------------------------------- + If incDecisions Or incLessons Or incKnowledge Then + Set rs = DAL().Query("SELECT memory_id, bm25(memories_fts) FROM memories_fts WHERE memories_fts MATCH ? AND tenant_id = ? ORDER BY bm25(memories_fts) LIMIT 300", Array(fts, Api_TenantId)) + n = 0 + ReDim ids(63) + ReDim scores(63) + Do While Not rs.EOF + If n > UBound(ids) Then + ReDim Preserve ids(n * 2) + ReDim Preserve scores(n * 2) + End If + ids(n) = "" & rs(0) + scores(n) = rs(1) + n = n + 1 + rs.MoveNext + Loop + rs.Close + idList = IdSqlList(ids, n) + If Len(idList) > 0 Then + ' Read the canonical rows (closing the result set), then add them in bm25 order. + sql = CtxMemorySelect() & " WHERE m.id IN (" & idList & ") AND m.tenant_id = ? AND m.namespace_id IN (" & allowed & ") AND m.lifecycle_status = 'active' " & _ + "AND (m.valid_from IS NULL OR m.valid_from <= ?) AND (m.valid_until IS NULL OR m.valid_until > ?) " & _ + "AND r.verification_status <> 'rejected' AND m.type NOT IN ('constraint','preference','working')" + Set rs = DAL().Query(sql, Array(Api_TenantId, now_, now_)) + Dim rowsTmp + rowsTmp = Empty + If Not rs.EOF Then + rowsTmp = rs.GetRows() + End If + rs.Close + If Not IsEmpty(rowsTmp) Then + ' GetRows is (column, row); walk the ranks and pick the matching row + For i = 0 To n - 1 + For j = 0 To UBound(rowsTmp, 2) + If "" & rowsTmp(0, j) = ids(i) Then + sec = TypeSection("" & rowsTmp(2, j)) + If sec = CTX_DECISIONS And Not incDecisions Then + sec = -1 + ElseIf sec = CTX_LESSONS And Not incLessons Then + sec = -1 + ElseIf sec = CTX_KNOWLEDGE And Not incKnowledge Then + sec = -1 + End If + If sec >= 0 Then + AddMemoryRow rowsTmp, j, sec, vf, detail, -CDbl(scores(i)) + End If + Exit For + End If + Next + Next + End If + End If + End If + + '--- 3. reference passages ------------------------------------------------ + If incRefs And maxRefs > 0 Then + Set rs = DAL().Query("SELECT chunk_id, bm25(chunks_fts) FROM chunks_fts WHERE chunks_fts MATCH ? AND tenant_id = ? ORDER BY bm25(chunks_fts) LIMIT 300", Array(fts, Api_TenantId)) + n = 0 + ReDim ids(63) + ReDim scores(63) + Do While Not rs.EOF + If n > UBound(ids) Then + ReDim Preserve ids(n * 2) + ReDim Preserve scores(n * 2) + End If + ids(n) = "" & rs(0) + scores(n) = rs(1) + n = n + 1 + rs.MoveNext + Loop + rs.Close + idList = IdSqlList(ids, n) + If Len(idList) > 0 Then + Dim chunkRows + chunkRows = Empty + sql = "SELECT c.id, c.document_id, c.document_revision, c.ordinal, c.content, c.heading_path, c.start_offset, c.end_offset, d.namespace_id, d.title, d.source_uri " & _ + "FROM chunks c JOIN documents d ON d.id = c.document_id WHERE c.id IN (" & idList & ") AND d.tenant_id = ? AND d.namespace_id IN (" & allowed & ") " & _ + "AND c.document_revision = d.current_revision" + Set rs = DAL().Query(sql, Api_TenantId) + If Not rs.EOF Then + chunkRows = rs.GetRows() + End If + rs.Close + If Not IsEmpty(chunkRows) Then + refSeen = Chr(31) + cap = 0 + For i = 0 To n - 1 + If cap >= maxRefs Then + Exit For + End If + For j = 0 To UBound(chunkRows, 2) + If "" & chunkRows(0, j) = ids(i) Then + txt = "" & chunkRows(4, j) + If InStr(refSeen, Chr(31) & txt & Chr(31)) > 0 Then + m_dupes = m_dupes + 1 + Else + refSeen = refSeen & txt & Chr(31) + json = RefJson(chunkRows, j, detail, -CDbl(scores(i))) + AddCand CTX_REFERENCES, json, m_lastTok + cap = cap + 1 + End If + Exit For + End If + Next + Next + End If + End If + End If + End If + + '--- budget --------------------------------------------------------------------- + requiredTok = 0 + For i = 0 To m_cN - 1 + If m_cSec(i) = CTX_CONSTRAINTS Then + requiredTok = requiredTok + m_cTok(i) + End If + Next + If requiredTok > budget Then + Api_Audit "context.assemble", "context", "", "budget_exceeded" + Api_Send 422, "{""error"":{""code"":""context_budget_exceeded"",""message"":" & _ + JsonLite_Quote("The applicable constraints need about " & requiredTok & " tokens, more than max_context_tokens (" & budget & "). Raise the budget or narrow namespace_ids.") & _ + ",""required_tokens"":" & requiredTok & ",""max_context_tokens"":" & budget & ",""request_id"":" & JsonLite_Quote(Api_RequestId()) & "}}" + Exit Sub + End If + + ReDim outSec(CTX_SECTION_COUNT - 1) + ReDim cnt(CTX_SECTION_COUNT - 1) + For i = 0 To CTX_SECTION_COUNT - 1 + outSec(i) = "" + cnt(i) = 0 + Next + used = requiredTok + omittedBudget = 0 + omittedLimit = 0 + For i = 0 To m_cN - 1 + If m_cSec(i) = CTX_CONSTRAINTS Then + AppendTo outSec, cnt, CTX_CONSTRAINTS, m_cJson(i) + End If + Next + + warnings = "" + If stateTok > 0 Then + If used + stateTok <= budget Then + used = used + stateTok + Else + stateJson = "null" + omittedBudget = omittedBudget + 1 + AddWarning warnings, "working_state did not fit the budget and was left out; restore it with GET /sessions/{id}/state" + End If + End If + + For sec = CTX_PREFERENCES To CTX_SECTION_COUNT - 1 + If sec = CTX_PREFERENCES Then + cap = 50 + ElseIf sec = CTX_REFERENCES Then + cap = maxRefs + Else + cap = maxItems + End If + For i = 0 To m_cN - 1 + If m_cSec(i) = sec Then + If cnt(sec) >= cap Then + omittedLimit = omittedLimit + 1 + ElseIf used + m_cTok(i) > budget Then + omittedBudget = omittedBudget + 1 + Else + used = used + m_cTok(i) + AppendTo outSec, cnt, sec, m_cJson(i) + End If + End If + Next + Next + + complete = True + If policiesCapped Then + complete = False + AddWarning warnings, "more than " & CTX_MAX_POLICIES & " constraint/preference memories are in scope; only the most important were considered, so the briefing is incomplete. Narrow namespace_ids." + End If + truncated = (omittedBudget > 0) + If omittedBudget > 0 Then + AddWarning warnings, omittedBudget & " item(s) left out to fit max_context_tokens" + End If + If m_unverifiedExcluded > 0 Then + AddWarning warnings, m_unverifiedExcluded & " unverified item(s) excluded; use verification_filter include_unverified to see them" + End If + If cnt(CTX_CONFLICTS) > 0 Then + AddWarning warnings, cnt(CTX_CONFLICTS) & " disputed item(s) included under conflicts; do not rely on them without checking" + End If + If Len(allowed) = 0 Then + AddWarning warnings, "the caller cannot read any namespace in scope; the briefing is empty" + End If + AddWarning warnings, "semantic retrieval is not configured; matches are lexical only" + + out = "{""context_id"":" & JsonLite_Quote("ctx-" & Api_NewId()) & ",""task"":" & JsonLite_Quote(task) & _ + ",""strategy"":""lexical"",""format"":""structured"",""verification_filter"":" & JsonLite_Quote(vf) & ",""detail_level"":" & JsonLite_Quote(detail) & _ + ",""budget"":{""max_context_tokens"":" & budget & ",""used_tokens"":" & used & ",""counting_method"":""estimate_chars_div_4""" & _ + ",""complete"":" & LCase(CStr(complete)) & ",""truncated"":" & LCase(CStr(truncated)) & "}" & _ + ",""omitted"":{""over_budget"":" & omittedBudget & ",""over_limit"":" & omittedLimit & ",""duplicates"":" & m_dupes & ",""unverified_excluded"":" & m_unverifiedExcluded & "}" + out = out & ",""constraints"":[" & outSec(CTX_CONSTRAINTS) & "]" + If incState Then + out = out & ",""working_state"":" & stateJson + End If + If incPrefs Then + out = out & ",""preferences"":[" & outSec(CTX_PREFERENCES) & "]" + End If + out = out & ",""conflicts"":[" & outSec(CTX_CONFLICTS) & "]" + If incDecisions Then + out = out & ",""decisions"":[" & outSec(CTX_DECISIONS) & "]" + End If + If incLessons Then + out = out & ",""lessons"":[" & outSec(CTX_LESSONS) & "]" + End If + If incKnowledge Then + out = out & ",""knowledge"":[" & outSec(CTX_KNOWLEDGE) & "]" + End If + If incRefs Then + out = out & ",""references"":[" & outSec(CTX_REFERENCES) & "]" + End If + If vf = "include_unverified" Then + out = out & ",""unverified"":[" & outSec(CTX_UNVERIFIED) & "]" + End If + out = out & ",""warnings"":[" & warnings & "]}" + + Api_Audit "context.assemble", "context", "", "ok" + Api_Send 200, out + End Sub + + '=============================================================== + ' Helpers + '=============================================================== + ' Columns relied on by AddMemory / AddMemoryRow: + ' 0 id, 1 namespace_id, 2 type, 3 revision, 4 title, 5 summary, 6 content, 7 tags, 8 confidence, 9 importance, + ' 10 verification_status, 11 content_hash, 12 creator, 13 updated_at, 14 valid_until + Private Function CtxMemorySelect() + CtxMemorySelect = "SELECT m.id, m.namespace_id, m.type, r.revision, r.title, r.summary, r.content, r.tags, r.confidence, r.importance, " & _ + "r.verification_status, r.content_hash, m.creator_principal_id, m.updated_at, m.valid_until " & _ + "FROM memories m JOIN memory_revisions r ON r.memory_id = m.id AND r.revision = m.current_revision" + End Function + + Private Function TypeSection(t) + Select Case t + Case "decision" + TypeSection = CTX_DECISIONS + Case "lesson" + TypeSection = CTX_LESSONS + Case Else + TypeSection = CTX_KNOWLEDGE + End Select + End Function + + ' Copies one result-set row into an array and hands it to AddMemoryRow (single code path for both sources). + Private Sub AddMemory(rs, sec, vf, detail, score) + Dim row(14, 0), k + For k = 0 To 14 + row(k, 0) = rs(k) + Next + AddMemoryRow row, 0, sec, vf, detail, score + End Sub + + ' rows is GetRows-shaped (column, row). Sorts the memory into its section by verification state and dedupes by content. + Private Sub AddMemoryRow(rows, j, sec, vf, detail, score) + Dim st, key, json, target + st = "" & rows(10, j) + target = sec + If st = "disputed" Then + target = CTX_CONFLICTS + ElseIf st <> "verified" Then + If vf = "include_unverified" Then + target = CTX_UNVERIFIED + Else + m_unverifiedExcluded = m_unverifiedExcluded + 1 + Exit Sub + End If + End If + ' The stored content_hash also covers namespace, type and title, so the same text in two namespaces has two + ' hashes. Dedupe on the normalized content instead. + key = LCase(Trim("" & rows(6, j))) + If InStr(m_seen, Chr(31) & key & Chr(31)) > 0 Then + m_dupes = m_dupes + 1 + Exit Sub + End If + m_seen = m_seen & key & Chr(31) + json = MemJson(rows, j, detail, score, st, (sec = CTX_CONSTRAINTS)) + AddCand target, json, m_lastTok + End Sub + + Private Function MemJson(rows, j, detail, score, st, isPolicy) + Dim s, bodyText, trust + If detail = "summary" Then + If IsNull(rows(5, j)) Then + bodyText = "" & rows(6, j) + If Len(bodyText) > 240 Then + bodyText = Left(bodyText, 240) & "..." + End If + Else + bodyText = "" & rows(5, j) + End If + Else + bodyText = "" & rows(6, j) + End If + m_lastTok = Tokens("" & rows(4, j) & vbLf & bodyText) + Select Case st + Case "verified" + trust = "verified_memory" + Case "disputed" + trust = "disputed_memory" + Case Else + trust = "unverified_memory" + End Select + s = "{""id"":" & JsonLite_Quote("" & rows(0, j)) & ",""revision"":" & CLng(rows(3, j)) & ",""type"":" & JsonLite_Quote("" & rows(2, j)) & _ + ",""namespace_id"":" & JsonLite_Quote("" & rows(1, j)) & ",""title"":" & JsonLite_Quote("" & rows(4, j)) + If detail = "summary" Then + s = s & ",""summary"":" & JsonLite_Quote(bodyText) + Else + s = s & ",""content"":" & JsonLite_Quote(bodyText) + End If + s = s & ",""verification_status"":" & JsonLite_Quote(st) & ",""content_trust"":" & JsonLite_Quote(trust) + If isPolicy Then + If st = "verified" Then + s = s & ",""authority"":""policy""" + End If + End If + s = s & ",""tags"":" & JRaw(rows(7, j), "[]") & ",""confidence"":" & JNum(rows(8, j)) & ",""importance"":" & JNum(rows(9, j)) + If score <> 0 Then + s = s & ",""relevance_score"":" & JsonLite_Num(score) + End If + s = s & ",""valid_until"":" & JStr(rows(14, j)) & ",""provenance"":{""created_by"":" & JsonLite_Quote("" & rows(12, j)) & _ + ",""updated_at"":" & JsonLite_Quote("" & rows(13, j)) & "},""token_estimate"":" & m_lastTok & "}" + MemJson = s + End Function + + ' Chunk row columns: 0 id, 1 document id, 2 document revision, 3 ordinal, 4 content, 5 heading path, 6 start, 7 end, + ' 8 namespace id, 9 title, 10 source uri + Private Function RefJson(rows, j, detail, score) + Dim txt, s + txt = "" & rows(4, j) + If detail = "summary" Then + If Len(txt) > 240 Then + txt = Left(txt, 240) & "..." + End If + End If + m_lastTok = Tokens(txt) + s = "{""chunk_id"":" & JsonLite_Quote("" & rows(0, j)) & ",""document_id"":" & JsonLite_Quote("" & rows(1, j)) & _ + ",""document_title"":" & JsonLite_Quote("" & rows(9, j)) & ",""source_uri"":" & JStr(rows(10, j)) & _ + ",""document_revision"":" & CLng(rows(2, j)) & ",""ordinal"":" & CLng(rows(3, j)) & ",""heading_path"":" & JStr(rows(5, j)) & _ + ",""locator"":{""start"":" & CLng(rows(6, j)) & ",""end"":" & CLng(rows(7, j)) & "},""namespace_id"":" & JsonLite_Quote("" & rows(8, j)) & _ + ",""relevance_score"":" & JsonLite_Num(score) & ",""content"":" & JsonLite_Quote(txt) & _ + ",""content_trust"":""untrusted_reference"",""token_estimate"":" & m_lastTok & "}" + RefJson = s + End Function + + Private Sub AddCand(sec, json, tok) + If m_cN > UBound(m_cSec) Then + ReDim Preserve m_cSec(m_cN * 2) + ReDim Preserve m_cJson(m_cN * 2) + ReDim Preserve m_cTok(m_cN * 2) + End If + m_cSec(m_cN) = sec + m_cJson(m_cN) = json + m_cTok(m_cN) = tok + m_cN = m_cN + 1 + End Sub + + Private Sub AppendTo(outSec, cnt, sec, json) + If cnt(sec) > 0 Then + outSec(sec) = outSec(sec) & "," + End If + outSec(sec) = outSec(sec) & json + cnt(sec) = cnt(sec) + 1 + End Sub + + Private Sub AddWarning(warnings, text) + If Len(warnings) > 0 Then + warnings = warnings & "," + End If + warnings = warnings & JsonLite_Quote(text) + End Sub + + ' Token estimate for included text: characters / 4, rounded up (declared as estimate_chars_div_4) + Private Function Tokens(text) + Tokens = Int((Len(text) + 3) / 4) + End Function + + ' 'id1','id2' for the first n valid ids + Private Function IdSqlList(ids, n) + Dim i, out + out = "" + For i = 0 To n - 1 + If Api_IsId(ids(i)) Then + If Len(out) > 0 Then + out = out & "," + End If + out = out & "'" & ids(i) & "'" + End If + Next + IdSqlList = out + End Function + + Private Function JStr(v) + If IsNull(v) Then + JStr = "null" + Else + JStr = JsonLite_Quote("" & v) + End If + End Function + + Private Function JNum(v) + If IsNull(v) Then + JNum = "null" + ElseIf Len("" & v) = 0 Then + JNum = "null" + Else + JNum = JsonLite_Num(v) + End If + End Function + + Private Function JRaw(v, dflt) + If IsNull(v) Then + JRaw = dflt + ElseIf Len("" & v) = 0 Then + JRaw = dflt + Else + JRaw = "" & v + End If + End Function + + Private Sub AddErr(msg) + If Len(m_errs) > 0 Then + m_errs = m_errs & Chr(30) + End If + m_errs = m_errs & msg + End Sub + + Private Function ReqString(input, name, maxLen) + Dim v + ReqString = "" + If Not input.Exists(name) Then + AddErr name & " is required." + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + AddErr name & " is required." + Exit Function + End If + If VarType(v) <> vbString Then + AddErr name & " must be a string." + Exit Function + End If + v = Trim(v) + If Len(v) = 0 Then + AddErr name & " must not be empty." + Exit Function + End If + If Len(v) > maxLen Then + AddErr name & " must be at most " & maxLen & " characters." + Exit Function + End If + ReqString = v + End Function + + ' Optional string with a default when absent or null + Private Function OptStringDefault(input, name, maxLen, dflt) + Dim v + OptStringDefault = dflt + If Not input.Exists(name) Then + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + Exit Function + End If + If VarType(v) <> vbString Then + AddErr name & " must be a string." + Exit Function + End If + If Len(v) > maxLen Then + AddErr name & " must be at most " & maxLen & " characters." + Exit Function + End If + OptStringDefault = v + End Function + + ' Optional whole number in lo..hi with a default when absent or null + Private Function OptInt(input, name, dflt, lo, hi) + Dim v + OptInt = dflt + If Not input.Exists(name) Then + Exit Function + End If + v = input.Item(name) + If IsNull(v) Then + Exit Function + End If + If VarType(v) <> vbDouble Then + AddErr name & " must be a number." + Exit Function + End If + If v <> Int(v) Or v < lo Or v > hi Then + AddErr name & " must be a whole number between " & lo & " and " & hi & "." + Exit Function + End If + OptInt = CLng(v) + End Function + + Private Function IdListSql(input, name) + Dim arr, i, out + IdListSql = "" + If Not input.HasRaw(name) Then + If input.Exists(name) Then + If Not IsNull(input.Item(name)) Then + AddErr name & " must be an array of ids." + End If + End If + Exit Function + End If + arr = JsonLite_ParseStringArray(input.Raw(name)) + If IsNull(arr) Then + AddErr name & " must be an array of ids." + Exit Function + End If + out = "" + For i = 0 To UBound(arr) + If Not Api_IsId(arr(i)) Then + AddErr name & " must contain valid ids." + Exit Function + End If + If Len(out) > 0 Then + out = out & "," + End If + out = out & "'" & arr(i) & "'" + Next + If Len(out) = 0 Then + AddErr name & " must not be empty when given." + End If + IdListSql = out + End Function + + Private Function IntersectIds(allowed, requested) + Dim a, i, out + a = Split(allowed, ",") + out = "" + For i = 0 To UBound(a) + If InStr("," & requested & ",", "," & a(i) & ",") > 0 Then + If Len(out) > 0 Then + out = out & "," + End If + out = out & a(i) + End If + Next + IntersectIds = out + End Function + + ' Static action dispatch (AxonASP mishandles runtime-built Eval/Execute calls and shared call sites) + Public Sub Invoke(actionName, args) + Select Case LCase(actionName) + Case "assemble" : Assemble + Case Else + Err.Raise 438, "ApiContextController_Class", "Action '" & actionName & "' not found" + End Select + End Sub + +End Class + +Dim ApiContextController_Class__Singleton +Function ApiContextController() + If IsEmpty(ApiContextController_Class__Singleton) Then + Set ApiContextController_Class__Singleton = New ApiContextController_Class + End If + Set ApiContextController = ApiContextController_Class__Singleton +End Function + +' Global entry point used by MVC_InvokeAction via GetRef (one call site per controller) +Sub ApiContextController_Invoke(actionName, args) + ApiContextController().Invoke actionName, args +End Sub +%> diff --git a/app/controllers/autoload_controllers.asp b/app/controllers/autoload_controllers.asp index d9ca2b9..bcf45c1 100644 --- a/app/controllers/autoload_controllers.asp +++ b/app/controllers/autoload_controllers.asp @@ -5,3 +5,4 @@ + diff --git a/core/lib.Api.asp b/core/lib.Api.asp index ee760d4..4f1dc09 100644 --- a/core/lib.Api.asp +++ b/core/lib.Api.asp @@ -144,14 +144,23 @@ Function Api_ReadBody() Api_Error 400, "body_too_large", "Request body exceeds 1 MiB." Exit Function End If + Api_Utf8Unsupported = False text = Api_Utf8Decode(CStr(Request.BinaryRead(n))) If JsonLite_Parse(text) Is Nothing Then Api_Error 400, "invalid_json", "Body must be a valid JSON object." Exit Function End If + ' Reject rather than store damaged text (see Api_Utf8Decode) + If Api_Utf8Unsupported Or JsonLite_SurrogateSeen Then + Api_Error 422, "unsupported_character", "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them." + Exit Function + End If Api_ReadBody = 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. Function Api_Utf8Decode(ByVal s) Dim i, n, c, cp, extra, out, k, ok, b @@ -188,9 +197,15 @@ Function Api_Utf8Decode(ByVal s) Next End If If ok And cp <= 1114111 Then - ' AxonASP strings hold whole code points: ChrW(cp) works above U+FFFF, while a UTF-16 - ' surrogate pair would be stored as two U+FFFD characters. - out = out & ChrW(cp) + ' 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) + Else + out = out & ChrW(cp) + End If i = i + extra + 1 Else out = out & ChrW(65533) diff --git a/core/lib.ControllerRegistry.asp b/core/lib.ControllerRegistry.asp index 9ed25d6..180f852 100644 --- a/core/lib.ControllerRegistry.asp +++ b/core/lib.ControllerRegistry.asp @@ -15,6 +15,7 @@ Class ControllerRegistry_Class ' Format: m_controllers.Add "controllername", True RegisterController "homecontroller" RegisterController "errorcontroller" + RegisterController "apicontextcontroller" RegisterController "apidocumentscontroller" RegisterController "apihealthcontroller" RegisterController "apisessionscontroller" diff --git a/core/lib.JsonLite.asp b/core/lib.JsonLite.asp index 56c2312..0a68baf 100644 --- a/core/lib.JsonLite.asp +++ b/core/lib.JsonLite.asp @@ -10,6 +10,11 @@ ' obj.Exists("Name"), obj.Item("Name") ' JsonLite_Quote(s) ' "text" with JSON escaping ' JsonLite_Num(n) ' locale-independent number literal +' JsonLite_SurrogateSeen ' True after JsonLite_Parse met a backslash-u escape for a UTF-16 surrogate +' +' 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. @@ -101,10 +106,15 @@ Class JsonLite_Object End Class Class JsonLite_Parser - Private m_s, m_pos, m_len, m_ok + Private m_s, m_pos, m_len, m_ok, m_sur + + Public Property Get SurrogateSeen() + SurrogateSeen = (m_sur = True) + End Property Public Function Run(text) Dim obj + m_sur = False m_s = "" & text m_len = Len(m_s) m_pos = 1 @@ -345,18 +355,29 @@ Class JsonLite_Parser Exit Function End If cu = CLng("&H" & h) + ' "&H8000".."&HFFFF" are read as signed 16-bit (e.g. D83D -> -10179) + 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; AxonASP strings need it combined. + ' 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 - cu = 65536 + (cu - 55296) * 1024 + (lo - 56320) m_pos = m_pos + 6 End If End If End If + If cu >= 55296 And cu <= 57343 Then + m_sur = True + cu = 65533 + End If out = out & ChrW(cu) Case Else m_ok = False @@ -389,10 +410,14 @@ Function JsonLite_ParseStringArray(text) JsonLite_ParseStringArray = p.RunStringArray(text) End Function +Dim JsonLite_SurrogateSeen +JsonLite_SurrogateSeen = False + Function JsonLite_Parse(text) Dim p Set p = New JsonLite_Parser Set JsonLite_Parse = p.Run(text) + JsonLite_SurrogateSeen = p.SurrogateSeen End Function ' "text" with JSON escaping (non-ASCII is left as is; the response is UTF-8) diff --git a/docker-compose.yml b/docker-compose.yml index 97190f7..008da56 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,6 +1,8 @@ services: axonasp: - image: ghcr.io/guimaraeslucas/axonasp:latest + # Pinned (AxonASP v2.3.42, tested with tests/*.sh). ":latest" changed behaviour under us once + # (ChrW above U+FFFF started to fail); bump the digest deliberately and rerun the suites. + image: ghcr.io/guimaraeslucas/axonasp@sha256:39f582e2fcdb067d0141f94896e30bbe414e6c79db274077c653b543d519a741 container_name: axonasp ports: - "8801:8801" diff --git a/public/Default.asp b/public/Default.asp index d9e885a..ce3ddd2 100644 --- a/public/Default.asp +++ b/public/Default.asp @@ -38,6 +38,9 @@ router.AddRoute "GET", "/api/v1/chunks/:id", "ApiDocumentsController", "Chunk" router.AddRoute "POST", "/api/v1/search", "ApiDocumentsController", "Search" + ' Context assembly (Phase 3) + router.AddRoute "POST", "/api/v1/context", "ApiContextController", "Assemble" + ' 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 0dbbea7..26db83a 100644 --- a/public/api/memory-v1.openapi.json +++ b/public/api/memory-v1.openapi.json @@ -2,8 +2,8 @@ "openapi": "3.0.3", "info": { "title": "Agent Memory API", - "version": "1.0.0-phase2", - "description": "Universal AI Agent Memory platform, phases 1-2: memories with revisions and verification, sessions with checkpoints, Markdown/text document ingestion with chunk locators, lexical search and recall, health. Authenticate with `Authorization: Bearer `; the tenant is derived from the key. Anything the caller cannot see is reported as 404." + "version": "1.0.0-phase3", + "description": "Universal AI Agent Memory platform, phases 1-3: memories with revisions and verification, sessions with checkpoints, Markdown/text document ingestion with chunk locators, lexical search and recall, health. Authenticate with `Authorization: Bearer `; the tenant is derived from the key. Anything the caller cannot see is reported as 404. Phase 3: POST /context assembles a budgeted task briefing." }, "servers": [ { @@ -408,6 +408,217 @@ "type": "integer" } } + }, + "ContextRequest": { + "type": "object", + "required": [ + "task" + ], + "properties": { + "task": { + "type": "string", + "maxLength": 2000, + "description": "What the agent is about to do; used as the lexical query for decisions, lessons, knowledge and references." + }, + "namespace_ids": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Restrict to these namespaces (intersected with what the caller can read)." + }, + "session_id": { + "type": "string", + "description": "Include the session's latest checkpoint as working_state. 404 when the session is not visible." + }, + "include": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "constraints", + "preferences", + "decisions", + "lessons", + "knowledge", + "references", + "working_state" + ] + }, + "description": "Sections to assemble (default all). Constraints and conflicts are always included." + }, + "verification_filter": { + "type": "string", + "enum": [ + "verified_only", + "include_unverified" + ], + "default": "verified_only" + }, + "detail_level": { + "type": "string", + "enum": [ + "full", + "summary" + ], + "default": "full", + "description": "summary returns the stored summary (or first 240 characters); constraints are always full." + }, + "max_context_tokens": { + "type": "integer", + "minimum": 100, + "maximum": 32000, + "default": 4000 + }, + "max_items": { + "type": "integer", + "minimum": 1, + "maximum": 50, + "default": 10, + "description": "Per-section cap for conflicts, decisions, lessons, knowledge and unverified (preferences: 50)." + }, + "max_references": { + "type": "integer", + "minimum": 0, + "maximum": 20, + "default": 5 + }, + "format": { + "type": "string", + "enum": [ + "structured" + ], + "default": "structured" + } + }, + "example": { + "task": "Implement a customer repository", + "session_id": "", + "include": [ + "constraints", + "decisions", + "preferences", + "lessons", + "references", + "working_state" + ], + "max_context_tokens": 4000 + } + }, + "ContextResponse": { + "type": "object", + "description": "Sections in budget priority order: constraints (required), working_state, preferences, conflicts, decisions, lessons, knowledge, references, unverified. Memory items carry id, revision, type, namespace_id, title, content|summary, verification_status, content_trust (verified_memory|unverified_memory|disputed_memory), authority (policy for verified constraints), tags, confidence, importance, relevance_score (lexical matches), valid_until, provenance {created_by, updated_at} and token_estimate. References carry chunk/document ids, locator, content and content_trust untrusted_reference.", + "properties": { + "context_id": { + "type": "string" + }, + "task": { + "type": "string" + }, + "strategy": { + "type": "string", + "example": "lexical" + }, + "budget": { + "type": "object", + "properties": { + "max_context_tokens": { + "type": "integer" + }, + "used_tokens": { + "type": "integer" + }, + "counting_method": { + "type": "string", + "example": "estimate_chars_div_4" + }, + "complete": { + "type": "boolean", + "description": "False when not every applicable constraint/preference could be considered; do not treat the briefing as complete." + }, + "truncated": { + "type": "boolean", + "description": "True when items were left out to fit the budget." + } + } + }, + "omitted": { + "type": "object", + "properties": { + "over_budget": { + "type": "integer" + }, + "over_limit": { + "type": "integer" + }, + "duplicates": { + "type": "integer" + }, + "unverified_excluded": { + "type": "integer" + } + } + }, + "constraints": { + "type": "array", + "items": { + "type": "object" + } + }, + "working_state": { + "type": "object", + "nullable": true + }, + "preferences": { + "type": "array", + "items": { + "type": "object" + } + }, + "conflicts": { + "type": "array", + "items": { + "type": "object" + } + }, + "decisions": { + "type": "array", + "items": { + "type": "object" + } + }, + "lessons": { + "type": "array", + "items": { + "type": "object" + } + }, + "knowledge": { + "type": "array", + "items": { + "type": "object" + } + }, + "references": { + "type": "array", + "items": { + "type": "object" + } + }, + "unverified": { + "type": "array", + "items": { + "type": "object" + }, + "description": "Only with verification_filter include_unverified." + }, + "warnings": { + "type": "array", + "items": { + "type": "string" + } + } + } } } }, @@ -1954,6 +2165,88 @@ } } } + }, + "/context": { + "post": { + "summary": "Assemble a token-budgeted task briefing: constraints by scope, working state, preferences, conflicts, lexical matches and reference passages", + "security": [ + { + "bearerAuth": [] + } + ], + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContextRequest" + } + } + } + }, + "responses": { + "200": { + "description": "Briefing", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ContextResponse" + } + } + } + }, + "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" + } + } + } + }, + "404": { + "description": "session_id not found or not visible to the caller", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "422": { + "description": "Validation failed, unsupported_character (code points above U+FFFF), or context_budget_exceeded (the applicable constraints do not fit max_context_tokens; the error also carries required_tokens)", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "500": { + "description": "Internal error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } } } -} \ No newline at end of file +} diff --git a/scripts/templates/Api.tpl.asp b/scripts/templates/Api.tpl.asp index 5584259..770edd6 100644 --- a/scripts/templates/Api.tpl.asp +++ b/scripts/templates/Api.tpl.asp @@ -18,6 +18,7 @@ Const {{CONST}}_MAX_PER_PAGE = 100 Class Api{{TABLE}}Controller_Class {{MEMBERS}} + Private m_unsupportedChar ' set by Utf8Decode for code points above U+FFFF ' Dispatcher reads this to decide whether to wrap the output in the HTML layout Public Property Get useLayout() @@ -239,12 +240,18 @@ Class Api{{TABLE}}Controller_Class Exit Function End If ' AxonASP: BinaryRead returns one character per byte, so decode the UTF-8 by hand. + m_unsupportedChar = False text = Utf8Decode(CStr(Request.BinaryRead(n))) If JsonLite_Parse(text) Is Nothing Then SendError 400, "Body must be a valid JSON object." Exit Function End If + ' Reject rather than store damaged text (see Utf8Decode) + If m_unsupportedChar Or JsonLite_SurrogateSeen Then + SendError 422, "Characters above U+FFFF (for example emoji) are not supported yet. Remove or replace them." + Exit Function + End If ReadBodyText = text End Function @@ -284,9 +291,11 @@ Class Api{{TABLE}}Controller_Class Next End If If ok And cp <= 1114111 Then - If cp >= 65536 Then - cp = cp - 65536 - out = out & ChrW(55296 + Int(cp / 1024)) & ChrW(56320 + (cp Mod 1024)) + ' AxonASP (pinned build): ChrW above U+FFFF fails and surrogate pairs come out as CESU-8, so these + ' code points are flagged and ReadBodyText answers 422. + If cp > 65535 Or (cp >= 55296 And cp <= 57343) Then + m_unsupportedChar = True + out = out & ChrW(65533) Else out = out & ChrW(cp) End If diff --git a/tests/phase1-api.sh b/tests/phase1-api.sh index 2a40c8f..81b2622 100644 --- a/tests/phase1-api.sh +++ b/tests/phase1-api.sh @@ -16,6 +16,7 @@ prov() { # prov [arg1 arg2 arg3 arg4] axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r' } field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } # field from provision output +has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; } jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; } # first "name":"value" in a JSON text cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; } @@ -145,11 +146,17 @@ check "state must be object -> 422" "422" "$(code "$WK" PUT /sessions/$SID/state check "complete -> 200" "200" "$(code "$WK" POST /sessions/$SID/complete -d '{"outcome":"ok"}')" check "save after complete -> 409" "409" "$(code "$WK" PUT /sessions/$SID/state -H 'If-Match: 2' -d '{"state":{"s":3}}')" -# ---- UTF-8 round trip (BMP and beyond) ------------------------------------------------------------------- -U=$'caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac \xf0\x9f\x98\x80' +# ---- UTF-8 round trip (BMP); characters above U+FFFF are rejected (pinned runtime cannot hold them) ------- +U=$'caf\xc3\xa9 \xe6\x97\xa5\xe6\x9c\xac' UJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"utf8","content":"%s"}' "$NSA" "$U") UID_=$(printf '%s' "$UJ" | curl -s -X POST -H "Authorization: Bearer $WK" --data-binary @- "$BASE/remember" | jget id) check "utf-8 content round trip" "yes" "$(body "$WK" GET /memories/$UID_ | grep -qF "$U" && echo yes || echo no)" +EJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"emoji","content":"x %s"}' "$NSA" $'\xf0\x9f\x98\x80') +check "raw emoji -> 422" "422" "$(printf '%s' "$EJ" | curl -s -o /dev/null -w '%{http_code}' -X POST -H "Authorization: Bearer $WK" --data-binary @- "$BASE/remember")" +# escaped surrogate pair; the backslashes are produced at run time so no tool or shell can pre-decode them +SJ=$(printf '{"namespace_id":"%s","type":"semantic","title":"emoji","content":"x %sud83d%sude00"}' "$NSA" '\' '\') +check "escaped surrogate pair -> 422" "422" "$(code "$WK" POST /remember --data-binary "$SJ")" +check "unsupported_character code" "yes" "$(has unsupported_character "$(body "$WK" POST /remember --data-binary "$SJ")")" # ---- revoked key, restart persistence (AC-01), cold first request ---------------------------------------- KID=$(prov key "$WID" | field api_key_id); KK=$(prov key "$WID" | field api_key) diff --git a/tests/phase3-context.sh b/tests/phase3-context.sh new file mode 100644 index 0000000..220b09c --- /dev/null +++ b/tests/phase3-context.sh @@ -0,0 +1,168 @@ +#!/usr/bin/env bash +# Phase 3 checks for POST /context (spec FR-010, section 9.3, AC-05): sections, constraints loaded by scope, +# verification and lifecycle filtering, conflicts, deduplication, token budget (incl. the 422 budget error), +# working state, isolation (AC-06), validation, escaping and UTF-8. +# +# Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions two +# throw-away tenants and purges them at the end (even on failure). +# bash tests/phase3-context.sh +set -u +BASE=${BASE:-http://localhost:8801/api/v1} +PASS=0; FAIL=0; FAILED=(); TENANTS=() +prov() { + MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \ + -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \ + axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r' +} +field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; } +jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; } +cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; } +trap cleanup EXIT +check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; } +code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } +body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; } +has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; } +jq_() { python -I -c "import sys,json;d=json.load(sys.stdin);print($1)"; } # jq_ '' +js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; } # JSON string literal + +# remember <content> [importance] -> memory id +remember() { + local imp=${6:-0.5} + body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5"),\"importance\":$imp}" | jget id +} +verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"$3\",\"method\":\"manual\",\"revision\":1}" >/dev/null; } +ctx() { local key=$1; shift; body "$key" POST /context -d "$1"; } + +# ---- setup ------------------------------------------------------------------------------------------------ +TA=$(prov tenant "p3-A" | field tenant_id); TB=$(prov tenant "p3-B" | field tenant_id); TENANTS=("$TA" "$TB") +mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); } +mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY +mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY +mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY +mk "$TB" writerB agent; BID=$P_ID; BK=$P_KEY +prov grant "$WID" /kb "read,write,delete,verify" 1 >/dev/null +prov grant "$WID" /big "read,write,delete,verify" 1 >/dev/null +prov grant "$RID" /kb "read" 1 >/dev/null +prov grant "$BID" /kb "read,write,delete,verify" 1 >/dev/null +prov grant "$BLID" /elsewhere "read" 1 >/dev/null +NS=$(prov namespace "$TA" /kb | field namespace_id); NSSUB=$(prov namespace "$TA" /kb/sub | field namespace_id) +NSBIG=$(prov namespace "$TA" /big | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id) +[ -n "$NS" ] && [ -n "$NSSUB" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; } + +# ---- cold start: first request after a restart is a context POST -------------------------------------------- +docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done +check "cold: context on empty tenant -> 200" "200" "$(code "$WK" POST /context -d '{"task":"zebracorn"}')" + +C1=$(remember "$WK" "$NS" constraint "No Friday deploys" "Never deploy zebracorn on Fridays." 0.9); verify "$WK" "$C1" verified +C2=$(remember "$WK" "$NS" constraint "Draft xylophone rule" "Draft constraint about the xylophone." 0.8) # unverified +P1=$(remember "$WK" "$NS" preference "Tabs" "Prefer tabs in zebracorn source files." 0.4); verify "$WK" "$P1" verified +D1=$(remember "$WK" "$NS" decision "Storage" "We chose SQLite for zebracorn storage." 0.5); verify "$WK" "$D1" verified +L1=$(remember "$WK" "$NS" lesson "Migrations" "Zebracorn migrations must run one at a time." 0.5); verify "$WK" "$L1" verified +K1=$(remember "$WK" "$NS" semantic "Port" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$K1" verified +K2=$(remember "$WK" "$NS" semantic "Platform" "Zebracorn runs on Windows only." 0.5); verify "$WK" "$K2" disputed +K3=$(remember "$WK" "$NS" semantic "Old host" "Zebracorn used to run on host alpha." 0.5); verify "$WK" "$K3" verified +code "$WK" POST /memories/$K3/retire >/dev/null +KD=$(remember "$WK" "$NSSUB" semantic "Port copy" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$KD" verified # same content +X1=$(remember "$WK" "$NS" semantic "Fruit" "Bananas are yellow." 0.5); verify "$WK" "$X1" verified # unrelated +E1=$(remember "$WK" "$NS" semantic "Escaping" "Zebracorn quote \"q\" and <script>alert(1)</script> tag." 0.5); verify "$WK" "$E1" verified +# Non-ASCII goes in as JSON \u escapes (Git Bash curl mangles raw UTF-8 literals), BMP only: characters above U+FFFF are a known runtime issue, see phase1 +UJ='{"namespace_id":"'$NS'","type":"semantic","title":"utf8","content":"Gr\u00fc\u00dfe zebracorn \u65e5\u672c"}' +UM=$(curl -s -X POST -H "Authorization: Bearer $WK" --data-binary "$UJ" "$BASE/remember" | jget id); verify "$WK" "$UM" verified +LONGC=$(python -I -c "print(' '.join(['Rule %d: every zebracorn release needs a signed checklist entry.' % i for i in range(20)]))") +CB=$(remember "$WK" "$NSBIG" constraint "Big rule" "$LONGC" 0.9); verify "$WK" "$CB" verified +BM=$(remember "$BK" "$NSB" constraint "B secret" "Tenant B secret zebracorn rule." 0.9); verify "$BK" "$BM" verified +FILL=$(python -I -c "print(' '.join(['zebracorn operations note %d explains the routine.' % i for i in range(40)]))") +curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \ + -d "{\"namespace_id\":\"$NS\",\"title\":\"Ops\",\"source_uri\":\"kb://ops\",\"format\":\"markdown\",\"content\":$(js "# Ops + +Zebracorn runbook: restart the zebracorn service with care. + +$FILL")}" +SID=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"Ship zebracorn\"}" | jget id) +code "$WK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"step":3,"next":"tests"}}' >/dev/null +[ -n "$C1" ] && [ -n "$K2" ] && [ -n "$SID" ] && [ -n "$CB" ] || { echo "data setup failed"; exit 2; } + +# ---- full briefing ------------------------------------------------------------------------------------------ +R=$(ctx "$WK" "{\"task\":\"zebracorn deploy\",\"namespace_ids\":[\"$NS\",\"$NSSUB\"],\"session_id\":\"$SID\"}") +check "context -> valid JSON" "yes" "$(echo "$R" | jq_ "'yes'" 2>/dev/null || echo no)" +check "constraint loaded by scope" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")" +check "constraint has policy authority" "policy" "$(echo "$R" | jq_ "[x for x in d['constraints'] if x['id']=='$C1'][0].get('authority')")" +check "unverified constraint excluded by default" "no" "$(has "$C2" "$R")" +check "preference included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$P1' for x in d['preferences']) else 'no'")" +check "decision section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$D1' for x in d['decisions']) else 'no'")" +check "lesson section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$L1' for x in d['lessons']) else 'no'")" +check "knowledge section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K1' for x in d['knowledge']) else 'no'")" +check "disputed memory under conflicts" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K2' and x['content_trust']=='disputed_memory' for x in d['conflicts']) else 'no'")" +check "retired memory excluded" "no" "$(has "$K3" "$R")" +check "unrelated memory not matched" "no" "$(has "$X1" "$R")" +check "duplicate content appears once" "no" "$(has "$KD" "$R")" +check "duplicates counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['duplicates']>=1 else 'no'")" +check "unverified excluded counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['unverified_excluded']>=1 else 'no'")" +check "references are untrusted" "yes" "$(echo "$R" | jq_ "'yes' if d['references'] and all(x['content_trust']=='untrusted_reference' for x in d['references']) else 'no'")" +check "working state included" "tests" "$(echo "$R" | jq_ "d['working_state']['state']['next']")" +check "items carry revision and provenance" "yes" "$(echo "$R" | jq_ "'yes' if all('revision' in x and 'created_by' in x['provenance'] for x in d['knowledge']) else 'no'")" +check "used tokens within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=d['budget']['max_context_tokens'] else 'no'")" +check "complete and not truncated" "True False" "$(echo "$R" | jq_ "d['budget']['complete'], d['budget']['truncated']" | tr -d '(),')" +check "counting method declared" "estimate_chars_div_4" "$(echo "$R" | jq_ "d['budget']['counting_method']")" +check "lexical-only warning" "yes" "$(has 'lexical only' "$R")" +check "tenant B content never included" "no" "$(has 'Tenant B secret' "$R")" +check "escaped content round-trips" "yes" "$(echo "$R" | jq_ "'yes' if any(x['content']=='Zebracorn quote \"q\" and <script>alert(1)</script> tag.' for x in d['knowledge']) else 'no'")" +check "UTF-8 round trip" "yes" "$(echo "$R" | python -I -c " +import sys,json +d=json.loads(sys.stdin.buffer.read()); u='Gr\u00fc\u00dfe zebracorn \u65e5\u672c' +print('yes' if any(x['content']==u for x in d['knowledge']) else 'no')")" + +# ---- verification filter ------------------------------------------------------------------------------------ +R=$(ctx "$WK" "{\"task\":\"zebracorn xylophone\",\"namespace_ids\":[\"$NS\"],\"verification_filter\":\"include_unverified\"}") +check "include_unverified -> unverified section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' and x['content_trust']=='unverified_memory' for x in d['unverified']) else 'no'")" +check "unverified constraint is not policy" "no" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' for x in d['constraints']) else 'no'")" + +# ---- budget ------------------------------------------------------------------------------------------------- +R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_context_tokens\":100}") +check "small budget -> truncated" "True" "$(echo "$R" | jq_ "d['budget']['truncated']")" +check "small budget -> within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=100 else 'no'")" +check "small budget keeps constraints" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")" +check "small budget -> over_budget counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['over_budget']>0 else 'no'")" +check "constraints over budget -> 422" "422" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}")" +check "budget error code" "context_budget_exceeded" "$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}" | jq_ "d['error']['code']")" +check "bigger budget fits big constraint" "200" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":2000}")" +R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_items\":1,\"max_references\":0}") +check "max_items caps a section" "1" "$(echo "$R" | jq_ "len(d['knowledge'])")" +check "max_references 0 -> none" "0" "$(echo "$R" | jq_ "len(d['references'])")" + +# ---- include and detail ------------------------------------------------------------------------------------- +R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"include\":[\"lessons\"]}") +check "include limits sections" "False False True" "$(echo "$R" | jq_ "'decisions' in d, 'references' in d, 'lessons' in d" | tr -d '(),')" +check "constraints always included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")" +R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"detail_level\":\"summary\"}") +check "summary detail on knowledge" "True False" "$(echo "$R" | jq_ "'summary' in d['knowledge'][0], 'content' in d['knowledge'][0]" | tr -d '(),')" +check "constraints stay full in summary" "yes" "$(echo "$R" | jq_ "'yes' if 'content' in d['constraints'][0] else 'no'")" + +# ---- access ------------------------------------------------------------------------------------------------- +check "reader gets briefing" "yes" "$(ctx "$RK" '{"task":"zebracorn"}' | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")" +check "reader can use session read" "200" "$(code "$RK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")" +R=$(ctx "$BLK" '{"task":"zebracorn"}') +check "no-access principal gets empty briefing" "0 0" "$(echo "$R" | jq_ "len(d['constraints']), len(d['knowledge'])" | tr -d '(),')" +check "no-access session -> 404" "404" "$(code "$BLK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")" +check "other tenant session -> 404" "404" "$(code "$BK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")" +check "unknown session -> 404" "404" "$(code "$WK" POST /context -d '{"task":"zebracorn","session_id":"00000000-0000-4000-8000-000000000000"}')" +check "tenant B sees only its constraint" "yes" "$(ctx "$BK" '{"task":"zebracorn"}' | jq_ "'yes' if [x['id'] for x in d['constraints']]==['$BM'] else 'no'")" +check "namespace outside grants yields nothing" "0" "$(ctx "$RK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"]}" | jq_ "len(d['constraints'])")" + +# ---- validation --------------------------------------------------------------------------------------------- +check "no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{"task":"x"}' "$BASE/context")" +check "missing task -> 422" "422" "$(code "$WK" POST /context -d '{}')" +check "task without words -> 422" "422" "$(code "$WK" POST /context -d '{"task":"!!!"}')" +check "budget too small -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":50}')" +check "budget not whole -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":500.5}')" +check "unknown include -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","include":["bogus"]}')" +check "unsupported format -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","format":"markdown"}')" +check "bad verification_filter -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","verification_filter":"all"}')" +check "bad session id -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","session_id":"nope"}')" +check "bad namespace ids -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","namespace_ids":["nope"]}')" +check "invalid JSON -> 400" "400" "$(code "$WK" POST /context -d '{"task":')" +check "empty body -> 400" "400" "$(code "$WK" POST /context)" + +echo "passed: $PASS failed: $FAIL" +for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done +[ "$FAIL" -eq 0 ]