#!/usr/bin/env bash
# Conduct Record walkthrough with curl: seal a mandate, register an agent inventory entry,
# read the mandate in force, then check the returned receipt with the downloadable verifier.
#
# Written 27 October 2026 by an AI agent from the source code. It has not been run against any
# server and has had no human review. Run it with --dry-run first.
#
# Needs: bash, curl, node (node reads the JSON and runs the verifier).
#
#   BASE_URL            your tenant's origin, with no path: https://<your-tenant-host>
#   GOVERNANCE_API_KEY  your key. Read from the environment only. It needs the scopes
#                       governance:mandate, governance:agent_inventory and governance:record.
#   AGENT_REF           optional. Your own opaque agent reference (16 or more characters, 8 or more
#                       distinct, not an email address or a name). Default: a random one per run.
#   IDENTITY_BINDING    optional. A reference to the agent's identity, such as cert:sha256:<fingerprint>
#                       or a DID. Default: a random demonstration reference, which binds to nothing real.
#   OUT_DIR             optional. Where the saved bundles go. Default: ./conduct-record-out
#
# Usage:
#   BASE_URL=https://<your-tenant-host> GOVERNANCE_API_KEY=... ./conduct-record-walkthrough.sh
#   ./conduct-record-walkthrough.sh --dry-run        # prints the requests, sends nothing, needs no key

set -euo pipefail

DRY=0
if [ "${1:-}" = "--dry-run" ]; then DRY=1; fi

BASE_URL="${BASE_URL:-}"
if [ -z "$BASE_URL" ]; then
  if [ "$DRY" -eq 1 ]; then BASE_URL="https://your-tenant-host.example"
  else echo "BASE_URL is not set (a tenant origin, no path)." >&2; exit 2; fi
fi
BASE_URL="${BASE_URL%/}"
API="$BASE_URL/api/v1/governance"

if [ "$DRY" -eq 0 ] && [ -z "${GOVERNANCE_API_KEY:-}" ]; then
  echo "GOVERNANCE_API_KEY is not set. It is read from the environment and is never written to a file or a command line." >&2
  exit 2
fi

rand_hex() { node -e "process.stdout.write(require('crypto').randomBytes($1).toString('hex'))"; }

# 16+ characters, 8+ distinct: 'agt-' plus 16 random hex characters clears the entropy floor.
AGENT_REF="${AGENT_REF:-agt-$(rand_hex 8)}"
IDENTITY_BINDING="${IDENTITY_BINDING:-cert:sha256:$(rand_hex 32)}"
OUT_DIR="${OUT_DIR:-./conduct-record-out}"
IDEM="walkthrough-$AGENT_REF"
if [ "$DRY" -eq 0 ]; then mkdir -p "$OUT_DIR"; fi

json_get() { # json_get <file> <js expression on d>
  node -e "const d=JSON.parse(require('fs').readFileSync(process.argv[1],'utf8'));const v=($2);process.stdout.write(v===undefined||v===null?'':String(v))" "$1"
}

# One request. The key goes to curl on standard input as a config line, so it is never in argv.
call() { # call <METHOD> <path-with-query> <body-or-empty> <outfile>
  local method="$1" path="$2" body="$3" out="$4" url="$API$2" code
  echo "-> $method $url"
  if [ -n "$body" ]; then echo "   body: $body"; fi
  if [ "$DRY" -eq 1 ]; then
    echo '   header: Authorization: Bearer ${GOVERNANCE_API_KEY}'
    echo "   (dry run: nothing sent)"
    return 0
  fi
  local args=(-sS -o "$out" -w '%{http_code}' -X "$method" -H 'Content-Type: application/json' --config -)
  if [ -n "$body" ]; then
    printf '%s' "$body" > "$out.req"
    args+=(--data-binary "@$out.req")
  fi
  code=$(printf 'header = "Authorization: Bearer %s"\n' "$GOVERNANCE_API_KEY" | curl "${args[@]}" "$url")
  rm -f "$out.req"
  echo "   HTTP $code"
  case "$code" in
    2*) ;;
    *) echo "   error body: $(cat "$out")" >&2; echo "Stopped on HTTP $code. 400 invalid_request on a ref means it missed the entropy floor; 403 forbidden_scope means the key lacks a scope." >&2; exit 1 ;;
  esac
}

echo "agent_ref: $AGENT_REF"
echo

# 1. Seal a mandate: what this agent is permitted to do. Never edited; a later one names this in 'supersedes'.
MANDATE_BODY=$(node -e "console.log(JSON.stringify({agent_ref:process.argv[1],permitted_actions:['report.read','email.draft'],idempotency_key:process.argv[2]}))" "$AGENT_REF" "$IDEM-mandate")
call POST "/mandates" "$MANDATE_BODY" "$OUT_DIR/mandate-post.json"

# 2. Register that this agent identity exists. identity_binding is a reference, not a name or an email address.
INV_BODY=$(node -e "console.log(JSON.stringify({agent_ref:process.argv[1],identity_binding:process.argv[2],idempotency_key:process.argv[3]}))" "$AGENT_REF" "$IDENTITY_BINDING" "$IDEM-inventory")
call POST "/agent-inventory" "$INV_BODY" "$OUT_DIR/inventory-post.json"

