|
- #!/usr/bin/env bash
- # Phase 3 checks for POST /context (spec FR-010, section 9.3, AC-05): sections, constraints loaded by scope,
- # verification and lifecycle filtering, conflicts, deduplication, token budget (incl. the 422 budget error),
- # working state, isolation (AC-06), validation, escaping and UTF-8.
- #
- # Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions two
- # throw-away tenants and purges them at the end (even on failure).
- # bash tests/phase3-context.sh
- set -u
- BASE=${BASE:-http://localhost:8801/api/v1}
- PASS=0; FAIL=0; FAILED=(); TENANTS=()
- prov() {
- MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
- -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
- axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r'
- }
- field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
- jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
- cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; }
- trap cleanup EXIT
- check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
- code() { local key=$1 m=$2 p=$3; shift 3; curl -s -o /dev/null -w '%{http_code}' -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
- body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
- has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; }
- jq_() { python -I -c "import sys,json;d=json.load(sys.stdin);print($1)"; } # jq_ '<python expr on d>'
- js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; } # JSON string literal
-
- # remember <key> <ns> <type> <title> <content> [importance] -> memory id
- remember() {
- local imp=${6:-0.5}
- body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5"),\"importance\":$imp}" | jget id
- }
- verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"$3\",\"method\":\"manual\",\"revision\":1}" >/dev/null; }
- ctx() { local key=$1; shift; body "$key" POST /context -d "$1"; }
-
- # ---- setup ------------------------------------------------------------------------------------------------
- TA=$(prov tenant "p3-A" | field tenant_id); TB=$(prov tenant "p3-B" | field tenant_id); TENANTS=("$TA" "$TB")
- mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
- mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
- mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY
- mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY
- mk "$TB" writerB agent; BID=$P_ID; BK=$P_KEY
- prov grant "$WID" /kb "read,write,delete,verify" 1 >/dev/null
- prov grant "$WID" /big "read,write,delete,verify" 1 >/dev/null
- prov grant "$RID" /kb "read" 1 >/dev/null
- prov grant "$BID" /kb "read,write,delete,verify" 1 >/dev/null
- prov grant "$BLID" /elsewhere "read" 1 >/dev/null
- NS=$(prov namespace "$TA" /kb | field namespace_id); NSSUB=$(prov namespace "$TA" /kb/sub | field namespace_id)
- NSBIG=$(prov namespace "$TA" /big | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
- [ -n "$NS" ] && [ -n "$NSSUB" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; }
-
- # ---- cold start: first request after a restart is a context POST --------------------------------------------
- docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
- check "cold: context on empty tenant -> 200" "200" "$(code "$WK" POST /context -d '{"task":"zebracorn"}')"
-
- C1=$(remember "$WK" "$NS" constraint "No Friday deploys" "Never deploy zebracorn on Fridays." 0.9); verify "$WK" "$C1" verified
- C2=$(remember "$WK" "$NS" constraint "Draft xylophone rule" "Draft constraint about the xylophone." 0.8) # unverified
- P1=$(remember "$WK" "$NS" preference "Tabs" "Prefer tabs in zebracorn source files." 0.4); verify "$WK" "$P1" verified
- D1=$(remember "$WK" "$NS" decision "Storage" "We chose SQLite for zebracorn storage." 0.5); verify "$WK" "$D1" verified
- L1=$(remember "$WK" "$NS" lesson "Migrations" "Zebracorn migrations must run one at a time." 0.5); verify "$WK" "$L1" verified
- K1=$(remember "$WK" "$NS" semantic "Port" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$K1" verified
- K2=$(remember "$WK" "$NS" semantic "Platform" "Zebracorn runs on Windows only." 0.5); verify "$WK" "$K2" disputed
- K3=$(remember "$WK" "$NS" semantic "Old host" "Zebracorn used to run on host alpha." 0.5); verify "$WK" "$K3" verified
- code "$WK" POST /memories/$K3/retire >/dev/null
- KD=$(remember "$WK" "$NSSUB" semantic "Port copy" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$KD" verified # same content
- X1=$(remember "$WK" "$NS" semantic "Fruit" "Bananas are yellow." 0.5); verify "$WK" "$X1" verified # unrelated
- E1=$(remember "$WK" "$NS" semantic "Escaping" "Zebracorn quote \"q\" and <script>alert(1)</script> tag." 0.5); verify "$WK" "$E1" verified
- # Non-ASCII goes in as JSON \u escapes (Git Bash curl mangles raw UTF-8 literals), BMP only: characters above U+FFFF are a known runtime issue, see phase1
- UJ='{"namespace_id":"'$NS'","type":"semantic","title":"utf8","content":"Gr\u00fc\u00dfe zebracorn \u65e5\u672c"}'
- UM=$(curl -s -X POST -H "Authorization: Bearer $WK" --data-binary "$UJ" "$BASE/remember" | jget id); verify "$WK" "$UM" verified
- LONGC=$(python -I -c "print(' '.join(['Rule %d: every zebracorn release needs a signed checklist entry.' % i for i in range(20)]))")
- CB=$(remember "$WK" "$NSBIG" constraint "Big rule" "$LONGC" 0.9); verify "$WK" "$CB" verified
- BM=$(remember "$BK" "$NSB" constraint "B secret" "Tenant B secret zebracorn rule." 0.9); verify "$BK" "$BM" verified
- FILL=$(python -I -c "print(' '.join(['zebracorn operations note %d explains the routine.' % i for i in range(40)]))")
- curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \
- -d "{\"namespace_id\":\"$NS\",\"title\":\"Ops\",\"source_uri\":\"kb://ops\",\"format\":\"markdown\",\"content\":$(js "# Ops
-
- Zebracorn runbook: restart the zebracorn service with care.
-
- $FILL")}"
- SID=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"Ship zebracorn\"}" | jget id)
- code "$WK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"step":3,"next":"tests"}}' >/dev/null
- [ -n "$C1" ] && [ -n "$K2" ] && [ -n "$SID" ] && [ -n "$CB" ] || { echo "data setup failed"; exit 2; }
-
- # ---- full briefing ------------------------------------------------------------------------------------------
- R=$(ctx "$WK" "{\"task\":\"zebracorn deploy\",\"namespace_ids\":[\"$NS\",\"$NSSUB\"],\"session_id\":\"$SID\"}")
- check "context -> valid JSON" "yes" "$(echo "$R" | jq_ "'yes'" 2>/dev/null || echo no)"
- check "constraint loaded by scope" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
- check "constraint has policy authority" "policy" "$(echo "$R" | jq_ "[x for x in d['constraints'] if x['id']=='$C1'][0].get('authority')")"
- check "unverified constraint excluded by default" "no" "$(has "$C2" "$R")"
- check "preference included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$P1' for x in d['preferences']) else 'no'")"
- check "decision section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$D1' for x in d['decisions']) else 'no'")"
- check "lesson section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$L1' for x in d['lessons']) else 'no'")"
- check "knowledge section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K1' for x in d['knowledge']) else 'no'")"
- check "disputed memory under conflicts" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K2' and x['content_trust']=='disputed_memory' for x in d['conflicts']) else 'no'")"
- check "retired memory excluded" "no" "$(has "$K3" "$R")"
- check "unrelated memory not matched" "no" "$(has "$X1" "$R")"
- check "duplicate content appears once" "no" "$(has "$KD" "$R")"
- check "duplicates counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['duplicates']>=1 else 'no'")"
- check "unverified excluded counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['unverified_excluded']>=1 else 'no'")"
- check "references are untrusted" "yes" "$(echo "$R" | jq_ "'yes' if d['references'] and all(x['content_trust']=='untrusted_reference' for x in d['references']) else 'no'")"
- check "working state included" "tests" "$(echo "$R" | jq_ "d['working_state']['state']['next']")"
- check "items carry revision and provenance" "yes" "$(echo "$R" | jq_ "'yes' if all('revision' in x and 'created_by' in x['provenance'] for x in d['knowledge']) else 'no'")"
- check "used tokens within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=d['budget']['max_context_tokens'] else 'no'")"
- check "complete and not truncated" "True False" "$(echo "$R" | jq_ "d['budget']['complete'], d['budget']['truncated']" | tr -d '(),')"
- check "counting method declared" "estimate_chars_div_4" "$(echo "$R" | jq_ "d['budget']['counting_method']")"
- check "strategy reported" "yes" "$(echo "$R" | jq_ "'yes' if d['strategy'] in ('hybrid','lexical') else 'no'")"
- check "tenant B content never included" "no" "$(has 'Tenant B secret' "$R")"
- check "escaped content round-trips" "yes" "$(echo "$R" | jq_ "'yes' if any(x['content']=='Zebracorn quote \"q\" and <script>alert(1)</script> tag.' for x in d['knowledge']) else 'no'")"
- check "UTF-8 round trip" "yes" "$(echo "$R" | python -I -c "
- import sys,json
- d=json.loads(sys.stdin.buffer.read()); u='Gr\u00fc\u00dfe zebracorn \u65e5\u672c'
- print('yes' if any(x['content']==u for x in d['knowledge']) else 'no')")"
-
- # ---- verification filter ------------------------------------------------------------------------------------
- R=$(ctx "$WK" "{\"task\":\"zebracorn xylophone\",\"namespace_ids\":[\"$NS\"],\"verification_filter\":\"include_unverified\"}")
- check "include_unverified -> unverified section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' and x['content_trust']=='unverified_memory' for x in d['unverified']) else 'no'")"
- check "unverified constraint is not policy" "no" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' for x in d['constraints']) else 'no'")"
-
- # ---- budget -------------------------------------------------------------------------------------------------
- R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_context_tokens\":100}")
- check "small budget -> truncated" "True" "$(echo "$R" | jq_ "d['budget']['truncated']")"
- check "small budget -> within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=100 else 'no'")"
- check "small budget keeps constraints" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
- check "small budget -> over_budget counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['over_budget']>0 else 'no'")"
- check "constraints over budget -> 422" "422" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}")"
- check "budget error code" "context_budget_exceeded" "$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}" | jq_ "d['error']['code']")"
- check "bigger budget fits big constraint" "200" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":2000}")"
- R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_items\":1,\"max_references\":0}")
- check "max_items caps a section" "1" "$(echo "$R" | jq_ "len(d['knowledge'])")"
- check "max_references 0 -> none" "0" "$(echo "$R" | jq_ "len(d['references'])")"
-
- # ---- include and detail -------------------------------------------------------------------------------------
- R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"include\":[\"lessons\"]}")
- check "include limits sections" "False False True" "$(echo "$R" | jq_ "'decisions' in d, 'references' in d, 'lessons' in d" | tr -d '(),')"
- check "constraints always included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
- R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"detail_level\":\"summary\"}")
- check "summary detail on knowledge" "True False" "$(echo "$R" | jq_ "'summary' in d['knowledge'][0], 'content' in d['knowledge'][0]" | tr -d '(),')"
- check "constraints stay full in summary" "yes" "$(echo "$R" | jq_ "'yes' if 'content' in d['constraints'][0] else 'no'")"
-
- # ---- access -------------------------------------------------------------------------------------------------
- check "reader gets briefing" "yes" "$(ctx "$RK" '{"task":"zebracorn"}' | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
- check "reader can use session read" "200" "$(code "$RK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
- R=$(ctx "$BLK" '{"task":"zebracorn"}')
- check "no-access principal gets empty briefing" "0 0" "$(echo "$R" | jq_ "len(d['constraints']), len(d['knowledge'])" | tr -d '(),')"
- check "no-access session -> 404" "404" "$(code "$BLK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
- check "other tenant session -> 404" "404" "$(code "$BK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
- check "unknown session -> 404" "404" "$(code "$WK" POST /context -d '{"task":"zebracorn","session_id":"00000000-0000-4000-8000-000000000000"}')"
- check "tenant B sees only its constraint" "yes" "$(ctx "$BK" '{"task":"zebracorn"}' | jq_ "'yes' if [x['id'] for x in d['constraints']]==['$BM'] else 'no'")"
- check "namespace outside grants yields nothing" "0" "$(ctx "$RK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"]}" | jq_ "len(d['constraints'])")"
-
- # ---- validation ---------------------------------------------------------------------------------------------
- check "no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{"task":"x"}' "$BASE/context")"
- check "missing task -> 422" "422" "$(code "$WK" POST /context -d '{}')"
- check "task without words -> 422" "422" "$(code "$WK" POST /context -d '{"task":"!!!"}')"
- check "budget too small -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":50}')"
- check "budget not whole -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":500.5}')"
- check "unknown include -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","include":["bogus"]}')"
- check "unsupported format -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","format":"markdown"}')"
- check "bad verification_filter -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","verification_filter":"all"}')"
- check "bad session id -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","session_id":"nope"}')"
- check "bad namespace ids -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","namespace_ids":["nope"]}')"
- check "invalid JSON -> 400" "400" "$(code "$WK" POST /context -d '{"task":')"
- check "empty body -> 400" "400" "$(code "$WK" POST /context)"
-
- echo "passed: $PASS failed: $FAIL"
- for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
- [ "$FAIL" -eq 0 ]
|