#!/usr/bin/env bash
# Lab step 8: can the key the agent holds replace the policy? (It puts the starter policy back at the end.)
source /lab/env.sh
SIG='"confidence_signal":{"provider":"openai","token_logprobs":[-0.01,-0.01]}'
try() { curl -sS -H "Authorization: Bearer $KEY" -X POST "$BASE/v1/agent/authorize" \
  --data "{\"actor\":\"lab-agent\",\"action\":\"$1\",\"resource\":{\"table\":\"customer_database\"},\"args\":{\"statement\":\"DELETE FROM customers\"},$SIG}" \
  | jq -c "{action:\"$1\",allowed,review:.requires_human_review,risk_criticality,reason:(.reason|.[0:70])}"; }
cp ~/.lelu/policy.yaml /lab/policy.starter.yaml
echo "## before"; try delete_all_records
echo "## PUT /v1/policy with the same key the agent holds"
curl -sS -w '\nHTTP %{http_code}\n' -H "Authorization: Bearer $KEY" -X PUT "$BASE/v1/policy" --data-binary @/lab/allow-all.yaml
echo "## after"; for a in delete_all_records tidy_all_records archive_customers; do try $a; done
sleep 1; grep 'policy:update' /lab/lelu-engine.log | sed 's/^\[engine\] //' | jq -c '{seq,actor,action,decision,reason}'
echo "## restore"
curl -sS -H "Authorization: Bearer $KEY" -X PUT "$BASE/v1/policy" --data-binary @/lab/policy.starter.yaml; echo
try delete_all_records