# 3. Read the mandate in force. This response is flat (receipts and verification_keys at the top
#    level), so it can be saved as it stands and given to the verifier. The write responses above nest
#    the sealed object and carry no verification_keys, so they are not the file to verify.
AGENT_REF_Q="$(node -e "process.stdout.write(encodeURIComponent(process.argv[1]))" "$AGENT_REF")"
call GET "/mandates/in-force?agent_ref=$AGENT_REF_Q" "" "$OUT_DIR/mandate-in-force.json"

# 4. The inventory list returns the newest 200 entries, each self-contained. Save ours as its own bundle.
call GET "/agent-inventory" "" "$OUT_DIR/inventory-list.json"

if [ "$DRY" -eq 0 ]; then
  node -e "
    const fs=require('fs');
    const d=JSON.parse(fs.readFileSync(process.argv[1],'utf8'));
    const e=(d.agent_inventory_entries||[]).find(x=>x.agent_ref===process.argv[2]);
    if(!e){console.error('inventory entry not found in the newest 200');process.exit(1);}
    fs.writeFileSync(process.argv[3],JSON.stringify(e,null,2));
  " "$OUT_DIR/inventory-list.json" "$AGENT_REF" "$OUT_DIR/inventory-entry.json"
  TENANT_DID="$(json_get "$OUT_DIR/mandate-in-force.json" 'd.tenant_did')"
  echo
  echo "mandate decision_id: $(json_get "$OUT_DIR/mandate-in-force.json" 'd.decision_id')"
  echo "grade of the time stamp on the mandate receipt: $(json_get "$OUT_DIR/mandate-in-force.json" 'd.receipts && d.receipts[0] && d.receipts[0].time_attestation && d.receipts[0].time_attestation.grade')"
  echo "saved: $OUT_DIR/mandate-in-force.json and $OUT_DIR/inventory-entry.json"
else
  TENANT_DID="<tenant did from the receipt's tenant_did field>"
fi

cat <<EOF

Verify the receipts yourself, without calling the API again.

1. Fetch the receipt checker (one Node file, no dependencies) and check it against its published hash:
     curl -sS -O https://mysovereignty.digital/downloads/governance-receipt-verifier.js
     curl -sS -O https://mysovereignty.digital/downloads/governance-receipt-verifier.js.sha256
     sha256sum -c governance-receipt-verifier.js.sha256

2. Save the tenant's DID document, and the stored time-stamp token for each receipt (the receipt names
   the token's SHA-256 in its time attestation; send the Authorization header you used above; the key
   goes to curl on standard input from the environment, never in the command line):
     curl -sS https://<host>/.well-known/did.json -o did.json
     printf 'header = "Authorization: Bearer %s"\\n' "\$GOVERNANCE_API_KEY" | curl -sS -K - \\
       "$BASE_URL/api/v1/governance/records/<id>/time-stamp-tokens/<token_sha256>" -o token.tsr

3. Check each saved receipt, pinning the signer to your tenant's DID:
     node governance-receipt-verifier.js "$OUT_DIR/mandate-in-force.json" --did-file did.json --token token.tsr --expect-did "$TENANT_DID"
     node governance-receipt-verifier.js "$OUT_DIR/inventory-entry.json" --did-file did.json --token token.tsr --expect-did "$TENANT_DID"

4. Optional, once a UTC day has closed and been anchored: fetch the anchor proof (Built and deployed; Midnight main-network anchoring was switched on 12 November 2026,
   and as at 16 November 2026 the public estate-root index lists a main-network anchor for every daily root from 5 to 15 November). Until then the route answers 404 not_yet_anchored, which is not a fault. Use the
   mandate's decision_id printed above. The verdict in step 3 never depends on this:
     printf 'header = "Authorization: Bearer %s"\\n' "\$GOVERNANCE_API_KEY" | curl -sS -K - \\
       "$BASE_URL/api/v1/governance/records/<decision_id>/anchor-proof" -o anchor-proof.json
     node governance-receipt-verifier.js "..." --did-file did.json --anchor-proof anchor-proof.json
   The extra line reads anchored or anchor_not_checked. Add --anchor-check <file> (the text printed by
   verify-anchor.mjs) to read the ledger too.

Verdicts and exit codes, as the checker prints them:
  verified 0 (signature and outside time-stamp both check out) | changed 1 | key_mismatch 1 | gap_in_sequence 1
  sandbox_receipt 3 | pq_unconfirmed 3 | key_not_pinned 4 | timestamp_missing 4 | not_understood 4
  signer_did_differs 4 | pq_missing 4 | unanchored_under_withdrawn_key 5 | unknown_version 6 | unreadable 6
Run it with --help for what each means. Add --require-pq to fail a receipt with no post-quantum attestation.
Nothing is sent anywhere. Certificate revocation is not checked, and a pass does not show that a record's
content is true, nor that the mandate is enforced: nothing in the API checks a mandate before an agent acts.
EOF
