Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

169 rindas
15KB

  1. #!/usr/bin/env bash
  2. # Phase 3 checks for POST /context (spec FR-010, section 9.3, AC-05): sections, constraints loaded by scope,
  3. # verification and lifecycle filtering, conflicts, deduplication, token budget (incl. the 422 budget error),
  4. # working state, isolation (AC-06), validation, escaping and UTF-8.
  5. #
  6. # Needs the container from docker-compose.yml running (name "axonasp", http://localhost:8801). It provisions two
  7. # throw-away tenants and purges them at the end (even on failure).
  8. # bash tests/phase3-context.sh
  9. set -u
  10. BASE=${BASE:-http://localhost:8801/api/v1}
  11. PASS=0; FAIL=0; FAILED=(); TENANTS=()
  12. prov() {
  13. MSYS_NO_PATHCONV=1 docker exec -u axonasp -e SERVER_WEB_ROOT=/opt/axonasp/site \
  14. -e "PROV_ACTION=$1" -e "PROV_ARG1=${2:-}" -e "PROV_ARG2=${3:-}" -e "PROV_ARG3=${4:-}" -e "PROV_ARG4=${5:-}" \
  15. axonasp ./axonasp-cli -r /opt/axonasp/site/scripts/provision.asp 2>&1 | tr -d '\r'
  16. }
  17. field() { sed -n "s/^$1: *\([^ ]*\).*/\1/p" | head -1; }
  18. jget() { sed -n "s/.*\"$1\":\"\([^\"]*\)\".*/\1/p" | head -1; }
  19. cleanup() { for t in "${TENANTS[@]}"; do prov purge "$t" >/dev/null; done; }
  20. trap cleanup EXIT
  21. check() { if [ "$2" = "$3" ]; then PASS=$((PASS+1)); else FAIL=$((FAIL+1)); FAILED+=("$1 (expected $2, got $3)"); fi; }
  22. 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"; }
  23. body() { local key=$1 m=$2 p=$3; shift 3; curl -s -X "$m" -H "Authorization: Bearer $key" "$@" "$BASE$p"; }
  24. has() { grep -q -- "$1" <<<"$2" && echo yes || echo no; }
  25. jq_() { python -I -c "import sys,json;d=json.load(sys.stdin);print($1)"; } # jq_ '<python expr on d>'
  26. js() { python -I -c "import json,sys;print(json.dumps(sys.argv[1]))" "$1"; } # JSON string literal
  27. # remember <key> <ns> <type> <title> <content> [importance] -> memory id
  28. remember() {
  29. local imp=${6:-0.5}
  30. body "$1" POST /remember -d "{\"namespace_id\":\"$2\",\"type\":\"$3\",\"title\":$(js "$4"),\"content\":$(js "$5"),\"importance\":$imp}" | jget id
  31. }
  32. verify() { code "$1" POST /memories/$2/verifications -d "{\"result\":\"$3\",\"method\":\"manual\",\"revision\":1}" >/dev/null; }
  33. ctx() { local key=$1; shift; body "$key" POST /context -d "$1"; }
  34. # ---- setup ------------------------------------------------------------------------------------------------
  35. TA=$(prov tenant "p3-A" | field tenant_id); TB=$(prov tenant "p3-B" | field tenant_id); TENANTS=("$TA" "$TB")
  36. mk() { local out; out=$(prov principal "$1" "$2" "$3"); P_ID=$(echo "$out" | field principal_id); P_KEY=$(echo "$out" | field api_key); }
  37. mk "$TA" writer agent; WID=$P_ID; WK=$P_KEY
  38. mk "$TA" reader agent; RID=$P_ID; RK=$P_KEY
  39. mk "$TA" blind agent; BLID=$P_ID; BLK=$P_KEY
  40. mk "$TB" writerB agent; BID=$P_ID; BK=$P_KEY
  41. prov grant "$WID" /kb "read,write,delete,verify" 1 >/dev/null
  42. prov grant "$WID" /big "read,write,delete,verify" 1 >/dev/null
  43. prov grant "$RID" /kb "read" 1 >/dev/null
  44. prov grant "$BID" /kb "read,write,delete,verify" 1 >/dev/null
  45. prov grant "$BLID" /elsewhere "read" 1 >/dev/null
  46. NS=$(prov namespace "$TA" /kb | field namespace_id); NSSUB=$(prov namespace "$TA" /kb/sub | field namespace_id)
  47. NSBIG=$(prov namespace "$TA" /big | field namespace_id); NSB=$(prov namespace "$TB" /kb | field namespace_id)
  48. [ -n "$NS" ] && [ -n "$NSSUB" ] && [ -n "$NSB" ] && [ -n "$WK" ] || { echo "setup failed"; exit 2; }
  49. # ---- cold start: first request after a restart is a context POST --------------------------------------------
  50. docker restart axonasp >/dev/null; for i in $(seq 1 20); do curl -s -o /dev/null "$BASE/health/live" && break; sleep 1; done
  51. check "cold: context on empty tenant -> 200" "200" "$(code "$WK" POST /context -d '{"task":"zebracorn"}')"
  52. C1=$(remember "$WK" "$NS" constraint "No Friday deploys" "Never deploy zebracorn on Fridays." 0.9); verify "$WK" "$C1" verified
  53. C2=$(remember "$WK" "$NS" constraint "Draft xylophone rule" "Draft constraint about the xylophone." 0.8) # unverified
  54. P1=$(remember "$WK" "$NS" preference "Tabs" "Prefer tabs in zebracorn source files." 0.4); verify "$WK" "$P1" verified
  55. D1=$(remember "$WK" "$NS" decision "Storage" "We chose SQLite for zebracorn storage." 0.5); verify "$WK" "$D1" verified
  56. L1=$(remember "$WK" "$NS" lesson "Migrations" "Zebracorn migrations must run one at a time." 0.5); verify "$WK" "$L1" verified
  57. K1=$(remember "$WK" "$NS" semantic "Port" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$K1" verified
  58. K2=$(remember "$WK" "$NS" semantic "Platform" "Zebracorn runs on Windows only." 0.5); verify "$WK" "$K2" disputed
  59. K3=$(remember "$WK" "$NS" semantic "Old host" "Zebracorn used to run on host alpha." 0.5); verify "$WK" "$K3" verified
  60. code "$WK" POST /memories/$K3/retire >/dev/null
  61. KD=$(remember "$WK" "$NSSUB" semantic "Port copy" "Zebracorn listens on port 8801." 0.5); verify "$WK" "$KD" verified # same content
  62. X1=$(remember "$WK" "$NS" semantic "Fruit" "Bananas are yellow." 0.5); verify "$WK" "$X1" verified # unrelated
  63. E1=$(remember "$WK" "$NS" semantic "Escaping" "Zebracorn quote \"q\" and <script>alert(1)</script> tag." 0.5); verify "$WK" "$E1" verified
  64. # 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
  65. UJ='{"namespace_id":"'$NS'","type":"semantic","title":"utf8","content":"Gr\u00fc\u00dfe zebracorn \u65e5\u672c"}'
  66. UM=$(curl -s -X POST -H "Authorization: Bearer $WK" --data-binary "$UJ" "$BASE/remember" | jget id); verify "$WK" "$UM" verified
  67. LONGC=$(python -I -c "print(' '.join(['Rule %d: every zebracorn release needs a signed checklist entry.' % i for i in range(20)]))")
  68. CB=$(remember "$WK" "$NSBIG" constraint "Big rule" "$LONGC" 0.9); verify "$WK" "$CB" verified
  69. BM=$(remember "$BK" "$NSB" constraint "B secret" "Tenant B secret zebracorn rule." 0.9); verify "$BK" "$BM" verified
  70. FILL=$(python -I -c "print(' '.join(['zebracorn operations note %d explains the routine.' % i for i in range(40)]))")
  71. curl -s -o /dev/null -X POST -H "Authorization: Bearer $WK" "$BASE/ingestion/jobs" \
  72. -d "{\"namespace_id\":\"$NS\",\"title\":\"Ops\",\"source_uri\":\"kb://ops\",\"format\":\"markdown\",\"content\":$(js "# Ops
  73. Zebracorn runbook: restart the zebracorn service with care.
  74. $FILL")}"
  75. SID=$(body "$WK" POST /sessions -d "{\"namespace_id\":\"$NS\",\"objective\":\"Ship zebracorn\"}" | jget id)
  76. code "$WK" PUT /sessions/$SID/state -H 'If-Match: 0' -d '{"state":{"step":3,"next":"tests"}}' >/dev/null
  77. [ -n "$C1" ] && [ -n "$K2" ] && [ -n "$SID" ] && [ -n "$CB" ] || { echo "data setup failed"; exit 2; }
  78. # ---- full briefing ------------------------------------------------------------------------------------------
  79. R=$(ctx "$WK" "{\"task\":\"zebracorn deploy\",\"namespace_ids\":[\"$NS\",\"$NSSUB\"],\"session_id\":\"$SID\"}")
  80. check "context -> valid JSON" "yes" "$(echo "$R" | jq_ "'yes'" 2>/dev/null || echo no)"
  81. check "constraint loaded by scope" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
  82. check "constraint has policy authority" "policy" "$(echo "$R" | jq_ "[x for x in d['constraints'] if x['id']=='$C1'][0].get('authority')")"
  83. check "unverified constraint excluded by default" "no" "$(has "$C2" "$R")"
  84. check "preference included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$P1' for x in d['preferences']) else 'no'")"
  85. check "decision section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$D1' for x in d['decisions']) else 'no'")"
  86. check "lesson section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$L1' for x in d['lessons']) else 'no'")"
  87. check "knowledge section" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$K1' for x in d['knowledge']) else 'no'")"
  88. 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'")"
  89. check "retired memory excluded" "no" "$(has "$K3" "$R")"
  90. check "unrelated memory not matched" "no" "$(has "$X1" "$R")"
  91. check "duplicate content appears once" "no" "$(has "$KD" "$R")"
  92. check "duplicates counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['duplicates']>=1 else 'no'")"
  93. check "unverified excluded counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['unverified_excluded']>=1 else 'no'")"
  94. 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'")"
  95. check "working state included" "tests" "$(echo "$R" | jq_ "d['working_state']['state']['next']")"
  96. 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'")"
  97. check "used tokens within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=d['budget']['max_context_tokens'] else 'no'")"
  98. check "complete and not truncated" "True False" "$(echo "$R" | jq_ "d['budget']['complete'], d['budget']['truncated']" | tr -d '(),')"
  99. check "counting method declared" "estimate_chars_div_4" "$(echo "$R" | jq_ "d['budget']['counting_method']")"
  100. check "strategy reported" "yes" "$(echo "$R" | jq_ "'yes' if d['strategy'] in ('hybrid','lexical') else 'no'")"
  101. check "tenant B content never included" "no" "$(has 'Tenant B secret' "$R")"
  102. 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'")"
  103. check "UTF-8 round trip" "yes" "$(echo "$R" | python -I -c "
  104. import sys,json
  105. d=json.loads(sys.stdin.buffer.read()); u='Gr\u00fc\u00dfe zebracorn \u65e5\u672c'
  106. print('yes' if any(x['content']==u for x in d['knowledge']) else 'no')")"
  107. # ---- verification filter ------------------------------------------------------------------------------------
  108. R=$(ctx "$WK" "{\"task\":\"zebracorn xylophone\",\"namespace_ids\":[\"$NS\"],\"verification_filter\":\"include_unverified\"}")
  109. 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'")"
  110. check "unverified constraint is not policy" "no" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C2' for x in d['constraints']) else 'no'")"
  111. # ---- budget -------------------------------------------------------------------------------------------------
  112. R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_context_tokens\":100}")
  113. check "small budget -> truncated" "True" "$(echo "$R" | jq_ "d['budget']['truncated']")"
  114. check "small budget -> within budget" "yes" "$(echo "$R" | jq_ "'yes' if d['budget']['used_tokens']<=100 else 'no'")"
  115. check "small budget keeps constraints" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
  116. check "small budget -> over_budget counted" "yes" "$(echo "$R" | jq_ "'yes' if d['omitted']['over_budget']>0 else 'no'")"
  117. check "constraints over budget -> 422" "422" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}")"
  118. check "budget error code" "context_budget_exceeded" "$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":100}" | jq_ "d['error']['code']")"
  119. check "bigger budget fits big constraint" "200" "$(code "$WK" POST /context -d "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"],\"max_context_tokens\":2000}")"
  120. R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"max_items\":1,\"max_references\":0}")
  121. check "max_items caps a section" "1" "$(echo "$R" | jq_ "len(d['knowledge'])")"
  122. check "max_references 0 -> none" "0" "$(echo "$R" | jq_ "len(d['references'])")"
  123. # ---- include and detail -------------------------------------------------------------------------------------
  124. R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"include\":[\"lessons\"]}")
  125. check "include limits sections" "False False True" "$(echo "$R" | jq_ "'decisions' in d, 'references' in d, 'lessons' in d" | tr -d '(),')"
  126. check "constraints always included" "yes" "$(echo "$R" | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
  127. R=$(ctx "$WK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NS\"],\"detail_level\":\"summary\"}")
  128. check "summary detail on knowledge" "True False" "$(echo "$R" | jq_ "'summary' in d['knowledge'][0], 'content' in d['knowledge'][0]" | tr -d '(),')"
  129. check "constraints stay full in summary" "yes" "$(echo "$R" | jq_ "'yes' if 'content' in d['constraints'][0] else 'no'")"
  130. # ---- access -------------------------------------------------------------------------------------------------
  131. check "reader gets briefing" "yes" "$(ctx "$RK" '{"task":"zebracorn"}' | jq_ "'yes' if any(x['id']=='$C1' for x in d['constraints']) else 'no'")"
  132. check "reader can use session read" "200" "$(code "$RK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
  133. R=$(ctx "$BLK" '{"task":"zebracorn"}')
  134. check "no-access principal gets empty briefing" "0 0" "$(echo "$R" | jq_ "len(d['constraints']), len(d['knowledge'])" | tr -d '(),')"
  135. check "no-access session -> 404" "404" "$(code "$BLK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
  136. check "other tenant session -> 404" "404" "$(code "$BK" POST /context -d "{\"task\":\"zebracorn\",\"session_id\":\"$SID\"}")"
  137. check "unknown session -> 404" "404" "$(code "$WK" POST /context -d '{"task":"zebracorn","session_id":"00000000-0000-4000-8000-000000000000"}')"
  138. 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'")"
  139. check "namespace outside grants yields nothing" "0" "$(ctx "$RK" "{\"task\":\"zebracorn\",\"namespace_ids\":[\"$NSBIG\"]}" | jq_ "len(d['constraints'])")"
  140. # ---- validation ---------------------------------------------------------------------------------------------
  141. check "no auth -> 401" "401" "$(curl -s -o /dev/null -w '%{http_code}' -X POST -d '{"task":"x"}' "$BASE/context")"
  142. check "missing task -> 422" "422" "$(code "$WK" POST /context -d '{}')"
  143. check "task without words -> 422" "422" "$(code "$WK" POST /context -d '{"task":"!!!"}')"
  144. check "budget too small -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":50}')"
  145. check "budget not whole -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","max_context_tokens":500.5}')"
  146. check "unknown include -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","include":["bogus"]}')"
  147. check "unsupported format -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","format":"markdown"}')"
  148. check "bad verification_filter -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","verification_filter":"all"}')"
  149. check "bad session id -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","session_id":"nope"}')"
  150. check "bad namespace ids -> 422" "422" "$(code "$WK" POST /context -d '{"task":"x","namespace_ids":["nope"]}')"
  151. check "invalid JSON -> 400" "400" "$(code "$WK" POST /context -d '{"task":')"
  152. check "empty body -> 400" "400" "$(code "$WK" POST /context)"
  153. echo "passed: $PASS failed: $FAIL"
  154. for f in "${FAILED[@]:-}"; do [ -n "$f" ] && echo " FAIL: $f"; done
  155. [ "$FAIL" -eq 0 ]

Powered by TurnKey Linux.